ourweakness - 1 year ago 45

Java Question

SO I'm working with array's in java, and I'm running into an issue where I'm trying to list of f the locations of the least occurring number in an array with a length of 100, with a range of 0-9. I'm using a second array to count the occurrences, and it all works out until my last piece of code.

`import java.util.Random;`

public class Program6

{

public static void main(String[] args)

{

int[] bigArray = new int[100];

int[] count = new int[10];

for (int i = 0; i < bigArray.length ;i++ )

{

bigArray[i] = (int)(Math.random() * 10);

}

for (int i = 0; i < bigArray.length ;i++ )

{

System.out.println(bigArray[i] + " ");

}

for(int i = 0; i < bigArray.length; i++)

{

count[bigArray[i]]++;

}

for (int i = 0, j = 0; i < count.length ;i++, j++)

System.out.println("count for " + j +" is: " + count[i] + " ");

int min = count[0];

int indexOfMin = 0;

for ( int i =1; i < count.length; i++)

{ if (count[i] < min )

{

min = count[i];

indexOfMin = i;

}

}

System.out.println("\nThe number " + indexOfMin + " only appears " + min + " times in the array.");

System.out.println("It appears in the large array at: ");

\\this guy right here

for ( int i = 0 ; i < bigArray.length; i++)

{ if (bigArray[i] == min )

{

System.out.println("bigArray["+ i + "]");

}

}

}

}

It should just list off the array locations. But it returns way more than just the locations of the lowest occurring integer, even though the qualifier is using the variable

What gives? What am i missing?

There is no input, the output that returns is

`8`

..

4

count for 0 is: 18

count for 1 is: 6

count for 2 is: 9

count for 3 is: 9

count for 4 is: 16

count for 5 is: 4

count for 6 is: 12

count for 7 is: 8

count for 8 is: 7

count for 9 is: 11

The number 5 only appears 4 times in the array.

It appears in the large array at:

bigArray[3]

bigArray[6]

bigArray[10]

bigArray[23]

bigArray[25]

bigArray[39]

bigArray[44]

bigArray[48]

bigArray[49]

bigArray[50]

bigArray[51]

bigArray[57]

bigArray[58]

bigArray[67]

bigArray[84]

bigArray[99]

which is perfect, except for the bigArray[] list out. It should only show where the index when the array is equal to the least occurring number.

Answer Source

You are comparing against the count of the number. use the number instead. Update

```
//this guy right here
for ( int i = 0 ; i < bigArray.length; i++)
{ if (bigArray[i] == min )
{
System.out.println("bigArray["+ i + "]");
}
}
```

to use `indexOfMin`

as

```
`//this guy right here
for ( int i = 0 ; i < bigArray.length; i++)
{ if (bigArray[i] == indexOfMin)
{
System.out.println("bigArray["+ i + "]");
}
}
```