Given int[] arr = [7, 2, 5, 2]; and int index;, how can I use a for loop to make sure that index is assigned to 1 (the first index at which 2 was observed in arr) and not 3 (the last index at which 2 was observed in arr)?
I'm thinking using a break; statement but I'm not sure how to implement the syntax.
You can add every array value to a hashmap with the value as key and the index as value, that way if a key already exists you know at which index it was.
Alternatively you could also have the hashmap value be a list so you can store for each value, all of the indexes in which is appears in the array.
If you're using embedded for loops (the suggested answer when you search this question) one of your loop counters will point to the first instance while the second will point to the second instance. Just use the correct variable.
You can break a for loop once you've found what you want, like this:
for (int i = 0; i < arr.length; i++) {
if (foundDuplicate()) {
break;
}
}
// You end up here after the break
This gets you out of the for loop
You can also find the duplicate whichever way you want and then iterate over the array until you find the first instance.
Depends on what arbitrary rules have been placed on this exercise
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.
In a class I have a private array
private boolean[][][] array;
that is later declared as
array = new boolean[2][100][100]; //*
At a certain point I want to overwrite the first array in the first dimension with the second array of the first dimension. I assumed this should work
array[0] = array[1];
but this yielded wrong behavior. I tried this plain for-loop:
for (int column = 0; column < array[0].length; column++) {
for (int row = 0; row < array[0][0].length; row++) {
array[0][column][row] = array[1][column][row];
}
}
and it worked as expected.
Why didn't the first snippet of code work?
*The first dimension is static at 2 but the other actually come from another array. I removed them for clarity.
The first snippet of code did not work because it does not copy the array dimension, it aliases it. Arrays are objects, so the assignment creates a second reference to the same dimension, and assigns it to the first dimension. That is why you get a different (and incorrect) behavior.
Here is an illustration of what is going on:
The assignment drops the 100x100 array from the top dimension at index zero, and replaces it with a reference to the 100x100 array at dimension 1. At this point any modification to the first array get reflected in the second array, and vice versa.
If you do not care about keeping the prior version of the array after re-assignment, you can assign a brand-new array to element 1, like this:
array[0] = array[1];
array[1] = new boolean[100][100];
This line
array[0] = array[1];
States that the object reference stored in array[1] will be now also stored in array[0]. Since an array in Java is an object reference, now both array[0] and array[1] point to the same location.
If you want/need to clear the data of an array, use a loop: for, while, do-while, the one you feel more comfortable.
Well, i don't think that you can perform copy or even a simple call unless you address you array in "proper way".
So something like
array[0]=array[1];
or
array[0][1]=array[1][1];
won't work but if you write
array[0][0][0]=array[1][0][0];
it will work, i'm guessing because the compiler is sure you are talking about the same array here.
This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Closed 7 years ago.
Lets say that i have an array which i would like to iterate over:
int[] someArray = {1,2,3,4}
for (int i = 0; i < someArray.length; i++) {
// do stuff
}
Will this length of aray be caclulated with each iteration or it will be optimized to calculate it only once ?
Should i iterate arrays by calculating the length in advance and pass that to a loop ?
for (int i = 0, length = someArray.length; i < length ; i++) {
// do stuff
}
From JLS 7
10.7 Array Members
The members of an array type are all of the following:
• The public final field length, which contains the number of components of
the array. length may be positive or zero.
Coming back to your question,java doesn't recount the number of elements in array on array.length. It returns the value of public final int length, calculated during array creation.
As always for performance: write the simplest code you can, and test it to see whether it performs well enough.
If you only need the element (and not the index) I would encourage you to use the enhanced-for loop:
for (int value : array) {
...
}
As per JLS 14.14.2 that's basically equivalent to your first piece of code, but the code only talks about what you're actually interested in.
But if you do need the index, and assuming you don't change array anywhere, I believe the JIT compiler will optimize the native code to only fetch the length once. Obtaining the length is an O(1) operation, as it's basically just a field within the array, but obviously it does involve hitting memory, so it's better for the eventual code to only do this once... but that doesn't mean that your code has to do this. Note that I wouldn't expect the Java compiler (javac) to perform this optimization - I'd expect the JIT to.
In fact, I believe a good JIT will actually see code such as:
for (int i = 0; i < array.length; i++) {
int value = array[i];
...
}
and be able to optimize away the array bounds checks - it can recognize that if it accesses the same array object all the time, that can't possibly fail with an array bounds error, so it can avoid the check. It may be able to do the same thing for more "clever" code that fetches the length beforehand, but JIT optimizations often deliberately target very common code patterns (in order to get the biggest "bang for buck") and the above way of iterating over an array is very common.
As length is the member of Array So it is already been set when you create an Array , On Each iteration you are only accessing that property nothing else .
So either you access it like
int myArrayLength=arr.length;
for(int i=0;i<myArrayLength;i++)
or like :
for(int i=0;i<arr.length;i++)
There will be no measurable performance change .
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.