So here I am with this simple question
Consider these two for cycles and please
explain to me if there's any difference
between the two ways of writing
method 1 :
for(i=(max-1) ; i>=0 ; i--){ do-some-stuff }
method 2 :
for(i=max ; i>0 ; i--) { do-some-stuff }
the reason I'm asking this is because today at school
while we were seeing some Java functions, there was
this palindrome method wich would use as max the
length of the word passed to it and the method used
to cycle trough the for was the first, can anyone
clarify me why the person who writed that piece of
code prefeered using that method ?
Yes, there's a big difference - in the version, the range is [0, max-1]. In the second version, it's [1, max]. If you're trying to access a 0-based array with max elements, for example, the second version will blow up and the first won't.
If the order in which the loop ran didn't matter, I'd personally use the more idiomatic ascending sequence:
for (int i = 0; i < max; i++)
... but when descending, the first form gives the same range of values as this, just in the opposite order.
Both the loops will iterate max times. But the ranges would be different:
First loop's range would be max - 1 to 0 (both inclusive)
Second second loop's range would be max to 1.
Therefore, if you are using i as an array index, or doing some work which is a function of i , dependent of i, then it will create problems for the terminal values (for example 0 is considered in the first one, where as not by the second one). But if you simply want to iterate the loop max nos of times , and do some work which is independent of the value of i, then there is no difference.
Related
I am taking an intro to java course and I am taking a practice quiz. These quizzes are not graded and do not count towards our grade so I thought I would post here.
Under normal circumstances, I would just copy the code and paste it into an IDE but I wanted to know if there is a way to think about this logically so I can figure out the answer. On real exams, we are not allowed to use eclipse or anything like that to figure out an answer and this question would take way too long to do it by hand and count how many times it goes through the for loop.
Here is the question:
How many times does the print statement in the for loop execute?
for(int i = 0; i <347589; i++) {
System.out.print("Give me coffee!");
}
You can basically just take the upper bound of the for loop as an answer, which is 347,589 in this case. To arrive at this answer, consider a for loop with a much smaller bound:
for (int i=0; i < 5; ++i) {
System.out.println("Give me coffee!");
}
By inspection, we can see that this loop will execute when:
i = 0
i = 1
i = 2
i = 3
i = 4
It won't execute when i = 5, because that fails the condition. So, it executes five times, which is the same as the upper bound of the for loop. We can extrapolate this to the loop in your problem to get 347,589 as the answer.
There is no general way to figure out how many times a while loop will execute before running it. This fact is known as the undecidability of the halting problem. For loops are just syntactic sugar for while loops, so this applies to for loops as well. The halting problem is the subject of a great many awesome books, among which Gödel, Escher and Bach by Douglas Hofstadter.
However, the for loop you give is extremely simple: it increases i until i no longer satisfies i < 347589. The variable i starts at 0 and increases one by one: i++ is equivalent to i = i + 1;. So i takes all the successive values: 0, 1, 2, 3, 4, ...,347588 and every time, the line System.out.println("Give me coffee!"); is executed.
Then i takes the value 347589 and no longer satisfies i < 347589, so the loop halts.
In total, "Give me coffee!" was printed 347589 times.
If you don't like the syntax for for loops, your code is equivalent to the following code using a while loop:
int i = 0;
while (i < 347589)
{
System.out.print("Give me coffee!");
i = i + 1;
}
As you have a simple for-loop that executes only one statement multiple times, you can simply count. You might know that the loop starts with i=0 with the first execution and adds 1 after each execution until the condition i<347589 is false. So:
i=0 -> once (1.)
i=1 -> twice (2.)
...
i=347588 -> 347589 times (347589.)
i=347589 -> loop stops.
so the print statement will be executed 347589 times.
In the course they might just want to check your knowledge towards the coding basics. In these type of problems you should notice most importantly 4-5 things.
1- Starting point of index.
2- Ending point of index, also check whether that value in included or not.
3- Increment/Decrement of index, whether index is increased/ decreased by 1 or some other value or pattern.
4- Is their any break statement inside the loop, which will also indicate that loop will run till specific condition.
In the example you gave starting point is 0 and end point is 347589 (excluded) with increment of 1, so loop will run. 347589 - 0 + 1( 0 based index) = 347589 times.
Obviously, FOR loop is not Java specific question.
To understand FOR loop properly let's take an easy example.
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This code will print all number from 0 to 10 (Excluding).
So, the range 0-10 has 10 different values:
0
1
2
3
4
5
6
7
8
9
When i becomes 10 FOR loop statement (i<10) will not be satisfied and the loop will be broken.
So, in you case "Give me coffee!" will be printed 347589 times with the same logic.
I am having such a tough time reading and understanding recursive statements in java.
if my professor shows us code and asks what does this do? what does it return?...I find myself staring at the code as if its going to eventually make sense...but it NEVER does.
examples like---
public static Int mystery(int[][] a, int b) {
int x = 0;
for (int i = 0; i < a.length; i++){
for (int j = 0; j < a.length; i++){
x += (a([i][j] == b) ? 1 : 0;
}
}
return x:
}
what does mystery (a, 8) return where a =
{{6, 4, 5, 8},{4, 6, 4, 8,}, {7, 3, 6, 4,}, {1, 5, 7, 8}}
can someone please explain? thanks!
Hi welcome to the world of programming
This is not recursive programming. Recursive is when a function calling itself.
For example, delete files() -> which will call itself again when there is folder, and you want to delete files under it again and again.
Your example is called a 'Nested Loops' -> Loops of Loops, and the condition 'a.length' being used in both i and j is wrong.
You are trying to loop arrays of arrays, a 3d table. It should be something like this.
int x = 0;
for (int i = 0; i < a.length; ++i){
for (int j = 0; j < a[i].length; ++j){
if (a[i][j] == b) {
++x;
}
}
return x;
Changes:
Try not to use 'ternary operator' ?: as this might confuse you as a beginner.
the max length of inner loop should be a[i]'s length
using ++i is better than i++ if you are not using the value directly.
Imagine
[[1,1,1],
[2,2]]
in your first loop, a[0].length will be 3.
in your second loop, a[1].length will be 2.
as for ++i vs i++:
++i is modifying i directly, making the value +1 instantly
i++ means var b = i; i = b + 1;
it is creating a new temporary variable to hold the original i value.
example:
int i = 0, j = 0;
System.out.println(i++); // will print 0, but i will be 1 moving forward
System.out.println(++j); // will print 1, and j will be 1 moving forward
you will learn more on this in future.
Firstly, if you don't understand something, don't just keep staring at it expecting it to suddenly make sense, as that's likely to just be frustrating. Instead, try to break it down into smaller parts, and work from what you know and expand from that, piece by piece.
That's easier said than done, though. How do you split it up? Here are two approaches: you'll need both.
Low level
One way is to ‘dry run’ the code, instruction by instruction, as if you were the computer. This is slow and tedious, but it gives you the best insight into what the computer is actually doing.
Take a piece of paper, or the virtual equivalent such as a spreadsheet. Make a column for each variable in the method: a, b, x, i, j. (Make the one for a extra wide.)
The method starts with parameters being set, so write the array under a and 8 under b. Next, x is set to 0, so write that under x. Then i is set to 0, and compared to a.length. The array a has four items, the inner arrays, so the length is 4 and the current value of i, 0, is less than that, so the condition is true and we enter the body of the outer loop.
The body of the outer loop contains only the inner loop, which sets j to 0 and compares it to a.length. It's less, so enter the body of the inner loop.
The inner loop body does a few things starting on the right of the =, first working out what a[i] means. Currently i is 0, so that's a[0], which is the first sub array. Then work out a[0][j], which is a[0][0], which is 6. That's not equal to b, so the condition is false: take 0 and add it to the
number under x, 0, and write the result under x to replace the current value. (Replacing 0 with 0? Yes, this doesn't actually change anything.)
Now that you've finished this iteration of the inner loop body, do the i++ (which should probably be j++) by replacing i's 0 with 1. Then do the test again: j is still less than 4, so do the inner loop body again, this time with a[1][0].
I'm going to stop here because it really is tedious, but hopefully you can see the process. The inner loop continues until its condition becomes false, then the outer loop increments i, starting the inner loop again but this time looking at a[1][0], a[1][1], and so on. That continues until the outer loop also makes its condition true. Finally, the last value of x is returned, and if you go through all the steps you'll get the same result the computer would. (Try it: once you get the hang of it, it'll be quicker than reading through the above, thank goodness.)
Okay, so that gives you the same sequence of steps the computer takes, and sometimes that level of detail is invaluable, especially when you have a bug such as assigning to the wrong variable name. But you may still end up not knowing why those particular operations, not seeing the wood for the trees. How can you work out what the purpose of the algorithm is?
High level
Another way we can look at the method is to work out what each statement does, and what the possible cumulative effect could be. For instance, the outer loop steps through each of the nested arrays, and the inner loop steps through each number within a nested array: so in combination, they step through every number within the array a. So something is happening with all the numbers.
Also, x is set to 0 at the start, and within the loops it sometimes has 0 added and sometimes 1. That tells us it's a counter, and by the end it'll tell us how often the condition was true: that is, how many of the numbers within a are equal to b. And so that's what the method returns: how many times b appears in a.
We can also tell the minimum value returned (0, when none of the numbers match), and the maximum (the total count of numbers, because at most 1 is added for each of them).
This is much more useful: we know what the method can be used for, and we can work out what the worst cases are: if we give it more than four billion numbers, a 32-bit int for the result wouldn't be enough, for instance; but it won't run forever (assuming j++) because the array has a fixed size, and it won't run out of memory because it doesn't allocate any other than for the variables.
But you need to be careful with this approach, because it's easy to make assumptions and miss details that change the outcome significantly: use the wrong kind of comparison or the wrong variable, or forget to clear a total, say, and you can end up with code that doesn't do what you think it does.
That can result in some of the most annoying bugs, when you stare at your code and you're sure it's right but somehow it still gives you the wrong answer. When that happens to you, switch to dry-running, re-examine your assumptions, or show your code to someone else: without your high-level knowledge of what the code should do, they can spot what it actually does.
Ultimately this is all a skill that you'll learn with practice, so keep writing and reading code.
public static void findNumber(int number) {
int[] soretedArray = { 1, 5, 6, 8, 9 };
for (int i = 0; i <= soretedArray.length; i++) {
for (int j = i + 1; j < soretedArray.length; j++) {
if (soretedArray[i] + soretedArray[j] == number) {
System.out.println(soretedArray[i] + "::" + soretedArray[j]);
return;
}
}
}
}
Using this code I am able to find the number and its complexity is O(N^2) but I have to find this using O(N) complexity i.e using only one for loop or hash-map or similar in Java.
I remember, I was watching the official Google video about this problem. Although it is not demonstrated in java, it is explained step-by-step in different variations of the problem. You should definitely check it:
How to: Work at Google — Example Coding/Engineering Interview
As explained in the Google video that Alexander G is linking to, use two array indexes. Initialize one to the first element (0) and the other to the last element (sortedArray.length - 1). In a loop, check the sum of the two elements at the two indexes. If the sum is the number you were looking for, you’re done. If it’s too high, you need to find a smaller number at one of the indexes; move the right index one step to the left (since the array is sorted, this is the right way). If on the other hand, the sum you got was too low, move the left index to the right to obtain a higher first addend. When the two indexes meet, if you still haven’t found the sum you were looking for, there isn’t any. At this point you have been n - 1 times through the loop, so the algorithm runs in O(n).
We ought to first check the precondition, that the array is really sorted. This too can be done in O(n), so doing it doesn’t break any requirements.
The algorithm may need refinement if you are required to find all possible pairs of numbers that yield the desired sum rather than just one pair.
Is this answer superfluous when the video link has already said it? For one thing, my explanation is shorter, so if it suffices, you’re fine. Most importantly, if the video is removed or just moved to another URL, my answer will still be here.
With fixed number, for any chosen x in the array you just have to find if number-x is in the array (Note that you can also bound x). This will not give you O(n), but O(n.log(n)).
Maybe by remarking that if you have a_i and a_j (j>i), taking the sum and comparing against number, if the result is greater next interesting tests are with a_(i-1) or a_(j-1), and if result is lower next interesting tests are with a_(i+1) or a_(j+1), will give hint to linear-time?
I'm really new to Java and am just struggling with arrays a little bit. I've got a block of code that I've written when following a tutorial but am struggling to understand it and would love if someone could explain it to me.
I've tried working through it with various different methods (explaining to my duck, writing it down, etc.) and still can't get my head around it. I normally wouldn't ask and I always try desperately hard to work it out myself, but I just can't figure it out this time.
int[] values = new int[3];
values[0] = 10;
values[1] = 20;
values[3] = 30;
for(int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
I understand why:
The for loop iterates through the values in "values".
The loop keeps looping until i is less than the last value in the array.
But what I don't understand is why I need to write values[i] in the System.out.println() statement. What tells Java that i can be used in the array values[]?
Sorry if this is a trivial question for you but this is the best place I could think of to turn.
Java knows that values is an array type. Arrays in Java are indexed by integers, so here we have an integer called i. i goes from 0 to less than values.length (in this case is 3). So i will be 0, 1, and 2.
Indexing values with 0, 1, and 2 are equivalent to:
values[0]
values[1]
values[2]
Since JAVA is not a mind reader, unless you tell java value of which index you want to print JAVA will not be able to understand :)
So you have mention index like values[0] ,values[1] etc
values is the array name and 'i' is the index.
values[0] will print 10. values[1] will print 20.
Refer these links for more information:
http://www.homeandlearn.co.uk/java/java_arrays.html
http://www.javatpoint.com/array-in-java
Also learn how to debug the java code.
Let me try to explain in a simple way:
As soon as you use the statement:
int[] values = new int[3];
and assign values to it there will be three blocks of memory of integer size in memory.
as i is initialized to zero and each iteration in the for loop,
will execute the statement System.out.println(values[i]);
It will just substitute current value of i in values[i] that is values[0] for first round etc.
So it will check for already assigned values in the memory I talked about earlier and print it.
The System.out.println(values[i]); Tells the system to print the value at the given index in the array.
If we say System.out.println(values[0]);, the value at index 0 which is 10 is printed.
To print out all the values in the array, instead of typing the index for each value manually like values[1], values[2]. We use a for statement for(int i = 0; i < values.length; i++) creates a variable i and assigns it a value 0, so on the first run through the loop,values[i] is values[0].
After the first run through the loop, the i is incremented from 0 to 1 because of the i++ part of the for statement. on the second run values[i] is values[1] and what is printed is the value at index 1 which is 20. This continues as long as i < values.lenght; returns true.
I've been searching on google, and couldn't find a a similar question or explanation.
Assume the following code:
int out, in;
for(out=nElems-1; out>1; out--)
for(in=0; in<out; in++) {
if( a[in] > a[in+1] )
swap(in, in+1);
}
Why does the outer loop stops when after the outer value reaches 1? Isn't it supposed to have 2 elements left? The 0 and 1 places? What makes us so sure that they are already sorted?
I understand how the Algorithm work, and realise there would be a better solution with a flag that stops if no iteration are done, but I'm really interested in understanding the above code.
So, i am afraid the book code doesn't work, let's prove it by example:
Array ={3,2,1};//nvm the syntax, i assume pseudocode because we don't even know what is swap()
nElems=3;
For: out=2;
For:in=0
check 0 and 1
Array={2,3,1}
in=1
check 1 and 2
Array={2,1,3}
in=2, break;
out=1, break;
You can see the flow ended with array {2,1,3} which is not sorted. So even books may have errors, or maybe if you read few pages ahead you might find out it was intentional. Correct bubble sort would have condition out>=1 or out>0
EDIT: with array consisting of 2 elements, the algorithm will do nothing, even simplier proof
Array ={2,1};
nElems=2;
For: out=1, break;//out = nElems-1, 1>1 is false
When out reaches 2, the inner loop goes from 0 to 1. It makes sure the two elements at [0] and [1] are in the correct order - this is the time to stop bubble sorting. However, the code you presented above will then compare [1] and [2] - resulting in a potential swap leading to unsorted array (as [0] and [1] should be compared again, after [1] and [2] are compared). For this code to work, the outer loop should go downto 1 inclusive, so for (out = nElems - 1; out > 0; out--).
What you need to see here is the fact, that in bubble sort the inner loop is doing the actual job of sorting (by swapping the elements). The outer loop is just setting the limit beyond which all elements are already sorted.