Determining output of an array implementation with class and constructor - java

Im trying to understand whats being iterated and went through a visualizer but after getting the [0,2,4,6,8,0,0,0,0,0] from the main Im having trouble understanding how the final output is [2,0,2,0...etc] Im assuming the "if (n > (arr.length - 2)) return;" is ignored since 5 is not bigger than 8, but then I get lost. If anyone could explain that I would appreciate it.
public class Class1{
public static void shiftTwoOver(int[] arr, int n) {
if (n > (arr.length - 2)) return;
for (int i = 0; i < n; ++i)
arr[i+2] = arr[i];
}
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < 5; ++i) a[i] = 2*i;
shiftTwoOver(a,5);
for (int i = 2; i < 7; ++i) System.out.println(a[i]);
}
}

This loop is executed five times, because n=5
for (int i = 0; i < n; ++i)
arr[i+2] = arr[i];
arr[2] = arr[0] which is 0;
arr[3] = arr[1] which is 2;
arr[4] = arr[2] which is 0 from the first execution;
arr[5] = arr[3] which is 2 from the second execution;
arr[6] = arr[4] which is 0 from the third execution;
And later it's only printed out from index 2 to 6.

The array you are passing in is a dynamic array of size 10, and for the parameters you are passing in 5. So the if (n > (arr.length - 2)) return; will never trigger because n is less then (arr.length -2) = 8.
Furthermore the data is corrupted when you arr[i+2] = arr[i] because you initialized the array with a[i] = 2*i from a[0] to a[4]. I think the goal is to move all 5 data elements two spaces over? So when you make arr[2] = arr[0] remember you just deleted all the data at arr[2] and replaced it with arr[0].
Since that loops five times understand what you have now say initially arr[0] = "bob" now you will have arr[0] = bob and arr[2] = bob. Note that arr[0] wasnt erased so you technically didn't move anything and just copied data over. Repeat that again for arr[3] = arr[1] and once again on the next step you will do arr[4] = arr[2] remember in arr[2] there was "bob" now you have arr[4] = "bob" as well.
So ultimately you have arr[0] = arr[2] = arr[4] = "bob". Hence, the data was never shifted two rows. Thats why you have 2 0 2 0 2 0 repeating.

Related

Why is the DP solution not working, Trapping Rain Water?

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
example:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
**Constraints**:
n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105
The issue with this is that it is outputting 0 for when the input is [2,0,2] but the code should be setting the index 1 to have a leftMax of 2 and rightMax of 2 so 2-0=2 should be the output
class Solution {
public int trap(int[] height) {
if(height == null || height.length == 0){
return 0;
}
int ans = 0;
int size = height.length;
int[] leftMax = new int[size];
int[] rightMax = new int[size];
leftMax[0] = height[0];
for(int i = 1; i < size; i++){
leftMax[i] = Math.max(leftMax[i-1],height[i]);
}
rightMax[0] = height[size-1];
for(int i = size-2; i >= 0; i--){
rightMax[i] = Math.max(rightMax[i+1],height[i]);
}
for(int i = 1; i < size-1; i++){
ans+= Math.min(leftMax[i],rightMax[i])-height[i];
}
return ans;
}
}
The problem is that your rightMax initialization is wrong, it initializes "on the wrong side". It initializes the [0] which was probably copied from the leftMax section. But the leftMax then iterates from the left, the rightMax iterates from the right and therefore the rightmost index should be initialized. Note that you already initialized with the correct height index but for the wrong rightMax - it should look like:
rightMax[size-1] = height[size-1]
This previously worked because the very right was (probably) not part of a water trap and therefore its wrong value did not have any impact. But in the very simply case of 2,0,2 it is part of the trap and messed up the result.
Now the code properly calculates the two given samples:
System.out.println(trap(new int[] {0,1,0,2,1,0,1,3,2,1,2,1})); // 6
System.out.println(trap(new int[] {2,0,2})); // 2

Why I cannot use array index decrement when using a another array value in Java?

This is a simple code for Insertion Sort in Java. I tried reducing the lines of my Java code. But it cannot be done with this issue. I want to know why it cannot be done.
Code that I have tried (error happens in line number 9)
import java.util.Scanner;
public class InsertionSortModified {
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int pos = i;
while (pos > 0 && arr[pos-1] > temp)
arr[pos--] = arr[pos-1];
arr[pos] = temp;
}
return arr;
}
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int elementarr[] = new int[5];
for (int j = 0; j < 5; j++)
elementarr[j] = scnr.nextInt();
elementarr = insertionSort(elementarr);
for (int j = 0; j < elementarr.length; j++)
System.out.print(elementarr[j] + " ");
}
}
Error showing in the command window
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at InsertionSortModified.insertionSort(InsertionSortModified.java:9)
at InsertionSortModified.main(InsertionSortModified.java:22)
Program is working when the code modified to like this. (Line number 8 to 11)
while (pos > 0 && arr[pos-1] > temp) {
arr[pos] = arr[pos-1];
pos--;
}
Why I cannot use
arr[pos--] = arr[pos-1];
When you are trying to do
arr[pos--] = arr[pos-1];
and the value of pos is 1 then it decrements pos to 0, then in the second usage of pos you are making it 0 - 1
In line 9 your decreasing the counter in the wrong order. The correct line is
`arr[pos] = arr[--pos];`
Here you're swapping the current value in arr[pos] for that in arr[pos-1] as you are decreasing the counter before using it. After, the pos value is already in the correct position to insert the 'temp' value
I have found what the problem is. Step by step execution of the code is here.
Line number 9:
When i == 2, pos == 2. At the line 9 execution order is like this.
At initially first execution if the while loop, arr[2] = arr[pos-1].
Positioning the array index 2. But after positioning pos is decreasing to pos == 1.
Then line becomes to this arr[2] = arr[1-1] means arr[2] = arr[0].
After that still while loop is true.
Then the second execution of the while loop at initially arr[1] = arr[pos-1].
Then positioning the array index 1. But after positioning pos is decreasing to pos == 0.
Then line becomes to this arr[1] = arr[0-1] means arr[1] = arr[-1].
So error happens in here. (ArrayIndexOutOfBounds).
Corrected code is like this. (Line number 9)
arr[pos--] = arr[pos];
or
arr[pos] = arr[--pos];

Understanding what java code prints

Hi guys I am fairly new to this and have a question about this code. I am unsure about how the output is what it is so if someone could explain it to a beginner I'd be grateful! This is the code:
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.
In your first function you are creating a new array. This array is returned however the value is never copied into the original. Therefore when printing the matrix the first loop will stay as 1, 2, 3. If you want this to change switch the line:
first(matrix[0]);
To:
matrix[0] = first(matrix[0]);
The second function takes the original array and loops once (since a.length is 3 and 3 / 2 = 1). During this loop it converts a[0] to a[a.length - 1 - i] or a[3 - 1 - 0]. It then switches a[a.length - 1 - i] or a[2] to temp which is a[0]. This will switch the first and last element in the array which are 6 and 4.
At first, your code is quite messy. Try to use the proper indentation (four spaces for each block). It makes the code easier to read (and you might have figured out the answer yourself).
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.

What's the output of this code written in java?

int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i;
}
int res = arr[0] + arr[2];
System.out.println(res);
I'm a beginner in java, as you can see, and I'm not quite sure what's the output of this. Can someone answer and explain along the way?
//if you're using Eclipse, press ctrl-shift-f to "beautify" your code and make it easier to read
int arr[] = new int[3]; //create a new array containing 3 elements
for (int i = 0; i < 3; i++) {
arr[i] = i;//assign each successive value of i to an entry in the array
}
int res = arr[0] + arr[2];//add the 0th element value to the 2nd element value, save in res
System.out.println(res);//print res, which is == 0 + 2
basically what you are doing here is
int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i; // you are adding elements on array location
}
int res = arr[0] + arr[2];
System.out.println(res);
when first time loop execute i equals to 0, on location 0 you are assigning 0 there and for 1,2 the same process is being applied. On line int res = arr[0] + arr[2]; you are adding values of location 0 and 2 which are 0and 2 so the output is 2 when you add 0+2 = 2 in basic mathematics
On the first line, you are creating a new array of integers. The array has the elements arr[0], arr[1], and arr[2].
On the next three lines, is your for loop. As you have written in the loop, it will start from i=0 and will continue running while i < 3. Therefore, i will be 0, 1, and 2. In the loop itself, you are saying:
arr[0] = 0, arr[1] = 1, arr[2] = 2.
On the last two lines, you have two statements. The first expression creates an integer called res. Then you are saying res = arr[0] + arr[2]. But as we just saw, in the for loop you made arr[0] = 0 and arr[2] = 2. Therefore, res = 0 + 2 = 2.
On the last line you are just printing the result in the console.

How exactly do arrays and for loops work together?

I understand that arrays are used to store values but when they are used with for loops I loose track of what is happening. I know that the output is 100 because I ran it in the terminal but what I need to understand is that how did it get 100 from using the for loops and the arrays because I'm not sure if it uses all three values or just the first one. Thanks in advance
Here is the problem:
public class arrays {
public static void main (String[] args) {
int[] a1 = {1, 1, 3};
mystery(a1);
}
public static void mystery(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
a[i] = (a[i - 1] + a[i + 1]) /2;
}
}
}
Not entirely sure what the question you're trying to ask is but - to try and help - does it help that each time a[i] is called, it takes the value of i (also the iteration number) at each instance and uses that to find the relevant array index - which is then used for the rest of the computation.
try to add this method for tracing.
public class arrays{
public static void main(String[] args) {
int[] a1 = {1, 1, 3};
mystery(a1);
}
public static void mystery(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
a[i] = (a[i - 1] + a[i + 1]) /2;
printArray(a);
}
public void printArray(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println("array[" + i + "] is now " + arr[i]);
}
}
EDIT: So what's going on back-stage?
for loop initializes i as 1.
a[1] (previously '1') is changed into (a[0] + a[2])/2 = (1 + 3)/2 = 2)
i is incremented by 1
i does not meet the condition (i < a.length - 1) because i = 2 and (a.length - 1) = (3 - 1) = 2 (2 is not less than 2, its equal to 2)
loop terminates and so is the program.
I think what you're missing is that i does not represent the index of the number 1 in your array, it is the index itself when used in the context of a[i] meaning "go to a, in index i..."
Your question is not clear. If you can provide question clearly, you will get great answers ! Anyways :
Try to think yourself.
Array position starts from "0" which is also called as the index of the array.
Here loop is going from value of
i =1 to i < the value of (array's length)-1 which is i < 2 as length of array = 3
So,
for(int i=1 ; i < a.length - 1; i++){
a[i] = (a[i - 1] + a[i + 1]) /2;
}
Now take initially value of i=1 and then run the code yourself in your mind :
1.. for i = 1,
**a[i] = (a[i - 1] + a[i + 1]) /2;**
gives a[1] = (a[0] + a[2])/2 ==> a[1] = (1+3)/2 ==> a[1] = 2
Important : you have given **i < a.length-1**
Now, a.length = 3 ok?
a.length -1 = 2 ok?
so i< a.length-1 will stop at i equals 1
So, your program will give {1,2,3} as for loop will iterate from i =1 to i=1 got it?
So only 1 value i.e. a[1] will gets changed.. a[0] and a[2] will remain same.
What happens when the method mistery(a1) is called:
1. int i is initialized to 1
2. The condition if i*a.length-1, which is (3-1), is checked; this condition is true;
3. because the condition at 2. is true, the code in the for loop is executed:
a[i] = (a[i - 1] + a[i + 1]) /2 => a[1] = (a[1-1]+a[1+1])/2 => a[1]=(a[0]+a[2])/2 =>
=> a[1]=(1+3)/2 => a[1]=2
4. after the code in the for loop is executed, i is incremented by 1, thus, the final stage of this for loop is executed: i++, i is equal to 2 right now.
5. Again, the for loop checks if the condition i<a.length-1, (3-1) is true; this time, the condition is false: i=2, 2 is not less than 2.
6. The for loop terminates its "existence", in this case the method mystery(a1) is fully executed.

Categories

Resources