Kylian Murphy Kylian Murphy - 29 days ago 8
Java Question

Using int[] arrays to manipulate each other through nested loops

What I am trying to do is use one method to generate 30 random numbers from 0-15 and then another method to count how many times each number prints and put it in a second array. Each position in the second array corresponds to the number in the array it is. if i = [0] and 0 shows up 3 times, it should be 3 and so on.

So far, I have gotten this. What seems to be happening is that it counts the number of times 15 shows up (The last number of the array). Though I could be wrong. I don't see what I'm doing wrong. There must be something wrong with my logic.

import java.util.Arrays;

public class FrequencyOfNumbers {

public static void main(String[]args){
System.out.println(Arrays.toString(randomNums()));
System.out.println(Arrays.toString(sortedNums(randomNums())));
}

public static int[] randomNums (){
int[] random = new int[30];
for(int i=0;i<random.length;i++){
double randNum = Math.random() * 16;
random[i] = (int)randNum;
}
return random;
}

public static int[] sortedNums(int[] sort){
int[] numVals = new int[15];
for(int i=0;i<numVals.length;i++)
{
for(int j=0;j<sort.length;j++)
{
if(sort[j] == numVals[i])
{
numVals[i]++;
}
}
}
return numVals;
}
}


Example output I'm receiving:

[5, 15, 0, 5, 4, 10, 4, 11, 5, 13, 13, 8, 9, 9, 10, 6, 0, 9, 10, 12, 3, 7, 4, 9, 4, 11, 9, 15, 10, 7]

[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

Answer

You have some problems in the code:

  1. Don't call randomNums() twice. Otherwise you don't count the right frequency. It will generate different arrays.

  2. If you want to keep numbers from 0 to 15, you should allocate 16 elements for numVals.

  3. You don't need an inner for loop when you count the appearances. Just consider all the numbers, take their values, and increment the number of appearances.

Try this:

public static void main(String[] args) {
    int[] randomNumbers = randomNums();
    System.out.println(Arrays.toString(randomNumbers));
    System.out.println(Arrays.toString(sortedNums(randomNumbers)));
}

public static int[] randomNums() {
    int[] random = new int[30];
    for (int i = 0; i < random.length; i++) {
        random[i] = (int) (Math.random() * 16);
    }
    return random;
}

public static int[] sortedNums(int[] sort) {
    int[] numVals = new int[16];
    for (int j = 0; j < sort.length; j++) {
        numVals[sort[j]]++;
    }
    return numVals;
}

A possible output:

[8, 6, 5, 12, 12, 9, 15, 6, 7, 9, 15, 3, 6, 7, 3, 8, 6, 3, 15, 8, 12, 4, 7, 12, 2, 15, 6, 5, 4, 5]
[0, 0, 1, 3, 2, 3, 5, 3, 3, 2, 0, 0, 4, 0, 0, 4]
Comments