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.
Related
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.
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];
I need to print [1,2,3,4] when I get array like [1,1,2,2,3,3,4].
Other examples:
input=[1,1,1,2] output should be=[1,2]
input=[1,1,1,1] output should be=[1]
int count=1;
//This for counts only the different numbers of the array input.
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
//New array only for the needed numbers.
Integer [] res = new Integer[count];
res[0] = array[0];
for(int i = 1;i<count;i++){
if(array[i]!=array[i+1]){
res[i]=array[i+1];
}
}
With input [1,1,2,2,3,3,4] I get [1, 2, null, 3].
Should be [1,2,3,4].
One problem is that you increment the loop's counter even when array[i]==array[i+1], which results in the output array having null values.
Another problem is that you don't iterate over all the elements of the input array in the second loop.
Both problems can be solved if you use two indices, one for the input array (the loop's variable) and another for the current position in the output array :
int count=1;
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
Integer [] res = new Integer[count];
res[0] = array[0];
int resIndex = 1;
for(int i = 1; i < array.length - 1; i++){
if(array[i] != array[i+1]) {
res[resIndex] = array[i+1];
resIndex++;
}
}
EDIT :
As fabian suggested, changing the second loop to
for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)
can make it slightly faster if the last unique number of the input array repeats multiple times.
I am working on a project, but I cannot use any existing java data structures (ie, ArraysList, trees, etc)
I can only use arrays. Therefore, I need to dynamically update an array with new memory.
I am reading from a text file, and I pre-allocate 100 for the arrays memory:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
wordList[wordCount] = s.next();
wordCount++;
}
}
Now this works fine for under 100 list items. br.readline is the buffered reader going through each line of a textfile. I have it then store each word into list and then increment my index (wordCount).
However, once I have a text file with more than 100 items, I get an allocation error.
How can I dynamically update this array (and thereby sort of reinvent the wheel)?
Thanks!
You can do something like this:
String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null) {
// Store the content into an array
Scanner s = new Scanner(strLine);
while(s.hasNext()) {
if (wordList.length == wordCount) {
// expand list
wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
}
wordList[wordCount] = s.next();
wordCount++;
}
}
Using java.util.Arrays.copyOf(String[]) is basically doing the same thing as:
if (wordList.length == wordCount) {
String[] temp = new String[wordList.length + arrayGrowth];
System.arraycopy(wordList, 0, temp, 0, wordList.length);
wordList = temp;
}
except it is one line of code instead of three. :)
You allocate a new Array (double the capacity, for instance), and move all elements to it.
Basically you need to check if the wordCount is about to hit the wordList.size(), when it does, create a new array with twice the length of the previous one, and copy all elements to it (create an auxiliary method to do this), and assign wordList to your new array.
To copy the contents over, you could use System.arraycopy, but I'm not sure that's allowed with your restrictions, so you can simply copy the elements one by one:
public String[] createNewArray(String[] oldArray){
String[] newArray = new String[oldArray.length * 2];
for(int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}
return newArray;
}
Proceed.
Take a look at implementation of Java ArrayList. Java ArrayList internally uses a fixed size array and reallocates the array once number of elements exceed current size. You can also implement on similar lines.
you can not increase array size dynamically better you copy into new array. Use System.arrayCopy for that, it better than copying each element into new array. For reference
Why is System.arraycopy native in Java?.
private static Object resizeArray (Object oldArray, int newSize) {
int oldSize = java.lang.reflect.Array.getLength(oldArray);
Class elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(
elementType, newSize);
int preserveLength = Math.min(oldSize, newSize);
if (preserveLength > 0)
System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
return newArray;
}
You have to manually create a new bigger array and copy over the items.
this may help
Visual Basic has a nice function : ReDim Preserve.
Someone has kindly written an equivalent function - you can find it here. I think it does exactly what you are asking for (and you're not re-inventing the wheel - you're copying someone else's)...
Lets take a case when you have an array of 1 element, and you want to extend the size to accommodate 1 million elements dynamically.
Case 1:
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 1];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 2 (increasing size by a addition factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 10];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 3 (increasing size by a multiplication factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length * 2];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
When extending the size of an Array dynamically, using Array.copy or iterating over the array and copying the elements to a new array using the for loop, actually iterates over each element of the array. This is a costly operation. Array.copy would be clean and optimized, still costly. So, I'd suggest increasing the array length by a multiplication factor.
How it helps is,
In case 1, to accommodate 1 million elements you have to increase the size of array 1 million - 1 times i.e. 999,999 times.
In case 2, you have to increase the size of array 1 million / 10 - 1 times i.e. 99,999 times.
In case 3, you have to increase the size of array by log21 million - 1 time i.e. 18.9 (hypothetically).
public class Arr {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {1,2,3};
//let a[] is your original array
System.out.println(a[0] + " " + a[1] + " " + a[2]);
int b[];
//let b[] is your temporary array with size greater than a[]
//I have took 5
b = new int[5];
//now assign all a[] values to b[]
for(int i = 0 ; i < a.length ; i ++)
b[i] = a[i];
//add next index values to b
b[3] = 4;
b[4] = 5;
//now assign b[] to a[]
a = b;
//now you can heck that size of an original array increased
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " "
+ a[4]);
}
}
Output for the above code is:
1 2 3
1 2 3 4 5
Im trying to add an element to an array at its last position in Java, but I am not able to...
Or rather, I don't know how to. This is the code at the moment:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][coordinates[0].length] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][coordinates[1].length] = values[i];
}
}
EDITED VERSION:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
int x_pos = 0;
int y_post = 0;
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][x_pos] = values[i];
x_pos++;
} else { //THIS IS ODD VALUE
coordinates[1][y_pos] = values[i];
y_pos++;
}
}
values is being read from a CSV file. My code is I believe wrong, since it will try to add the values always at the maximum array size for coordinates[] in both cases.
How would I go around adding them at the last set position?
Thanks!
/e: Would the EDITED VERSION be correct?
Your original code has two problems:
it addresses the array badly, the las element in a Java array is at position length-1, and this would result in an ArrayOutOfBoundsException
even if you'd correct it by subtracting 1, you would always overwrite the last element only, as the length of a Java array is not related to how many elements it contains, but how many elements it was initialised to contain.
Instead of:
coordinates[0][coordinates[0].length] = values[i];
You could use:
coordinates[0][(int)Math.round(i/2.0)] = values[i];
(and of course, same with coordinates[1]...)
EDIT
This is ugly of course:
(int)Math.round(i/2.0)
but the solution I'd use is far less easy to understand:
i>>1
This is a right shift operator, exactly the kind of thing needed here, and is quicker than every other approach...
Conclusion: this is to be used in a live scenario:
Use
coordinates[0][i>>1] = values[i];
EDIT2
One learns new things every day...
This is just as good, maybe a bit slower.
coordinates[0][i/2] = values[i];
If you know you'll definitely have an even number of values you can do
for(int i = 0; i < values.length / 2; i++) {
coordinates[0][i] = values[2*i];
coordinates[1][i] = values[2*i + 1];
}
You have to store the last position somewhere. .length gives you the size of the array.
The position in the array will always be the half of i (since you put half of the elements in one array and the other half in the other).
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][ i / 2] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][ i / 2 + 1 ] = values[i];
}
}
The array index for java is from "0" to "array length - 1".
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
why not:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i+=2) {
coordinates[0][i/2] = values[i];
coordinates[1][i/2] = values[i+1];
}