统计随机生成的数出现次数

统计随机生成的数出现次数

/**
 * 功能:定义一个一维数组,其中存储随机生成的1000个1到100以内的整数,统计每个整数出现的次数
 * 时间:2014年6月4日16:03:54
 * 作者:cutter_point
 */
package com.lesson4;

import java.util.*;

public class Demo4_9
{
	public static void main(String [] args)
	{
		//1、生成1000个100以内的整数
		int a[]=new int[1000];
		for(int i=0 ; i<a.length ; ++i)
		{
			a[i]=(int)(Math.random()*100);
		}
		//2、用数组统计出现的次数
		int b[]=new int[100];
		//吧数组初始化为0
		for(int i=0 ; i<b.length ; ++i)
		{
			b[i]=0;
		}
		//统计
		for(int i=0 ; i<a.length ; ++i)
		{
			b[a[i]]++;
		}
		//输出
		for(int i=0 ; i<b.length ; ++i)
		{
			System.out.println(i+"出现了:"+b[i]+" 次");
		}
		
	}
}


以下是Python代码实现: ```python import random # 生成100随机 nums = [random.randint(1, 100) for i in range(100)] # 排序并统计出现次数 sorted_nums = sorted(nums, reverse=True) count_dict = {} for num in sorted_nums: if num not in count_dict: count_dict[num] = 1 else: count_dict[num] += 1 # 输出结果 print("降序排序后的列:", sorted_nums) print("每个出现的次数:", count_dict) ``` 输出结果类似于: ``` 降序排序后的列: [100, 100, 99, 98, 97, 96, 95, 95, 94, 93, 92, 92, 92, 91, 90, 90, 89, 88, 87, 86, 85, 85, 84, 84, 83, 82, 82, 81, 80, 80, 79, 78, 77, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 38, 37, 36, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 每个出现的次数: {100: 2, 99: 1, 98: 1, 97: 1, 96: 1, 95: 2, 94: 1, 93: 1, 92: 3, 91: 1, 90: 2, 89: 1, 88: 1, 87: 1, 86: 1, 85: 2, 84: 2, 83: 1, 82: 2, 81: 1, 80: 2, 79: 1, 78: 1, 77: 2, 76: 1, 75: 1, 74: 1, 73: 1, 72: 1, 71: 1, 70: 1, 69: 1, 68: 1, 67: 2, 66: 1, 65: 1, 64: 1, 63: 1, 62: 1, 61: 1, 60: 1, 59: 1, 58: 1, 57: 1, 56: 1, 55: 1, 54: 1, 53: 1, 52: 1, 51: 2, 50: 1, 49: 1, 48: 1, 47: 1, 46: 1, 45: 1, 44: 1, 43: 1, 42: 1, 41: 1, 40: 1, 39: 1, 38: 2, 37: 1, 36: 2, 35: 1, 34: 1, 33: 1, 32: 1, 31: 1, 30: 1, 29: 1, 28: 1, 27: 1, 26: 1, 25: 1, 24: 1, 23: 1, 22: 1, 21: 1, 20: 2, 19: 1, 18: 1, 17: 1, 16: 1, 15: 1, 14: 1, 13: 1, 12: 1, 11: 1, 10: 1, 9: 1, 8: 1, 7: 1, 6: 1, 5: 1, 4: 1, 3: 1, 2: 1, 1: 1} ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值