Count occurrences of elements inside array? (Java)

2019-05-27 03:34发布

I have been working on trying to figure out this algorithm for about 6 hours now and can't seem to come up with a solution. I am trying to count the occurrences of elements inside an array and may two more separate arrays. One for the unique instances, and one for how many times these instances occurs. I found some other thinks on here about array lists and hashMaps, but I am only able to use arrays.

For example, I have this array (already sorted):

{cats, cats, cats, dog, dog, fish}

I am trying to get make an array for the instances, so:

{cats, dog, fish}

And finally, how many times these instances occur:

{3, 2, 1}

Here is the code i have so far:

public void findArrs( String[] words )
{
  int counter = 1;
  for(int i = 0; i < words.length - 1; i++){
  if(!(words[i].equals(words[i+1]))){
  counter++; 
  }
 }

 String[] unique = new String[counter];
 int[] times = new int[counter];

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

   }    
}

This is all the code I have after all my attempts.

7条回答
beautiful°
2楼-- · 2019-05-27 04:07

Here is plain simple JavaScript:

var myarray = {"cats", "cats", "cats", "dog", "dog", "fish"};
var values = [];
var instanceCount = []
for(var i = 0; i < myarray.length; i++){
    var value = myarray[i];
    var counter = 0;
    for(var j = 0; j < myarray.length; j++){
        if(firstVal == myarray[j]) counter++;
    }
    //Build your arrays with the values you asked for
    values.push(value);
    instanceCount.push(counter);

    //Remove All occurences further in the array
    var idx = myarray.indexOf(value);
    while (idx != -1) {
        myarray.splice(idx, 1);
        idx = array.indexOf(myarray, idx + 1);
    }
}

//Handle Result here
查看更多
登录 后发表回答