我有一个数组,它的大小是15,每个元素中都有一个正数字。如何计算0到9之间的每一个数字在我的数组中的次数,并打印出“o已出现x次,1次出现y次,2次出现z次”,直到9次。
发布于 2021-12-05 13:36:23
这就是我要做的事情(假设第一个数组中的数字只有一个数字):
let numbersCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //each index is for numbers from 0 to 9
let myArray = [1, 1, 1, 2,...] // array of numbers with positive digits
myArray.foreach(num => numbersCount[num]++);
console.log(numbersCount) // numbersCount = [0, 3, 1, ...]; 其中0是myArray中0的计数,3是1的计数,1是2的计数,.
发布于 2021-12-05 13:41:08
逻辑类似于计数排序。我认为阅读有关计数排序:计数排序的解释对您是有好处的。
下面的代码可能会回答您的问题:
#include <stdio.h>
#define ARR_SIZE 15
#define COUNT_ARR_SIZE 10
int main()
{
int i = 0;
int arr[ARR_SIZE] = {0,1,1,2,2,2,9,3,4,3,2,5,6,7,8};
int countArr[COUNT_ARR_SIZE] = {0};
for(i = 0; i < ARR_SIZE; i++)
countArr[arr[i]]++;
for(i = 0; i < COUNT_ARR_SIZE; i++)
printf("Number %d appears %d times in the array\n", i,countArr[i]);
return 0;
}注意:代码是用C语言编写的。
https://stackoverflow.com/questions/70234689
复制相似问题