计算数组内元素的出现次数? (JAVA)

时间:2014-01-20 07:27:54

标签: java arrays elements find-occurrences

我一直在努力试图找出这个算法大约6个小时,但似乎无法提出解决方案。我试图计算数组中元素的出现次数,可能还有两个单独的数组。一个用于唯一实例,一个用于这些实例发生的次数。我在这里发现了一些关于数组列表和hashMaps的想法,但我只能使用数组。

例如,我有这个数组(已经排序):

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

我正在尝试为实例创建一个数组,所以:

{cats, dog, fish}

最后,这些实例发生了多少次:

{3, 2, 1}

这是我到目前为止的代码:

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++){

   }    
}

这是我所有尝试后的所有代码。

7 个答案:

答案 0 :(得分:1)

这就是如何仅使用数组来完成的。棘手的部分是你必须知道创建数组之前的项目数。所以我必须创建自己的函数来创建一个更大的数组。实际上是两个,一个用于计数,一个用于唯一值。

如果你可以使用矢量,你会更好。这是没有vet​​ors的:

public class HelloWorld{

     public static void main(String []args){
        String[] initalArray;

        // allocates memory for 10 integers
        initalArray = new String[6];
        initalArray[0] = "cats";
        initalArray[1] = "cats";
        initalArray[2] = "cats";
        initalArray[3] = "dog";
        initalArray[4] = "dog";
        initalArray[5] = "fish";

        String[] uniqueValues = new String[0];
        int[] countValues = new int[0];
        for(int i = 0; i < initalArray.length; i++)
        {
            boolean isNewValue = true;
            for (int j = 0; j < uniqueValues.length; j++)
            {
                if (uniqueValues[j] == initalArray[i])
                {
                    isNewValue = false;
                    countValues[j]++;
                }
            }

            if (isNewValue)
            {
                // We have a new value!
                uniqueValues = addToArrayString(uniqueValues, initalArray[i]);
                countValues = addToArrayInt(countValues, 1);
            }
        }

        System.out.println("Results:");
        for(int i = 0; i < countValues.length; i++)
        {
            System.out.println(uniqueValues[i] + "=" +  countValues[i]);
        }
     }

     public static String[] addToArrayString(String[] initalArray, String newValue)
     {
         String[] returnArray = new String[initalArray.length+1];
         for(int i = 0; i < initalArray.length; i++)
         {
             returnArray[i] = initalArray[i];
         }
         returnArray[returnArray.length-1] = newValue;

         return returnArray;
     }

     public static int[] addToArrayInt(int[] initalArray, int newValue)
     {
         int[] returnArray = new int[initalArray.length+1];
         for(int i = 0; i < initalArray.length; i++)
         {
             returnArray[i] = initalArray[i];
         }
         returnArray[returnArray.length-1] = newValue;

         return returnArray;
     }
}

如评论中所述,如果我们知道数组是有序的,那么我们不需要搜索整个前一个数组,只需直接检查uniqueValues。

public class HelloWorld{

     public static void main(String []args){
        String[] initalArray;

        // allocates memory for 10 integers
        initalArray = new String[6];
        initalArray[0] = "cats";
        initalArray[1] = "cats";
        initalArray[2] = "cats";
        initalArray[3] = "dog";
        initalArray[4] = "dog";
        initalArray[5] = "fish";

        String[] uniqueValues = new String[0];
        int[] countValues = new int[0];
        for(int i = 0; i < initalArray.length; i++)
        {
            boolean isNewValue = true;
            if (i > 0)
            {
                if (uniqueValues[uniqueValues.length-1] == initalArray[i])
                {
                    isNewValue = false;
                    countValues[uniqueValues.length-1]++;
                }
            }

            if (isNewValue)
            {
                // We have a new value!
                uniqueValues = addToArrayString(uniqueValues, initalArray[i]);
                countValues = addToArrayInt(countValues, 1);
            }
        }

        System.out.println("Results:");
        for(int i = 0; i < countValues.length; i++)
        {
            System.out.println(uniqueValues[i] + "=" +  countValues[i]);
        }
     }

     public static String[] addToArrayString(String[] initalArray, String newValue)
     {
         String[] returnArray = new String[initalArray.length+1];
         for(int i = 0; i < initalArray.length; i++)
         {
             returnArray[i] = initalArray[i];
         }
         returnArray[returnArray.length-1] = newValue;

         return returnArray;
     }

     public static int[] addToArrayInt(int[] initalArray, int newValue)
     {
         int[] returnArray = new int[initalArray.length+1];
         for(int i = 0; i < initalArray.length; i++)
         {
             returnArray[i] = initalArray[i];
         }
         returnArray[returnArray.length-1] = newValue;

         return returnArray;
     }
}

答案 1 :(得分:1)

假设words数组至少有一个元素:

int numberOfDifferentWords = 1;
String firstWord = words[0];
for(int i = 0; i < words.length; i++) {
    if(!firstWord.equals(words[i])) {
        numberOfDifferentWords++;
    }
}

// These two arrays will contain the results. 
String[] wordResultArray = new String[numberOfDiffentWords];
int[] countResultArray = new int[numberOfDiffentWords];

// This will mark where we should put the next result
int resultArrayIndex = 0;

String currentWord = firstWord;
int currentWordCount = 0;
for(int i = 0; i < words.length; i++) {
    //if we're still on the same word, increment the current word counter
    if(currentWord.equals(words[i])) {
        currentWordCount++;
    }
    //otherwise, transition to a new word
    else {
        wordResultArray[resultArrayIndex] = currentWord;
        wordCountArray[resultArrayIndex] = currentWordCount;
        resultArrayIndex++;

        currentWord = words[i];
        currentWordCount = 1;
    }
}

正如其他答案所提到的,通过使用List这样的ArrayList来存储结果可以简化这个问题。

答案 2 :(得分:1)

将唯一的时间作为实例变量,以便您可以使用getter方法从另一个类中检索它们。

注意:修改后的代码可以通过注释找到(对于“添加行”这一行。对于“添加代码从这里开始”到“添加代码在这里结束”之间的块)。我试着在代码中解释实现。如果我需要更多地掌握我的文档技能,请通过评论告诉我

public class someClass(){
  private String[] unique;
  private int[] times;
  //Added code starts here
  public String[] getUnique(){
    return this.unique;
  }

  public int[] getTimes(){
    return this.times;
  }
  //Added code ends here
  //Below implementation would work as intended only when words array is sorted
  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++; 
        }
    }

    unique = new String[counter];
    times = new int[counter];
    //Added line.
    unique[0] = words[0];  
    for(int i=0,j=0; i < words.length&&j < counter; i++){
   //Added code starts here
       if(!(unique[j].equals(words[i]))){
            j++; //increment count when latest element in unique array is not equal to latest element in words array
            unique[j] = words[i]; //add newly found unique word from words array to unique array
            times[j] = 1; //make the count to 1 for first non repeated unique word

        }
        else{

            times[j]++; //increment the count every time the string repeats
        }
   //Added code ends here
   }    
  }
}

答案 3 :(得分:1)

您可以使用TreeMap实现它:

public class NumberOfOccurences {

    public static void main(String[] args) {
        String[] testArr = {"cats", "cats", "cats", "dog", "dog", "fish"};
        String output = countNumberOfChild(testArr);

        System.out.println(output);

    }


    public static String countNumberOfChild(String[] list){
        Arrays.sort(list);

        TreeMap<String,Integer> noOfOccurences = new TreeMap<String,Integer>();


        for(int i=0;i<list.length;i++){
            if(noOfOccurences.containsKey(list[i])){
                noOfOccurences.put(list[i], noOfOccurences.get(list[i])+1);
            }
            else{
                noOfOccurences.put(list[i], 1);
            }
        }

        String outputString = null;
        while(!noOfOccurences.isEmpty()){
            String key = noOfOccurences.firstKey();
            Integer value = noOfOccurences.firstEntry().getValue();
            if(outputString==null){
                outputString = key+"="+value;
            }
            else{
                outputString = outputString + ";" + key+"="+value;
            }
            noOfOccurences.remove(key);
        }

        return outputString;
    }
}

答案 4 :(得分:0)

如果使用ArrayList,那将非常简单。但是因为你特别需要Arrays,这是我的代码。

int lth = words.length;
// Specify a broad length
String[] unique = new String[lth];
int[] times = new int[lth];

int i = 0;
int j = 0;
int count;
while (i < lth) {
    String w = words[i];
    count = 1;
    while(++i < lth && words[i].equals(w)) ++count;
    unique[j] = w;
    times[j++] = count;
}

// Reduce the length of the arrays    
unique = Arrays.copyOf(unique, j);
times  = Arrays.copyOf(times, j);     

for (i = 0; i < unique.length;++i)
    System.out.println(unique[i] + " " + times[i]);

正如您所看到的,真正的问题是在使用它们之前必须指定的数组的长度。使用ArrayLists,您不必。 此外,由于项目的排序更喜欢使用while循环而不是for循环。它看起来不错。

答案 5 :(得分:0)

String s[] = {"Arranged", "Administered", "Advised", "Administered", "Adapted"}; //存储预定义数量的单词

String k="I have administered and advised him to stay away."; //如果字符串包含

,则要匹配的字符串

String ka[]=k.split("\\s"); //在evry空间出现时拆分字符串,以便提取每个单词

for(i=0;i<ka.length;i++)

{for(j=0;j<s.length;j++){

if(ka[i].equalsIgnoreCase(s[j]))

{System.out.println("The occurred words are:" +s[j]);

continue; //继续用于查找是否发生了多个单词

}

}

}

答案 6 :(得分:-1)

这是简单的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