Clarification about ArrayList syntax - java

What is being done in this for loop, counter and arr are two different ArrayLists.
// 3. store count of each number as we iterate through arr
for(int i = 0; i< arr.size(); i++){
counter[arr.get(i)]++;
}

arr contains indexes that the corresponding elements for them on counter should be incremented.
For example:
arr = [1,3,4]
Then the elements in 1,3 and 4 will be incremented in the array counter.
I highly recommend you to debug your code to better understand the flow of the program. You should also be careful with ArrayIndexOutOfBoundsException:
for(int i = 0; i< arr.size(); i++) {
if(arr.get(i) < 0 || arr.get(i) >= counter.length) {
continue;
}
counter[arr.get(i)]++;
}
Or doing something else, depends on the logic of your program.

If arr contains integer numbers it is index of counter array. Then you are incrementing the value of counter array on arr.get(i) index. I hope you understand what I am saying.

Related

selection sort loop questions in Java

I have a basic question about the inner loop length in Java selection sort. Here is the commonly used code for selection sort:
package com.java2novice.algos;
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++)
/* why not the length is not arr.length-1? I think the length is
exactly the same as what it is, the array's length is a
static number as array.length-1, but when it comes to the inner
loop why it plus 1 to the array length? */
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
}
Imagine you're trying to sort five items. The array length is 5, which means the indexes are 0 through 4.
In the first iteration of the inner loop, you have i=0 and j=1. You need j to index to the end of the array. That's why the expression in the inner loop is j < array.Length.
i, of course, only goes from 0 to 3, which is why the outer loop has i < array.Length - 1.
If you lay five playing cards on a table and walk through the steps of the selection sort, you'll get a better idea of what's happening here.
the first loop does not need to check the last index, therefore, it goes to arr.length - 1. on the second loop, of course, the last index of the array must be checked so the loop goes to the last index (arr.length).
imagine if the first loop goes to the last index. then this line for (int j = i + 1; j < arr.length; j++) will never execute.
check out this Pseudo code of selection sort for a better understanding of the algorithm

Java ArrayIndexOutOfBounds

Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:
JLabel[] wuerfelsummen = new JLabel[7];
wuerfelsummen[0] = player1_wuerfelsumme;
wuerfelsummen[1] = player2_wuerfelsumme;
wuerfelsummen[2] = player3_wuerfelsumme;
wuerfelsummen[3] = player4_wuerfelsumme;
wuerfelsummen[4] = player5_wuerfelsumme;
wuerfelsummen[5] = player6_wuerfelsumme;
public int ermittleGewinner(JLabel[] w)
{
int temp;
int[] zahlen = new int[w.length];
for(int i=0; i<=zahlen.length; i++)
{
if(w[i].getText() == null)
{
zahlen[i] = 99999999;
}
else
{
zahlen[i] = Integer.parseInt(w[i].getText());
}
}
for(int i=1; i<zahlen.length; i++)
{
for(int j=0; j<zahlen.length-i; j++)
{
if(zahlen[j]>zahlen[j+1])
{
temp=zahlen[j];
zahlen[j]=zahlen[j+1];
zahlen[j+1]=temp;
}
}
}
for(int i=0; i<=zahlen.length; i++)
This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.
Change it to
for(int i=0; i<zahlen.length; i++)
Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.
You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j
change "i<=zahlen.length" in your for loop to "i < zahlen.length".
remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using
The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array
ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)
You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.

counting the elements of array

I have an array which has null elements also. I want to keep track of number of elements that have the contents in it.
int counter = 0;
for (int a = 0; i <=array1.length; a ++){
if (array1[a] != null)
counter ++;
}
I used the above code for it. But I am getting ArrayIndexoutofBound exception at line
if (array1[a] != null)
why is that? Can someone point it pls.
Replace
for (int a = 0; i <=array1.length; a ++){
by
for (int a = 0; i <array1.length; a++){
Your code fails on element array1[array1.length], because the index must be between 0 and array1.length - 1 inclusive.
array1.length is the size of the array, but since the index is 0-based, you can only go to array1.length-1. So, either change your a <= array1.length to a <= array1.length - 1 or change it to the more common a < array1.length.
Change
for (int a = 0; i <=array1.length; a ++){
into
for (int a = 0; i <array1.length; a ++){
There is no element array1[array1.length]
If you have size of 5 array means you have index from 0 to 4, In other word index of the first element is 0 and the index of last element is 4
Of course it is because you are iterating one time extra than the length of an array.
If the length of your array is 3. Your array stores elements like array[0], array[1] and array[2].
Index of an array or any list Map Set starts from 0.
Use for(int a = 0; a < array1.length;a++)
In your "for" loop,it should be "a<=" instead of 'i'
switch <= to < in your for loop

Random number generator continues to include 0

I'm trying to populuate an array with random numbers to be sorted and used in a binary search. All of my code seems to work fine except the generating part. The numbers need be between 1-32767 and I continue to get 0.
for(int i = 0; i < SIZE-1; i++){
array[i] = (gen.nextInt(32767 - 1) + 1);
}
// Print out five entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
// Sort array
Arrays.sort(array);
// Print out first five sorted entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
After they're sorted and printed, the first entry is always 0. Perhaps this has to do with the array sorting, and I'm not realizing it. Any suggestions?
You're never setting the last element of the array -- use i < SIZE, not i < SIZE-1.

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources