求一個已知二維陣列的最大子陣列和(司宇,廖強)
阿新 • • 發佈:2018-11-07
小組成員:司宇,廖強
設計流程:
設計介面:
程式設計:1.封裝一個求二維整陣列最大子陣列和的子程式;
2.設計一個主函式,主函式可以呼叫子函式;
3.在主函式中新增程式碼,使主函式可以呼叫一個TXT檔案並且得到要求的結果。
遇到的問題:1.在呼叫txt檔案時,沒辦法使呼叫檔案前兩行分別顯示行數和列數;
2.在呼叫子函式的時候,不知道應該賦值給子函式一個什麼型別的引數;
3.如何將String型別的二維陣列轉化為int型別。
解決方案:(當我們遇到問題的時候,我們兩人分別獨立思考解決方案,然後互相分析對方的解決方案,最後得到結局方案。)
1.將Txt檔案中的第一行和第二行分別賦值給行和列,計算二維陣列時從第三行開始計算。
2.將一個二維陣列和改陣列的行和列一起賦值給子函式,程式碼如下:maxsum = maxSubArray(intlist, h, l);
3.intlist[i-2] = Array.ConvertAll<string, int>(str[i].Split(','), p => { return int.Parse(p); })。
原始碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public int maxSubArray(int[][] a, int n, int m) { int[][] p = new int[m][]; int i, j; if (m == 0 || n == 0) return 0; for (i = 0; i < n; i++) { p[i] = new int[m]; for (j = 0; j < m; j++) { if (i == 0) { if (j == 0) p[i][j] = a[i][j]; else p[i][j] = p[i][j - 1] + a[i][j]; } else { if (j == 0) p[i][j] = p[i - 1][j] + a[i][j]; else p[i][j] = p[i][j - 1] + p[i - 1][j] - p[i - 1][j - 1] + a[i][j]; } } } int temp; int max = a[0][0]; int ans = a[0][0]; if (m == 1) { for (i = 0; i < n; i++) { for (j = i; j < n; j++) { if (i == 0) { temp = p[j][m - 1]; } else { temp = p[j][m - 1] - p[i - 1][m - 1]; } if (ans < temp) ans = temp; } } } else { for (i = 0; i < n; i++) { for (j = i; j < n; j++) { if (i == 0) { temp = p[j][m - 1] - p[j][m - 2]; } else { temp = p[j][m - 1] - p[j][m - 2] - p[i - 1][m - 1] + p[i - 1][m - 2]; } for (int k = m - 2; k >= 0; k--) { if (temp < 0) temp = 0; if (i == 0) { if (k == 0) temp += p[j][k]; else temp += p[j][k] - p[j][k - 1]; } else { if (k == 0) temp += p[j][k] - p[i - 1][k]; else temp += p[j][k] - p[j][k - 1] - p[i - 1][k] + p[i - 1][k - 1]; } if (ans < temp) ans = temp; } } } } return ans; } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.Filter = "文字檔案|*.txt"; if (file.ShowDialog() == DialogResult.OK) { StreamReader sr = new StreamReader(file.FileName, System.Text.Encoding.Default); textBox1.Text = sr.ReadToEnd(); sr.Close(); } else return; int maxsum; /*double hang = Convert.ToDouble(textBox3.Text); double lie = Convert.ToDouble(textBox4.Text);*/ string[] str = textBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); int[][] intlist = new int[str.Length][]; int h = (int)Convert .ToDouble( str[0]); int l = (int)Convert.ToDouble(str[1]); for (int i = 2; i < str.Length; i++) { intlist[i-2] = Array.ConvertAll<string, int>(str[i].Split(','), p => { return int.Parse(p); }); } maxsum = maxSubArray(intlist, h, l); textBox2.Text = maxsum.ToString(); textBox3.Text =Convert.ToString(h); textBox4.Text = Convert.ToString(l); }
執行結果:1.TXT檔案截圖:
2.執行結果圖: