java Recursion row - java

i'm getting lost, could someone of you please help me?
i want my function "oddEvenRow" to check if the values in row index 0,2,4 are odd. if so return true, if not return false
this is the code i wrote :
public class Matrix
{
public static int temp=0;
public static boolean oddEvenRow (int[][]a, int r, int c, int count)
{
if(r>4&&count==12) {
temp=1;
return false;
}
if(a[r][c]%2==0) {
temp=1;
return false;
}
else {
count++;
if(c==3)
oddEvenRow(a,r+2,0,count);
else
oddEvenRow(a,r,c+1,count);
return true;
}
}
public static void main(String args[])
{
int r=0;
int c=0;
int count=0;
int[][]a=new int[5][4];
a[0][0]=1;
a[0][1]=3;
a[0][2]=7;
a[0][3]=15;
a[1][0]=4;
a[1][1]=15;
a[1][2]=2;
a[1][3]=9;
a[2][0]=11;
a[2][1]=21;
a[2][2]=1;
a[2][3]=45;
a[3][0]=8;
a[3][1]=15;
a[3][2]=8;
a[3][3]=12;
a[4][0]=7;
a[4][1]=3;
a[4][2]=25;
a[4][3]=21;
System.out.println(oddEvenRow(a,r,c,count));
}
}

[Looking at your code, i suspect you meant your question to say "if ALL values in rows 0,2, and 4 are odd..."]
Anyway, you're setting the short circuit variable 'temp' but never using it. Try adding a check to the top of your function...
if(temp == 1)
return false;

For me the part with count is redundant as you are checking all rows in r variable - after the last significant row (4th) the method will return. You do not need checking if there were 12 numbers checked.
What is more temp variable acts as return value in your code which you are actually returning with the method itself - also redundant.
I do not see the point in checking already defined number of values using recursion but if you need so consider the following:
public static boolean oddRow(int[][] a, int r, int c) {
//checking if we checked all rows
if (r > 4) {
return true;
}
//checking if all columns in row were checked and moving to r+2 row
if (c > 3) {
return oddRow(a, r + 2, 0);
}
//checking if current value is odd - if yes, keep checking the rest / if not, return false
return (a[r][c] % 2 == 0) ? oddRow(a, r, c + 1) : false;
}

Related

Storing an integer, adding to itself, and using it as a parameter in a method in java

I have a problem where I have to store an integer, if a user answers Y, from an input and then using it on a method, storing that integer and then adding it to a different input from the user. The total will be used on the same method and printed only if the user inputs N.
For instance,
Y
input =3
method(input)
Y
input = 4
method(input)
N
total = 3+4
method(input, total)
I have most of the code already, I just want to know if it is possible to get the total and use it on the method
Edit: here is the code
public static boolean walk(boolean bool, String answer) {
while(bool==true) {
if (answer.equals("Y") || answer.equals("y")) {
return bool=true;
}
else if (answer.equals("N") || answer.equals("n")) {
return bool=true;
}
}
return bool;
}
public static boolean continueWalking(boolean bool, String answer, int average) {
while(bool==true){
if (answer.equals("Y") || answer.equals("y")){
return bool=true;
}
else if(answer.equals("N") || answer.equals("n")){
System.out.println("Great exercise!");
System.out.println(average);
System.exit(0);
}
}
return bool;
}
while(bool) {
System.out.println("Do you want to start/continue walking?");
String continueWalk=input.next();
int totsteps=numberOfSteps;
continueWalking(true, continueWalk,totsteps);
System.out.println("How many steps do you want to walk in this section?");
totsteps=numberOfSteps + numberOfSteps;
int numberOfSteps = input.nextInt();
NumOfsteps(numberOfSteps,1);
}
Just a couple of syntax/formatting things to start with:
your while statement while(bool==true) can be changed to just while(bool). A while loop statement just needs to evaluate to a boolean in Java, and boolean bool is already a boolean. You can do a similar thing for your return statements, change them to return bool;
To answer your question, to update an int value in Java, use +=.
int test = 0;
test += 1;
System.out.println(test); // Prints out 1
In your code, declare totsteps outside of the while loop, and change the line int totsteps=numberOfSteps; to totsteps += numberOfSteps;

return int from within if statement in a loop in java

i have a loop which iterates equal to the length of an array, inside this loop i have a method which do some processing and have if-else structure inside. i want that if certain condition is true, then re-iterate the whole loop else continue.
the Minimum working code is provided.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
fp.factprocess(fact, rule, vars, cons);
}
contents of fp.factprocess are like
if(condition==true)
make xx = 0 in the parent loop
else
continue
i dont know how do i do it, i used return statement but it has to be in the end and can not be in the if-block.
Return a boolean from the condition test. If boolean true, set xx to -1 (to be incremented to 0) in the loop.
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
boolean setXXtoZero = fp.factprocess(fact, rule, vars, cons);
if(setXXtoZero) xx=-1;
}
fp.factprocess:
return condition;
Yes, there can be a return statement in the if block.
public int getValue(int val){
if ( value == 5 ){
return value;
}
else{
return 6;
}
}
for instance, is valid Java code.
public int getValue(int input){
if ( input == 5 ){
return input;
}
}
on the other hand, is not, since you don't return anything if input does not equal 5, yet the method has to either return an int, or throw an Exception.
That's probably what your problem is: you need to provide a return statement for all possible scenario's.
If you want to modify the xx variable of the loop, I suggest to return a boolean in your factprocess method.
for (int xx = 0; xx < temp.length; xx++) {
rule = temp[xx][1];
cons = temp[xx][2];
boolean shouldRestart = fp.factprocess(fact, rule, vars, cons);
if (shouldRestart) {
xx = 0;
}
}
Pass xx to factprocess() and assign the return to xx
for(int xx=0;xx<temp.length;xx++)
{
rule=temp[xx][1];
cons=temp[xx][2];
xx = fp.factprocess(fact, rule, vars, cons, xx);
}
Inside factprocces()
if (condition == true) {
return 0
} else {
return xx
}

Java Program does not give the output for values of n>6, Why?

import java.util.*;
class A{
static int count=0;
static String s;
public static void main(String z[]){
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println(noOfBouncy(n));
}
public static int noOfBouncy(int k){
int limit=(int)Math.pow(10,k);
s=new String("1");
int num=Integer.parseInt(s);
while(num<limit){
if(isIncreasing(s) || isDecreasing(s) ){
}
else{
count++;
}
num++;
s=new String(Integer.toString(Integer.parseInt(s)+1));
}
count=limit-count;
return count;
}
}
public static boolean isIncreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)>s.charAt(i+1)){
return false;
}
}
return true;
}
public static boolean isDecreasing(String s){
int len=s.length();
for(int i=0;i<len-1;i++){
if(s.charAt(i)<s.charAt(i+1)){
return false;
}
}
return true;
}
I have given the definitions to the two functions used isIncreasing() & isDecresing()
The program runs well for the value of n<7 but does not respond for values above it, Why ?
I accept the programming style is very immature,please ignore.
I've tried to execute it with n=7 and it finishes in 810ms, returning 30817.
However, I recommend to you to optimize the performance of your program by saving unnecessary object instantiation: It will be better if you maintain the counter in num, and convert it to string just once, at the beginning of the loop:
int num=1;
while (num < limit)
{
s=Integer.toString(num);
if (isIncreasing(s) || isDecreasing(s))
{
}
else
{
count++;
}
num++;
}
Like this it takes just 450ms to finish.
The program was not actually stuck but it is taking way too much time to complete its execution when value of 'n' is larger.
So now the question is, I need to optimize the code to take minimum time #Little have an optimization bit that's not enough.
Any hint would be appreciable.
To increase the performance you should avoid the conversation to String and do the check with numbers.
As it doesn't matter for the result if you start the comparison from left to right or from right to left one computational solution could be.
as pseudo code
1) compare the value of the right most digit with the digit on it's left
2) is it lower --> we found a decreasing pair
3) else check if it is bigger --> we found an increasing pair
4) else --> not a bouncy pair
5) if we found already one decreasing and one increasing pair it's bouncy number
6) divide the number by ten if it's bigger then ten repeat with step 1)
The method to check if it's a bouncy number could look like this
static boolean isBouncyNumber(int number) {
boolean increasingNumber = false;
boolean decreasingNumber = false;
int previousUnitPosition = number % 10;
int remainder = number / 10;
while (remainder > 0) {
// step 1
int currentUnitPosition = remainder % 10;
if (currentUnitPosition > previousUnitPosition) {
// step 2
decreasingNumber = true;
} else if (currentUnitPosition < previousUnitPosition) {
// step 3
increasingNumber = true;
}
// step 5
if (decreasingNumber && increasingNumber) {
return true;
}
// step 6
previousUnitPosition = currentUnitPosition;
remainder = remainder / 10;
}
return decreasingNumber && increasingNumber;
}

if condition to check if only one variable is set of the four variables at any point in JAVA

I want to display an error if more than one of the four variables is set...
In Java..this is what I came up with..
if( (isAset() && isBset()) || (isBset() && isCset()) || (isCset() && isDset()) || (isDset() && isAset()) )
attri.greedySelectionException(..);
I wanted to check if there is a better way of doing this..?
How about you use a counter and then compare it to 1?
Something like...
int i = 0;
if (isAset()) i++;
if (isBset()) i++;
if (isCset()) i++;
if (isDset()) i++;
if (i > 1)
...
Alternatively, if you are checking properties of a certain object, you could use some reflection to iterate through the relevant properties instead of having one if statement per property.
Edit: Take a look at Marius Žilėnas's varargs static method below for some tidier code, i.e. using (changed the oldschool for to a for-each and the ternary expression for an if):
static int trueCount(boolean... booleans) {
int sum = 0;
for (boolean b : booleans) {
if (b) {
sum++;
}
}
return sum;
}
instead of several if statements.
You can simplify this expression with :
if((isAset() || isCset()) && (isBset() || isDset()))
attri.greedySelectionException(..);
Wolfram alpha made the work for you :
Original expression
You can verify with the truth tables :
Original
Final
In Java 8 you can solve this problem with Streams in an elegant way (assuming your values are null if they are not set):
if (Stream.of(valueA, valueB, valueC, valueD).filter(Objects::nonNull).count() != 1) {
/* throw error */
}
If you have control on the implementation of isAset(), isBSet, isCSet, & isDset methods, you can achieve this with much more clarity if you return 1 or 0 instead of true or fales from this functions. These functions are to be created as below...
public int isAset()
{
return (A != null) ? 1 : 0;
}
To verify if more than one variable is set use use something like below...
if( isASet() + isBSet() + isCSet() + isDSet() > 1)
ThrowMoreAreSetException()
If you don't have control on this here is another way of doing it...
int count = isASet() ? 1 : 0;
count+= isBSet() ? 1 : 0;
count+= isCSet() ? 1 : 0;
count+= isDSet() ? 1 : 0;
if(count > 1)
ThrowMoreAreSetException()
By following either of these approches, code will be less clumsy and more readable than doing somany comparision combinations.
I suggest using varargs ... (see Java tutorial) and make a function that calculates how many trues was given. The following code to demonstrates it:
public class Values
{
public static boolean isASet()
{
return false;
}
public static boolean isBSet()
{
return true;
}
public static boolean isCSet()
{
return true;
}
public static boolean isDSet()
{
return true;
}
public static int booleans(boolean... booleans)
{
int sum = 0;
for (int i = 0; i < booleans.length; i++)
{
sum += booleans[i] ? 1 : 0;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(
booleans(isASet(), isBSet(), isCSet(), isDSet()));
if (1 < booleans(isASet(), isBSet(), isCSet(), isDSet()))
{
System.out.println("Condition met.");
}
}
}
Try this:
if (!(isAset ^ isBset ^ isCset ^ isDset))
This will true only is any one is true or else false.

How to avoid repetition in array filling

I have the next code and what I want to do is to check whether I have a value inside an array or not. The problem is, my code does the comparison just between the value I give as a parameter and the last value in the array, what I want to check is to see of I have the value and then return the boolean true, but my code just compare last value in the array. The code is here:
public boolean trueIdTienda(String s) {
boolean f = false;
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())) {
f = true;
} else {
f = false;
}
}
return f;
}
This part is not needed:
else {
f = false;
}
Since if one of them match it is a match, you don't need to set it back to true. Also you could return after a match, to speed the code up a bit (and more logical).
If you let the else part stay there, it will set the value back to false once it find a non-equal. Consider finding [1, 2] for 1 and you will see.
This is a classic search algorithm:
public boolean trueIdTienda(String s) {
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())){
return true;
}
}
return false;
}
Your function can be simplified to immediately return true if the value is found.
public boolean trueIdTienda(String s) {
for (int x = 0; x < lista.size(); x++) {
if (s.equals(ventas.getVenta(x).getIdTienda())) {
return true;
}
}
return false;
}
Maybe you can use a Collection. something like a Hash should help you
http://www.java2s.com/Tutorial/Java/0140__Collections/Createuniquelistsofitems.htm
The problem is that although you find that a value in the array is equal to the argument you set the boolean true and continue comparing with other values which return the boolean to false.
Final value of the boolean is the result of comparing with the last value, what solves the problem is to add break; after f=true;
Try to understand what caused your problem not simply using a correct code.

Categories

Resources