算法問題拓展——安全輸入
阿新 • • 發佈:2019-03-16
核心 測試 byte adf eno readfile dma 文件輸入 exception
前情提要
在計算子數組最大和的時候,我們一般只會給出默認情況來測試,數字是常見的,不會出問題。但如果我們是從文件中讀取數據,那麽就很可能出些奇怪的問題(多個空格?這還是正常的)。所以目前需要改進的就是安全輸入問題。
public int FindMaxSubArray(int[] a) { int n = a.length; int[] dp = new int[n]; dp[0] = a[0]; int sum = dp[0]; for(int i = 1; i < n; i++){ dp[i]= a[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); sum = Math.max(sum, dp[i]); } return sum; } 原作者FujiwaranoSai
核心運算采用動態劃分的方法,這是最省內存運算最快的方法。
然後為了支持大數,改寫為BigInteger類
public static BigInteger maxSubArray(ArrayList<BigInteger> A) { int n = A.size(); BigInteger[] dp= new BigInteger[n]; dp[0] = A.get(0); BigInteger max = dp[0]; for (int i = 1; i < n; i++) { // dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); // max = Math.max(max, dp[i]); if (dp[i - 1].compareTo(BigInteger.ZERO) == 1) { dp[i]= A.get(i).add(dp[i - 1]); } else { dp[i] = A.get(i); } if (max.compareTo(dp[i]) == -1) { max = dp[i]; } } return max; }
文件輸入時要註意的是——
- 數字之間的分割方式(但因為方便需要,我選擇只有“ ”分割)
- 分割的數字能否轉換為BigInterger
- 文件讀取會不會出問題
由此需要把異常提示處理好。
public static ArrayList<BigInteger> fileReadIn(Path path) { RandomAccessFile writeFile = null; RandomAccessFile readFile = null; String split = " ";// TODO int number = 100000;// 隨機數個數 int digit = 256;// 隨機數位數 try { writeFile = new RandomAccessFile(path.toFile(), "rw"); Random random = new Random(); writeFile.setLength(0);// 清空文件 for (int i = 0; i < number; i++) { writeFile.writeBytes((new BigInteger(256, new Random())).toString());// 產生digit位的隨機大數 if (i != number - 1) { writeFile.writeBytes(split); } } writeFile.close(); readFile = new RandomAccessFile(path.toFile(), "r"); String fileString; ArrayList<BigInteger> arrayList = new ArrayList<>(); while ((fileString = readFile.readLine()) != "" && fileString != null) { // System.out.println(fileString); for (String temp : fileString.split(split)) { arrayList.add(new BigInteger(temp)); } System.out.println(arrayList); } readFile.close(); return arrayList; // return (BigInteger[]) arrayList.toArray(new BigInteger[arrayList.size()]); } catch (NumberFormatException e) { System.out.println("文件中有錯誤數字" + e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println("未找到文件"); e.printStackTrace(); } catch (IOException e) { System.out.println("讀取出現異常"); e.printStackTrace(); } return null; }
我在文件輸入前先產生了隨機大數,以提供試驗。
結果很成功——
算法問題拓展——安全輸入