Java写的众数问题

来源:互联网 发布:电脑部分软件乱码 编辑:程序博客网 时间:2024/06/14 08:31

算法分析与设计中的众数问题

问题描述:给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集合S中重数最大的元素称为众数。

例如:S={1,2,2,2,3,5},其众数是2,其重数是3.

算法设计:对于给定的由n个自然数组成的多重集合S,计算其众数及重数。

数据输入:输入数据由input.txt提供,文件第一行为多重集合中的元素个数n,在接下来的n行中,每行有一个自然数

数据输出:将计算结果输出到output.txt中。输出有两行,第一行是众数,第二行是重数。


下面是我自己设计的一个基本满足题意的小程序

不足之处:

1.只能输入个位数。。

2.IO流的异常直接抛出没有处理

3.各种绕弯路,简直有种不达目的是不罢休的味道

4.各种BUG

5.。。。。。。

不过不可否认,写这个自己还是学到了很多东西。

啥也不说了,上代码。

package ym520.zhongshu;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class QiuZhongShu {public static void main(String[] args) throws IOException {// 读取input.txt中的数据// 需要注意读取的数据是带有换行符的,需要处理FileReader fr = new FileReader("F:/eclipse-jee/eclipse-jee-kepler/MyPro/算法分析与设计/src/ym520/zhongshu/input.txt");int ch = 0;String str = null;char[] cbuf = new char[1024];while((ch = fr.read(cbuf))!=-1){str = new String(cbuf,0,ch);}//System.out.println(str); //打印一下所取数据// System.getProperty("line.separator")表示换行符String str2 = str.replaceAll(System.getProperty("line.separator"), ""); // 将字符串中的空格" "去掉char[] str3 = str2.toCharArray(); // 将字符串转化为char数组int[] a = new int[(str3.length)-1]; // 因为原数据第一行是元素个数n故在此需要舍弃for(int i=0;i<a.length;i++){a[i] =  Character.getNumericValue(str3[i+1]);  // 利用char的包装类中Character的方法将char型转化为int型//System.out.println(a[i]); // 打印一下}// 再建立一个数组,用来存放每个数出现的次数int[] count = new int[a.length];for(int i = 0;i<a.length;i++){for(int j = 0;j<a.length;j++){if(a[i]==a[j]){count[i]++;}}}// 在获得的count[]数组中获取最大值int max = 0; // 众数出现次数int s = 0; // 众数for(int i =0;i<a.length;i++){if(max<=count[i]){max=count[i];s=a[i];}}// 将结果输出到output.txtFileWriter fw = new FileWriter("F:/eclipse-jee/eclipse-jee-kepler/MyPro/算法分析与设计/src/ym520/zhongshu/output.txt");fw.write(max+"");fw.write(System.getProperty("line.separator"));fw.write(s+"");fw.close();fr.close(); // 关闭资源// 将结果打印在控制台System.out.println(max);System.out.println(s);}}


原创粉丝点击