3

I'm trying to count the number of occurences of ints, one to six inclusive, in an array of size 6. I want to return an array with the number of times an int appears in each index, but with one at index zero.
Example:

Input: [3,2,1,4,5,1,3]
Expected output: [2,1,2,1,1,0].

Problem:
It outputs [1,1,3,0,1,0] with the code excerpt below. How can I fix this? I can't find where I'm going wrong.

public static int arrayCount(int[] array, int item) {
    int amt = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] == item) {
            amt++;
        }
    }
    return amt;
}

public int[] countNumOfEachScore(){
    int[] scores = new int[6];
    int[] counts = new int[6];
    for (int i = 0; i < 6; i++){
        scores[i] = dice[i].getValue();
    }
    for (int j = 0; j < 6; j++){
        counts[j] = arrayCount(scores, j+1);
    }
    return counts;
}

dice[] is just an array of Die objects, which have a method getValue() which returns an int between 1 and 6, inclusive. counts[] is the int array with the wrong contents.

xenteros
  • 15,586
  • 12
  • 56
  • 91
arnbobo
  • 2,515
  • 2
  • 12
  • 18

2 Answers2

4

It'll be faster to write another code instead of debugging yours.

public static int[] count(int[] array) {
    int[] result = new int[6];
    for (int i = 0; i < array.length; i++) {
        try{
            result[array[i]-1]++;
        } catch (IndexOutOfBoundsException e) {
            throw new IllegalArgumentException("The numbers must be between 1 and 6. Was " + String.valueOf(array[i]));
        }
    }
    return result;
}

The above will result in an array of 6 ints. ith number in the result array will store the number of occurences of i+1.

PoC for the OP
enter image description here

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • It still seems to be off. With input values of [1,2,4,4,3,5] it gave me [0,1,3,3,4,4], which isn't right. – arnbobo Oct 04 '16 at 18:19
  • It returns [1,1,1,2,1,0] on my machine. On my `Java Virtual Machine`. – xenteros Oct 04 '16 at 18:21
  • @arnbobo can you show me more of your code? I'll try to help. If it started working, feel free to mark it as a solution. – xenteros Oct 04 '16 at 19:05
  • @arnbobo you're welcome. I'll be happy to solve your problems in the future. Feel free to call me in comment. – xenteros Oct 04 '16 at 19:12
-2
public static void main(String [] args){
        int []ar=new int[]{3,2,1,4,5,1,3};
        System.out.println(Arrays.toString(counter(ar)));

    }


public static int[] counter(int []ar){
        int []result=new int [6];
        for(int i=0;i<ar.length;i++){
            int c=0;
            for(int j=0;j<ar.length;j++){
                if(j<i && ar[i]==ar[j])
                    break;
                if(ar[i]==ar[j])
                    c++;
                if(j==ar.length-1){
                    result[i]=c;
                }
            }
        }
        return result;
    }
Hasib
  • 19
  • 5