Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Recently in class, there was a recursion function that returned an array as either being true or false (sorted or not). However, I had trouble understanding it. The function is:
int[] array = { 3, 5, 2, 57, 8, 20 };
int start=0;
boolean sorted = sorted( array, start, array.length );
System.out.print( "array: ");
for ( int i=0 ; i<array.length ; ++i ) System.out.print( array[i] + " " );
if (sorted) System.out.println(" is sorted" );
else System.out.println( "is not sorted" );
static boolean sorted(int array[], int i, int count ) {
if (count == 1 || count == 0) return true;
if (array[count - 1] < array[count - 2]) return false;
return sorted(array, i-1, --count);
}
What is happening in the method and how is the recursion working? What does the variable count do if there is already an integer i? Why must it be equal to 0(or null) and 1? Why are the variables different for when you initialize "sorted" in the main method and for the sorted method? I believe some of the additional questions I asked may be redundant or unnecessary if I knew how the whole method worked. I would really appreciate your help!
First of all, welcome to the forum! :) Indubitably, recursion is something that's really difficult to come to grips with, but if you have learned about stack - as a part of the memory - you can understand recursion more easily. This article might appear useful in investigating what exactly happens in these types of algorithms.
The code might not be written in Java, but the syntax itself will be fairly understandable. I suggest you skip the memoization part - since it is more advanced and you can learn it later -, but the factorial code and the image are really self-explanatory.
You could also practice and write these algorithms and I agree: debugging is excessively useful if you don't understand something.
Finally, let me add some practical pieces of advice in the future for coding in Java:
Auto-format your code (the hotkeys are different in every major IDE's, but they definitely exist)
Avoid C-style coding when declaring arrays:
instead of
int array[]
, Java devs tend to do it in the following way:
int[] array
(Fun fact about multidimensional arrays: int[][] array, int array[][] and int[] array[] (!) work too.)
Last, but not least, do not miss curly braces also if there is only one statement in that particular block of code.
These are only coding conventions, though that code is syntactically alright, as you might have already seen it.
Happy coding!
The sorted method could just be:
static boolean sorted(int array[], int count) {
if (count == 1 || count == 0) {
// If the array has no elements or if it just has a single element,
// then it means that the array is sorted.
return true;
}
if (array[count - 1] < array[count - 2]) {
// If an element is less than the previous element,
// then the array is not sorted.
return false;
}
// check rest of the array.
return sorted(array, count-1);
}
I would suggest you to debug through the whole code so that you could get a better picture of what is happening.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
i need to sort an array of the type intgere in a basic way (nothing too complex) for a school computer science project. It would be nice if sb could give me not only a one sentence answer waht to consider but also some code i can work with.
thanks a lot.
You could've either googled it but since you didn't, use this bubblesort method:
boolean swapped; // to notice swaps during a pass
do {
swapped = false;
for (int i=1; i<a.length; i++)
if (a[i-1] > a[i]) {
// Swap!
int swap = a[i];
a[i] = a[i-1];
a[i-1] = swap;
swapped = true;
}
} while (swapped); // another pass if swaps happened
It swaps the ints next to each other until you have them sorted from the smallest to the greatest number. If you want it the other way around simply swap the ">" with a "<".
I hope that will help you.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
public static boolean sum_rec(int[] A, int n, int k) {
return addition(A, n, k, 0);
} // end sum_rec
private static boolean addition(int[] A, int n, int k, int i) {
if (k == A[i] + A[n - 1 - i]) {
return true;
}
else if (n == 1){
return false;
}
else
return addition(A, n, k, i++);
}
Hi, I am getting stackoverflow error whenever I try to run the following code. It returns true if there are any two numbers in array that sum up to a value k but I cant seem to find the error. Any help will be appreciated. Also what is the running time of this?
You need a base case that will end the recursion (return false) in the case that
k == A[i]+A[n-1-i]
is never true.
n == 1 is not that base case since n doesn't change during the recursion ... a base case that depends on the variable that changes during recursion
There are multiple problems with your code. One that hasn't been pointed out yet is that you think you're calling the method recursively by adding 1 to the last parameter, but you're not. This line:
return addition(A, n, k, i++);
has a post-increment operator. This means that it will add 1 to i but it will use the old value of i as the parameter. So it's the same as:
int oldValueOfI = i;
i = i + 1;
return addition(A, n, k, oldValueOfI);
You can see that you're calling the method recursively with the exact same values that it was called last time, so of course it will recurse infinitely. Although I wouldn't use recursion for this program, if you really want to, change the call to
return addition(A, n, k, i + 1);
You're not going to use i afterwards, so you don't need to change the value. (Note that each recursive call has its own i variable; the variable is not shared between the calls. So incrementing i will not have any impact on the i used by the next recursive call, the previous recursive call, or any other recursive call.)
Also note that this will not solve your problem, but making this change might help you figure out what to do next when your program starts blowing up on a different exception.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am practicing Java and working on arrays. As arrays size can not be changed in run time, is it possible to make 2 arrays and in run time keep storing input in the first of and then when it is full, then move to the second array by if statement. I'm basic in Java so hope my code is in the right direction. Anyway it does not work but I just want to share my idea and see if it can work.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] arr1 = new int[5];
int[] arr2 = new int[10];
while(in.hasNextInt())
{
for(int i = 0; i <= arr2.length; i++)
{
if (i <= arr1.length) { arr1[i] = in.nextInt(); }
else arr2[i] = in.nextInt();
}
}
}
You should change your code to the following:
if (i < arr1.length) { arr1[i] = in.nextInt(); } //"<" instead of "<="
else { arr2[i - arr1.length] = in.nextInt(); } //decrement i by the size of the first Array
As denoted in the other answer/answers, there are plenty of more practical ways to do what you are trying to achieve, but non the less the above should let your code work as inteded.
This is not a good idea. If the second array overfills, you'll have problems such as exceptions and lost data.
I recommend using the ArrayList.
You can create one:
ArrayList<Integer> list=new ArrayList<>();
and add to it with:
list.add(new Integer(in.nextInt()));
With autoboxing you can skip the creation of an integer reference object and use:
list.add(in.nextInt());
Anyway it does not work ...
Yea. Pretty obviously.
... but I just want to share my idea and see if it can work.
No. Pretty obviously.
Sure you can put elements in the second array when the first array. But then you run into the same problem all over again when when the second array fills up.
The best solution is to use an ArrayList<Integer> (... or any kind of List<Integer>). That will take care of the problem of "growing" the list transparently and automatically.
If you insist on doing this with arrays, then the solution is to:
dynamically allocate a "new" array that is bigger than the "current" array,
copy the elements of the "current" array to the "new" array, and
assign the reference for the "new" array to the "current" array variable.
In fact, you could do all of this using Arrays.copyOf(int[], int).