Java 计算数组中元素的出现次数?(爪哇)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21228384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count occurrences of elements inside array? (Java)
提问by helloMundo
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.
我一直在努力找出这个算法大约 6 个小时,但似乎无法提出解决方案。我正在尝试计算数组中元素的出现次数,可能还有两个单独的数组。一个用于唯一实例,另一个用于这些实例发生的次数。我在这里发现了一些关于数组列表和 hashMap 的其他想法,但我只能使用数组。
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.
这是我所有尝试后的所有代码。
回答by Pierre
Here is plain simple JavaScript:
这是简单的 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
回答by ansible
This is how it could be done using only arrays. The tricky part is you must know the number of items before the array is created. So I had to create my own function to create a bigger array. Actually two, one for the count and one for the unique values.
这就是仅使用数组就可以完成的方式。棘手的部分是您必须在创建数组之前知道项目的数量。所以我必须创建自己的函数来创建一个更大的数组。实际上有两种,一种用于计数,一种用于唯一值。
If you can use Vectors you will be better off. Here is it without vetors:
如果你可以使用 Vectors 你会更好。这是没有支持者的情况:
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;
}
}
As mentioned in the comments, if we know the array is in order, then we don't need to search through the entire previous array and can just check uniqueValues directly.
正如评论中提到的,如果我们知道数组是有序的,那么我们不需要搜索整个前面的数组,直接检查 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;
}
}
回答by martiansnoop
Assuming that the words
array has at least one element:
假设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;
}
}
As other answers have mentioned, this problem could be simplified by using a List such an ArrayList to store the results.
正如其他答案所提到的,可以通过使用 List 这样的 ArrayList 来存储结果来简化这个问题。
回答by user3173787
It would be very simple if you use ArrayList. But since you want especially Arrays, here's my code.
如果您使用 ArrayList,这将非常简单。但是因为你特别想要数组,这是我的代码。
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]);
As you can see the real problem is the length of the Arrays that you have to specify before using them. With ArrayLists you wouldn't have to. Also, since the items are sorted prefer using a while loop instead of a for loop. It just looks good.
正如您所看到的,真正的问题是在使用数组之前必须指定数组的长度。有了 ArrayLists,您就不必这样做了。此外,由于项目的排序更喜欢使用 while 循环而不是 for 循环。它看起来不错。
回答by hemanth
Make unique, times as instance variable so that you can retrieve them from another class using getter methods.
将唯一的时间作为实例变量,以便您可以使用 getter 方法从另一个类中检索它们。
Note: Modified code can be found through comments (for line "Added line". for block between "Added code starts here" to "Added code ends here"). I tried to explain the implementation in code. Please let me know through comments if I need to work more on my documentation skills
注意:修改后的代码可以通过注释找到(对于“添加的行”行。对于“添加的代码从这里开始”到“添加的代码在这里结束”之间的块)。我试图用代码解释实现。如果我需要更多地提高我的文档技能,请通过评论告诉我
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
}
}
}
回答by mohaksharma
You can achieve it using TreeMap:
您可以使用 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;
}
}
回答by Aradhya Jain
String s[] = {"Arranged", "Administered", "Advised", "Administered", "Adapted"};
//Store a pre-defined amount of words
String s[] = {"Arranged", "Administered", "Advised", "Administered", "Adapted"};
//存储预先定义的单词数量
String k="I have administered and advised him to stay away.";
//A string that you want to match if it contains those words
String k="I have administered and advised him to stay away.";
//一个你想匹配的字符串,如果它包含这些词
String ka[]=k.split("\\s");
//Split the string on evry space occurrence so that it extracts each word
String ka[]=k.split("\\s");
//在每个空格出现时拆分字符串,以便提取每个单词
for(i=0;i<ka.length;i++)
for(i=0;i<ka.length;i++)
{for(j=0;j<s.length;j++){
{for(j=0;j<s.length;j++){
if(ka[i].equalsIgnoreCase(s[j]))
if(ka[i].equalsIgnoreCase(s[j]))
{System.out.println("The occurred words are:" +s[j]);
{System.out.println("The occurred words are:" +s[j]);
continue;
//Continue is used to find if more that one word has occurred
continue;
//continue 用于查找是否超过一个单词出现
}
}
}
}
}
}