please help me out its very confusing java code - java

public class Test {
public static void main(String[] args) {
int arr[] = {1,2,3,4};
int i=0;
while (i<20)
{
System.out.println(arr[?]);
}
}}
what should we write in place of ? so that ArrayIndexOutOfBounds exception do not occur and the output is as follows?
1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4

Use modulu 4, since that would give you integers between 0 and 3, which are the indices of your array :
System.out.println(arr[i%4]);
But don't forget to increment i.
int arr[] = {1,2,3,4};
int i=0;
while (i<20)
{
System.out.println(arr[i%4]);
i++;
}
A more succinct solution (though less readable in my opinion), would be to combine the two statements :
System.out.println(arr[(i++)%4]);

You want the array index to always be one of {0, 1, 2, 3}.
The mod n (%n) operation will get you result among [0, n-1].
So you can write it like:
System.out.println(arr[(i++)%4]);

With this solution one can vary the length of the array. And 'i' can take any value. So that Array Index Out Of Bound exception do not occur.
System.out.print(arr[i++%arr.length]);

Related

Getting unexpected position value from binarySearch method in java

Currently working with java basics.While learning I've written the following code.
import java.util.*;
class RemoveDuplicates{
public static void main(String[] args) {
int[] arr = {1,2,3,1,5,2,3};
int[] out = {1,2,3,1,5,2,3};
for(int each : arr){
System.out.println("Element "+each+" at "+Arrays.binarySearch(out,each));
}
}
}
My expected output:
Element 1 at 3
Element 2 at 5
Element 3 at 6
Element 1 at 3
Element 5 at 4
Element 2 at 5
Element 3 at 6
My actual output:
Element 1 at 3
Element 2 at 5
Element 3 at 6
Element 1 at 3
Element 5 at -8
Element 2 at 5
Element 3 at 6
In my actual output at element 5 why I'm getting -8 from Arrays.binarySeach(out,each) function?
Explain me this please.
Always remember for binary search to work you must sort the array.
Use can use Arrays.sort() for sorting
import java.util.*;
class RemoveDuplicates{
public static void main(String[] args) {
int[] arr = {1, 2, 3, 1, 5, 2, 3};
int[] out = {1, 2, 3, 1, 5, 2, 3};
Arrays.sort(out);
for(int each : arr) {
System.out.println("Element "+each+" at "+Arrays.binarySearch(out,each));
}
}
}
If u want to use binary search, u should sort the array first.
add
Arrays.sort(out);
Besides, FYI, there is no guarantee for multiple elements.
here's some infs for Arrays.binarySearch(int[], int)
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

Why is the output 1 1 2 2 3 3 not 1 1 2 2 3 1 integer division [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
Why is the output of this program 1 1 2 2 3 3 instead of 1 1 2 2 3 1
class Scratch {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 3 };
for (int i = 0; i < 6; i++)
System.out.print(a[i / 2] + " ");
}
}
When you divide 3/2 it equals 1.5, which I thought Java only took the first value of an integer number. What's going on?
You are dividing the index not the value. To get the result you're looking for, you should take the division outside the square brackets:
System.out.print(a[i] / 2 + " ");
// Here --------------^
The last iteration of the loop will be when i = 5. 5/2 = 2. a[2] = 3.
Because the last number of your loop is 5.
Then 5/2 = 2.5 which java turns into 2.
If you see your array, it came up that in the position 2, the number printed is 3.
I think the mistake you're making is that you're thinking of the values stored in the array being divided by 2, not the index. Or really moreso, you're letting the fact that the value 3 is not what you would expect the last value in the array would be, affect your perception of what the array look-up should yield. It's important to keep those separate.
Your code is looking up (0, 1, 2, 3, 4, 5) all divided by two which is (0, 0, 1, 1, 2, 2) with integer division. That is, a[5 / 2] = a[2] = 3.
i / 2 is an integer division which will effectively take the floor of the produced value by discarding the fractional part.
This results in a[0/2=0], a[1/2=0], a[2/2=1], a[3/2=1], a[4/2=2], a[5/2=2] array element access in your code.

Understanding Code in Java

public static void mystery2d(int[][] a) {
for (int r = 0; r < a.length; r++) {
for (int c = 0; c < a[0].length - 1; c++) {
if (a[r][c + 1] > a[r][c]) {
a[r][c] = a[r][c + 1];
}
}
}
}
If a two-dimensional array named numbers is initialized to store the following integers, what are its contents after the call shown?
int[][] numbers = {
{3, 4, 5, 6},
{4, 5, 6, 7},
{5, 6, 7, 8}
};
mystery2d(numbers);
I am really trying to understand code with 2D list but am having difficulties following along through the for loops. If someone could walk me through the steps or explain to me how it works that would be great thank you very much!
For example what would be a the values of the code bellow so I could have something to see if I could see the iterations of the loop better?
numbers[0][0] = ??
numbers[1][1] = ??
numbers[2][3] = ??
The code is to remove the smallest element in each row.
This is how it works.
In First row, it will check if 3<4? It is true. So, the a[0]=3 is replaced as a[0]=4 but a[1]=4 remains same. The same procedure happens till it reaches the end of each row. So the number in the last position at the end of every 'c'th iteration remains same.
Hence, the Output will be :
4566
5677
6788
So, the smallest element in each row. i.e. 3,4,5 in 1st, 2nd and 3rd row respectively is removed from array. I hope you got something!
First off, you should use i and j in your for loops rather than r and c, it is good practice. Your loop compares one number with the next number and changes the original to the new number if the new is greater than the original. So numbers[0][0] would be compared 3 ? 4 = 3 < 4 = so the 3 now becomes a 4. numbers[1][1] would be 5 ? 6 = 5 < 6 = 5 now becomes 6. And so on. Hope this helps.

Can someone correct the way I understand this code because the output is different than what I think?

public class Test{
public static void main(String[] args){
int[] a = {3, 2, 5, 21}; // created an array with 4 elements
int b,c;
for (b=0; b<=2; b++)//for loop that will have 3 iterations
{
if (a[b] < a[b+1])
{
c=a[b];//this
a[b] = a[b+1];//is
a[b+1] = c;//swapping
}
}
for(b=0; b<4; b++)
{
System.out.println(a[b]);
}
}
}
This outputs :
3 5 21 2
What I got when I was writing it down:
3 5 21 21
Could someone tell me how to approach it in my thoughts?
Well if you really want to just trace out the program you could go through each iteration of that first for-loop by hand (the second loop just prints the contents of a).
Before the loop starts, a holds
{3, 2, 5, 21}
First iteration (b = 0):
a[0] is not less than a[1] so we do nothing.
Second iteration (b = 1):
a[1] is less than a[2], so we swap them. Now a holds
{3, 5, 2, 21}
Third iteration (b = 2):
a[2] is less than a[3], so we swap them. Now a holds
{3, 5, 21, 2}
which is what gets printed subsequently.
Well, the code always outputs the initial elements of a, possibly permuted. Thus your expectation can't possibly have been correct, since it lost 2 and made 21 appear twice.
Well you got lost at the 3rd iteration so I'll start there.
The array is {3, 5, 2, 21}.
b = 2
if (a[b] < a[b+1]) is equivalent to if (2 < 21), this is true, so...
c=a[b];//this -> c = 2
a[b] = a[b+1];//is -> a[2] = 21
a[b+1] = c;//swapping -> a[2+1] = 2
so now a[2] = 21 and a[3] = 2 and the final array is:
{3, 5, 21, 2}
Each time you run the full outer loop you will end up with the next smallest element at the end of the array. So as you're only running the loop once you end up with 2 (being the first smallest element) at the end of the array.
As others have mentioned, if you want to make this a complete sort then you need more iterations of the main loop to complete the sort (n-1, where n is the length of the array, so in this case you would need to run the loop 3 times).

Trouble understanding Multidimensional Arrays

So i am trying to understand multidimensional arrays a little better. So far, I understand there are 2 way to construct these arrays. One is
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
The first array constructs row 0 with 2 columns ( column 0 and column 1). What i don't understand is why are these numbers chosen. Does it always have to be in numerical order, or do the numbers mean something more? If i were to create a new row would it start with 6? Would it just be better for me to construct it this way?
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
Thanks for your help.
Those numbers are meant to be examples. You need not start your next row with "6" if it's not what your solution demands.
Either manner of construction is acceptable. You'd use the second one if you had to compute the values and didn't know them beforehand.
1, 2, 3, 4, and 5 are just data that got entered in this new array.
The array would look like this:
[
[1, 2]
[3, 4, 5]
]
so [0][0] = 1; [1][0] = 3, [1][2] = 5 etc
Those values are just chosen as example.
First: there is no multi-dimensional arrays in Java. There are only arrays containing arrays. Arrays of arrays if you prefer.
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
constructs an array containing 2 arrays of int. The first array contains the numbers 1 and 2, and the second contains the numbers 3, 4 and 5. These numbers could be anything you want. The line declares and populates the array at the same time.
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
constructs an array of arrays of ints, containing two null elements. Then, the first element of the outer array is initialized with an array of 2 ints, and the second element of the outer array is initialized with an array of 3 ints. All the ints are initialized to their default value: 0.

Categories