Java - 计算数组中的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19705499/
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
Java - Counting numbers in array
提问by Ree
I've written a java prog that stores some values:
我编写了一个存储一些值的 java prog:
public class array05 {
public static void main(String[] args) {
//placement of value
int arryNum[] = {2,3,4,5,4,4,3};
//placement of index, to start at 0
for(int counter=0;counter<arryNum.length;counter++){
System.out.println(counter + ":" + arryNum[counter]);
}
}
}
which generate such output:
0:2
1:3
2:4
3:5
4:4
5:4
6:3
产生这样的输出:
0:2
1:3
2:4
3:5
4:4
5:4
6:3
and now I need to count numbers in this output #1. Output #2 should be this:
现在我需要计算这个输出 #1 中的数字。输出 #2 应该是这样的:
1: 0
2: 1
3: 2
4: 3
5: 1
1:0
2:1
3:2
4:3
5:1
It means it counts ONE 2, TWO 3, THREE 4, and only One 5.
这意味着它计数一个 2、两个 3、三个 4 和只有一个 5。
I am not sure how to write the code for output 2. Is a binary search needed here?
我不确定如何编写输出 2 的代码。这里需要二分查找吗?
can anybody shed a light?
有人可以照亮吗?
采纳答案by user902383
if you are expecting in your array values between 1-5 (i assuming this from your expected output)
如果你期望你的数组值在 1-5 之间(我从你的预期输出中假设)
int arryNum[] = { 2, 3, 4, 5, 4, 4, 3 };
int[] counter = new int[] { 0, 0, 0, 0, 0 };
for (int i = 0; i < arryNum.length; i++) {
counter[arryNum[i] - 1]++;
}
for (int i = 0; i < counter.length; i++)
System.out.println((i + 1) + ":" + counter[i]);
回答by Maroun
I advise you to use a Map
:
我建议你使用Map
:
- If a number doesn't exist in it, add it with the valueof 1.
- If the number exists, add 1 to the its value.
- 如果其中不存在数字,则将其与值1相加。
- 如果该数字存在,则为其值加 1。
Then you print the map as a key
and value
.
然后将地图打印为 akey
和value
。
For example, for your array {2,3,4,5,4,4,3}
this will work as follows:
例如,对于您的阵列,{2,3,4,5,4,4,3}
这将按如下方式工作:
Does the map contains the key 2
? No, add it with value 1. (The same for 3
, 4
and 5
)
Does the map contains 4
? Yes! Add 1 to its value. Now the key4 has the valueof 2.
...
地图是否包含密钥2
?不,将其与值 1 添加。(对于3
,4
和相同5
)
地图是否包含4
?是的!将其值加 1。现在键4 的值为2。
...
回答by Dropout
One approach is to use a map. When you read the first array on each number check if it exists in the map, if it does then just increment the value assigned to the number(key), if not then create a new key in the map with value "1".
一种方法是使用地图。当您读取每个数字上的第一个数组时,检查它是否存在于映射中,如果存在,则只增加分配给数字(键)的值,如果不存在,则在映射中创建一个值为“1”的新键。
Check out http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
查看http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
回答by NickJ
Something like this:
像这样的东西:
//numbers to count
int arryNum[] = {2,3,4,5,4,4,3};
//map to store results in
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
//Do the counting
for (int i : arryNum) {
if (counts.containsKey(i) {
counts.put(i, counts.get(i)+1);
} else {
counts.put(i, 1);
}
}
//Output the results
for (int i : counts.keySet()) {
System.out.println(i+":"+counts.get(i));
}
回答by Ben Barkay
This is a solution to this problem:
这是这个问题的解决方案:
import java.util.Arrays;
public class array05 {
public static void main(String[] args) {
//placement of value
int arryNum[] = {2,3,4,5,4,4,3};
// Sort the array so counting same objects is easy
Arrays.sort(arryNum);
int index = 0; // The current index
int curnum; // The current number
int count; // The count of this number
while (index < arryNum.length) {
// Obtain the current number
curnum = arryNum[index];
// Reset the counter
count = 0;
// "while the index is smaller than the amount of items
// and the current number is equal to the number in the current index,
// increase the index position and the counter by 1"
for (; index < arryNum.length && curnum == arryNum[index]; index ++, count++);
// count should contain the appropriate amount of the current
// number now
System.out.println(curnum + ":" + count);
}
}
}
People posted good solutions using Map
, so I figured I'd contribute a good solution that will always work (not just for the current values), without using a Map
.
人们使用 发布了很好的解决方案Map
,所以我想我会贡献一个很好的解决方案,该解决方案将始终有效(不仅适用于当前值),而无需使用Map
.
回答by The_Lost_Avatar
If you don't want to use Map, this is how you would do it with Arrays only(if you have numbers from 1 to 9 only)
Integer[] countArray = new Integer[10]
// Firstly Initialize all elements of countArray to zero
// Then
for(i=0;i<arryNum.length();i++){
int j = arryNum[i];
countArray[j]++;
}
This countArray has number of 0's in 1st position, number of 1s in 2nd position and so on
这个countArray在第一个位置有0的数量,在第二个位置有1的数量等等
回答by Michael Kazarian
Use Map to store count values:
使用 Map 存储计数值:
import java.util.HashMap;
import java.util.Map;
class array05{
public static void main(String[] args){
// Container for count values
Map <Integer, Integer> result = new HashMap<Integer, Integer>();
int arryNum[] = {2,3,4,5,4,4,3};
for(int i: arryNum){ //foreach more correct in this case
if (result.containsKey(i)) result.put(i, result.get(i)+1);
else result.put(i, 1);
}
for (int i: result.keySet()) System.out.println(i + ":" + result.get(i));
}
}
Result below:
结果如下:
2:1
3:2
4:3
5:1
回答by Ruchira Gayan Ranaweera
You can try this way too
你也可以试试这个方法
int arrayNum[] = {2,3,4,5,4,4,3};
Map<Integer,Integer> valMap=new HashMap<>();
for(int i:arrayNum){ // jdk version should >1.7
Integer val=valMap.get(i);
if(val==null){
val=0;
}
valMap.put(i,val+1);
}
Arrays.sort(arrayNum);
for(int i=0;i< arrayNum[arrayNum.length-1];i++){
System.out.println(i+1+" : "+((valMap.get(i+1)==null) ? 0:valMap.get(i+1)));
}
Out put
输出
1 : 0
2 : 1
3 : 2
4 : 3
5 : 1
But following way is better
但以下方式更好
int arrayNum[] = {2,3,4,5,4,4,3};
Arrays.sort(arrayNum);
int countArray[]=new int[arrayNum[arrayNum.length-1]+1];
for(int i:arrayNum){
countArray[i]= countArray[i]+1;
}
for(int i=1;i<countArray.length;i++){
System.out.println(i+" : "+countArray[i]);
}
Out put
输出
1 : 0
2 : 1
3 : 2
4 : 3
5 : 1
回答by Vallerious
I would prefer some generic solution like this one:
我更喜欢这样的通用解决方案:
public static <T> Map<T, Integer> toCountMap(List<T> itemsToCount) {
Map<T, Integer> countMap = new HashMap<>();
for (T item : itemsToCount) {
countMap.putIfAbsent(item, 0);
countMap.put(item, countMap.get(item) + 1);
}
return countMap;
}