二维数组最大子数组
在上次的基础之上添加了向文件中读入读出随机数,并将随机数放入数组中,再从数组中求最大子数组的和,并且加入了数量级的要求,需要非常注意的是,产生的数当大到一定程度时,long long int也无法容纳时,会发生数据的溢出,所以必须要利用到大数类来防止数据的溢出,而且,不管在读入文件还是读出文件时,都需要涉及数据类型的转换,还需要考虑到数据的精度缺失,所以当数据大到一定的程度时,在难度上会有非常大的提升,我在代码中并没有用到biginteger类,这是最大的缺点,因为对biginteger太不熟悉了,而且在对数组进行比较时,都需要利用函数来比较了,貌似不能用简单的大于小于号来比较,而且读入读出数据时,都需要进行数据转换,仅用了int,所以只能进行较小数据的比较,在下面的博客中我会对其进行提升。
下面代码用来产生十万个-10到10的随机数保存在txt文件中:
package b;import java.util.*;import java.io.*;public class getrandom { public static void main(String[] args) { // TODO Auto-generated method stub try{ File f=new File("C:\\w.txt"); FileOutputStream fos = new FileOutputStream(f); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); int n; for (int i = 0; i < 100000; i++) { Random rand = new Random(); n = rand.nextInt(20)-10; bw.write(String.valueOf(n));//整型转换为字符串类型 bw.newLine(); } bw.close(); } catch(Exception e) { System.out.println("文件打开失败"); } } }
下面代码用来将产生的随机数存放在一维数组中计算最大子数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | package a; import java.util.*; import java.io.*; public class m { static Scanner sc= new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub try { File file= new File( "C:\\w.txt" ); File file1= new File( "C:\\w.txt" ); BufferedReader is= new BufferedReader( new FileReader(file)); BufferedReader im= new BufferedReader( new FileReader(file1)); //在一个函数中想读取某个文件两次的话必须 //定义两个文件对象 int m= 0 ; int l= 0 ; String i; while ((i=im.readLine())!= null ){ l++; } int a []= new int [l]; while ((i=is.readLine())!= null ){ a[m]= Integer.valueOf(i).intValue(); m++; } is.close(); im.close(); int q,w,e; int max[]= new int [l]; for (q= 0 ;q<l;q++){ max[q]=a[q]; e=a[q]; for (w=q+ 1 ;w<l;w++){ e=e+a[w]; if (e>max[q]) { max[q]=e; } } } int ma=max[ 0 ]; for (q= 1 ;q<l;q++) { if (max[q]>ma) { ma=max[q]; } } System.out.println( "所有子数组的和的最大值为" +ma); } catch (Exception e){ System.out.println( "文件打开失败" ); } } } |