/
Lisson
/
combinatorics
Обзор
Документация
Войти
/
Lisson
/
combinatorics
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
MainWindow.xaml.cs
787 строк
26 KB
Ruslan
Добавьте файлы проекта.
12 июл 2024, 15:13
12 июл 2024, 15:13
eb0ed24
Код
Авторство
О чём код?
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Security.Policy; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using static System.Net.Mime.MediaTypeNames; //using Color = System.Windows.Media.Color; namespace Combinator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { List<Brush> listBrush = new List<Brush>(); public MainWindow() { InitializeComponent(); //wbSample.Source = new Uri("Data/peres1.html", UriKind.Relative); //string CurDir = Directory.GetCurrentDirectory(); // wbSample.Source = new Uri(String.Format("file:///{0}/Data/peres1.html", CurDir)); //string path = + @"/Data/peres1.html"; //wbSample.Navigate(path); newcolors(); } #region 1 перестановки ////////////////// 1 void newcolors() { var colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0xED, 0x3D, 0x52); //красный ED3D52 listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0x08, 0xBE, 0x3E); //зеленый ABA63E listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0x64, 0x97, 0xC4); //синий 6497C4 listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0xB3, 0x9E, 0xD9); //сиреневый B39ED9 listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0xD2, 0xE4, 0xFA); //голубой D2E4FA listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0xF2, 0xC6, 0xE1); //светлорозовый F2C6E1 listBrush.Add(colorBrush); colorBrush = new SolidColorBrush(); colorBrush.Color = System.Windows.Media.Color.FromRgb(0xDA, 0xF4, 0xC6); //светлозеленый DAF4C6 listBrush.Add(colorBrush); } private void Button_Click(object sender, RoutedEventArgs e) { int x = int.Parse(tInput1.Text); tResult1.Text = Factorial(x).ToString(); string[] mas = M1(tInput1text.Text); string s = ""; if (mas != null) { for (int i = 0; i < mas.Length; i++) { if (mas[i] != null) s += (i + 1).ToString() + " \t" + mas[i].ToString() + "\n"; } tResult11.Text = s; /* if (x == tInput1text.Text.Length) { stackPanel1.Children.Clear(); // передаем <количество уникальных элементов> <список вариантов перестановок> stackPanel1.Children.Add(StackCircle(x, mas)); } */ } } private void tInput1text_TextChanged(object sender, TextChangedEventArgs e) { tInput1.Text = tInput1text.Text.Length.ToString(); } // факториал через итерации decimal Factorial(int c) { decimal res = 1; for (int i = 1; i <= c; i++) { res = res * i; } return res; } // факториал через рекурсию decimal Rfactorial(int a) { if (a == 1) return a; return a * Rfactorial(a - 1); } //1) перестановки Визуализация, список private string[] M1(string text) { string[] mas; int index = 0, b = 0; mas = new string[(int)Factorial(text.Length)]; //! Возможна Потеря данных decimal -> int M1allwords(mas, text, "", ref index, ref b); //Console.ReadLine(); return mas; } static void M1allwords(string[] mas, string left, string processed, ref int index, ref int b) { if (left.Length != 1) for (int i = 0; i < left.Length; i++) M1allwords(mas, M1delsim(left, i), processed + left[i], ref index, ref b); else if (M1unical(processed + left, mas, index)) { mas[index++] = processed + left; } //return mas; } static string M1delsim(string s, int num) { string a = ""; for (int i = 0; i < s.Length; i++) if (i != num) a = a + s[i]; return a; } static bool M1unical(string s, string[] mas, int index) { //for (int i = 0; i < index; i++) // if (s == mas[i]) return false; return true; } ////////////////// end 1 .перестановки Визуализация, список #endregion //рисуем кружки //1) /* void fun1(int c, string[] mas) { //очищаем поле(стэк) вывода кружков stackPanel1.Children.Clear(); Dictionary<string, int> dic = new Dictionary<string, int>(); for (int i = 0; i < c; i++) { if (!dic.ContainsKey(mas[0][i].ToString())) dic.Add(mas[0][i].ToString(), i); } if (listBrush.Count < c) { int countNewColors = c - listBrush.Count; //создаем список кистей(цветов) которыми будут закрашиваться элементы for (int i = 0; i < countNewColors; i++) { SolidColorBrush colorBrush = new SolidColorBrush(); Random random = new Random(); byte R = (byte)random.Next(0, 255); byte G = (byte)random.Next(0, 255); byte B = (byte)random.Next(0, 255); colorBrush.Color = Color.FromRgb(R, G, B); listBrush.Add(colorBrush); } } for (int line = 0; line < mas.Length; line++) { StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Horizontal; //создаем круги, закрашиваем, и добавляем в стек панель как дочерний элемент for (int column = 0; column < c; column++) { Ellipse ellipse = new Ellipse(); ellipse.Width = 10; ellipse.Height = 10; string s1 = mas[line]; string x = s1[column].ToString(); //int y = int.Parse(x); //int y = x - '0'; ellipse.Fill = listBrush[dic[x]]; ellipse.Stroke = new SolidColorBrush(Colors.Black); stackPanel.Children.Add(ellipse); } //выводим в интерфейс stackPanel1.Children.Add(stackPanel); } } */ // StackPanel StackCircle(int c, string[] mas) { StackPanel stackPanel0 = new StackPanel(); Dictionary<string, int> dic = new Dictionary<string, int>(); //for (int i = 0; i < c; i++) for (int i = 0; dic.Count < c; i++) { if (!dic.ContainsKey(mas[0][i].ToString())) dic.Add(mas[0][i].ToString(), i); } // Если колич цветов нехватает для сопоставления каждому уник элементу // создаем новые рандомно if (listBrush.Count < c) { int countNewColors = c - listBrush.Count; //создаем список кистей(цветов) которыми будут закрашиваться элементы for (int i = 0; i < countNewColors; i++) { SolidColorBrush colorBrush = new SolidColorBrush(); Random random = new Random(); byte R = (byte)random.Next(0, 255); byte G = (byte)random.Next(0, 255); byte B = (byte)random.Next(0, 255); colorBrush.Color = System.Windows.Media.Color.FromRgb(R, G, B); listBrush.Add(colorBrush); } } for (int line = 0; line < mas.Length; line++) { StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Horizontal; //создаем круги, закрашиваем, и добавляем в стек панель как дочерний элемент for (int column = 0; column < c; column++) { Ellipse ellipse = new Ellipse(); ellipse.Width = 10; ellipse.Height = 10; string s1 = mas[line]; string x = s1[column].ToString(); //int y = int.Parse(x); //int y = x - '0'; ellipse.Fill = listBrush[dic[x]]; ellipse.Stroke = new SolidColorBrush(Colors.Black); stackPanel.Children.Add(ellipse); } //добавляем в общий стек stackPanel0.Children.Add(stackPanel); } return stackPanel0; } StackPanel StackCircle(int c, List<string> mas) { StackPanel stackPanel0 = new StackPanel(); Dictionary<string, int> dic = new Dictionary<string, int>(); for (int i = 0; i < c; i++) { if (!dic.ContainsKey(mas[0][i].ToString())) dic.Add(mas[0][i].ToString(), i); } // Если колич цветов нехватает для сопоставления каждому уник элементу // создаем новые рандомно if (listBrush.Count < c) { int countNewColors = c - listBrush.Count; //создаем список кистей(цветов) которыми будут закрашиваться элементы for (int i = 0; i < countNewColors; i++) { SolidColorBrush colorBrush = new SolidColorBrush(); Random random = new Random(); byte R = (byte)random.Next(0, 255); byte G = (byte)random.Next(0, 255); byte B = (byte)random.Next(0, 255); colorBrush.Color = System.Windows.Media.Color.FromRgb(R, G, B); listBrush.Add(colorBrush); } } for (int line = 0; line < mas.Count; line++) { StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Horizontal; //создаем круги, закрашиваем, и добавляем в стек панель как дочерний элемент for (int column = 0; column < c; column++) { Ellipse ellipse = new Ellipse(); ellipse.Width = 10; ellipse.Height = 10; string s1 = mas[line]; string x = s1[column].ToString(); //int y = int.Parse(x); //int y = x - '0'; ellipse.Fill = listBrush[dic[x]]; ellipse.Stroke = new SolidColorBrush(Colors.Black); stackPanel.Children.Add(ellipse); } //добавляем в общий стек stackPanel0.Children.Add(stackPanel); } return stackPanel0; } #region 2 перестановки с повт ////////////////// 2 private void btn2_Click(object sender, RoutedEventArgs e) { int[] ires = f2_sumArg(); //пример: [2, 2, 1] decimal x = Func2(ires); // количество вариантов tResult2.Text = x.ToString(); // создать список вариантов List<string> mas = M2(tInput2word.Text); string s = ""; List<string> mas_distinct = mas.Distinct().ToList(); if (mas_distinct != null) { for (int i = 0; i < mas_distinct.Count; i++) { if (mas_distinct[i] != null) s += (i + 1).ToString() + " \t" + mas_distinct[i].ToString() + "\n"; } tResult2text.Text = s; } Dictionary<string, int> keyValuePairs = getElements_per2(); stackPanel2.Children.Clear(); // передаем <Количество уникальных элементов> <Список вариантов перестановок> stackPanel2.Children.Add(StackCircle(tInput2word.Text.Length, mas_distinct)); } // получение словаря с ключом = уник элемент private Dictionary<string, int> getElements_per2() { Dictionary<string, int> keyValuePairs = new Dictionary<string, int>(); string text = tInput2word.Text; // aabbc for (int i = 0; i < text.Length; i++) { if (!keyValuePairs.ContainsKey(text[i].ToString())) keyValuePairs.Add(text[i].ToString(), 1); else keyValuePairs[text[i].ToString()] += 1; } return keyValuePairs; } // При вводе слова происходит пересчет количества повторяющихся значений private void tInput2word_TextChanged(object sender, TextChangedEventArgs e) { Dictionary<string, int> keyValuePairs = getElements_per2(); tInput2.Text = ""; string s = string.Empty; foreach (var key in keyValuePairs) { s += key.Value.ToString() + " "; } tInput2.Text = s.ToString(); } // при изменении заполняется поле с количеством элементов (УДАЛИТЬ. НЕ НУЖНА) private void tInput2_TextChanged(object sender, TextChangedEventArgs e) { int[] ires = f2_sumArg(); int sum = 0; for (int i = 0; i < ires.Length; i++) { sum = sum + ires[i]; } tCount2.Text = sum.ToString(); } int[] f2_sumArg() { string s = tInput2.Text; string[] res = s.Split(" ", StringSplitOptions.RemoveEmptyEntries); bool isexception = false; int sum = 0; int[] ires = new int[res.Length]; try { for (int i = 0; i < res.Length; i++) { ires[i] = int.Parse(res[i]); } } catch (ArgumentNullException) { isexception = true; //throw new Exception("Пустой аргумент"); } catch (FormatException) { isexception = true; //throw new Exception("Неправильный формат аргумента"); } catch (OverflowException) { isexception = true; //throw new Exception("Переполнение переменной"); } /* if (!isexception) { for (int i = 0; i < ires.Length; i++) { sum = sum + ires[i]; } }*/ return ires; } // вычисление количества вариантов decimal Func2(int[] ires) { int x = ires[0]; for (int i = 1; i < ires.Length; i++) { x += ires[i]; } decimal a = Factorial(x); decimal b = Factorial(ires[0]); for (int i = 1; i < ires.Length; i++) { b = b * Factorial(ires[i]); } return a / b; } private List<string> M2(string text) { List<string> mas = new List<string>(); int index = 0, b = 0; M2allwords(mas, text, "", ref index, ref b); return mas; } static void M2allwords(List<string> mas, string left, string processed, ref int index, ref int b) { if (left.Length != 1) for (int i = 0; i < left.Length; i++) M2allwords(mas, M2delsim(left, i), processed + left[i], ref index, ref b); else //mas[index] = processed + left; mas.Add(processed+left); } static string M2delsim(string s, int num) { string a = ""; for (int i = 0; i < s.Length; i++) if (i != num) a = a + s[i]; return a; } ////////////////// end 2 #endregion #region 3 размещения private void btn3_Click(object sender, RoutedEventArgs e) { int n = int.Parse(tInput3n.Text); int k = int.Parse(tInput3k.Text); decimal x = Factorial(n) / Factorial(n - k); tResult3.Text = x.ToString(); //вывод комбинаций tResult31.Text = Pnr3(tInput1text3.Text, k); } private void tInput1text3_TextChanged(object sender, TextChangedEventArgs e) { tInput3n.Text = tInput1text3.Text.Length.ToString(); } string Pnr3(string word, int size) { ArrayList result = new ArrayList(); result = getCombinations3(word, size); int i = 1; string textResult = ""; foreach (string s in result) { textResult += i.ToString() + " \t" + s + "\n"; i++; } return textResult; } ArrayList getCombinations3(string word, int size) { ArrayList result = new ArrayList(); if (size <= 1) { int chr = 0; foreach (char c in word) { result.Add(Convert.ToString(c)); chr++; } return result; } string tempword = word; int i = 0; foreach (char c in word) { foreach (string s in getCombinations3(tempword.Remove(i, 1), size - 1)) { result.Add(Convert.ToString(c) + s); } i++; } return result; } #endregion #region 4 размещения с повт ////////////////// 4 private void btn4_Click(object sender, RoutedEventArgs e) { int n = int.Parse(tInput4n.Text); int k = int.Parse(tInput4k.Text); double x = Math.Pow(n, k); tResult4.Text = x.ToString(); //результат количество //вывод комбинаций tResult41.Text = Pnr4(tInput1text4.Text, k); } string Pnr4(string word, int size) { ArrayList result = new ArrayList(); result = getCombinations4(word, size); int i = 1; string textResult = ""; foreach (string s in result) { textResult += i.ToString() + " \t" + s + "\n"; i++; } return textResult; } ArrayList getCombinations4(string word, int size) { ArrayList result = new ArrayList(); if (size <= 1) { foreach (char c in word) { result.Add(Convert.ToString(c)); } return result; } foreach (char c in word) { foreach (string s in getCombinations4(word, size - 1)) { result.Add(Convert.ToString(c) + s); } } return result; } private void tInput1text4_TextChanged(object sender, TextChangedEventArgs e) { tInput4n.Text = tInput1text4.Text.Length.ToString(); } ////////////////// end 4 #endregion #region 5 сочетания private void btn5_Click(object sender, RoutedEventArgs e) { int n = int.Parse(tInput5n.Text); int k = int.Parse(tInput5k.Text); decimal x = Factorial(n) / (Factorial(n - k) * Factorial(k)); tResult5.Text = x.ToString(); ; //вывод комбинаций tResult51.Text = Cn5(tInput1text5.Text, k); } private void tInput1text5_TextChanged(object sender, TextChangedEventArgs e) { tInput5n.Text = tInput1text5.Text.Length.ToString(); } string Cn5(string word, int size) { ArrayList result = getCombinations5(word, word.Length, size); int i = 1; string textResult = ""; foreach (string s in result) { textResult += i.ToString() + " \t" + s + "\n"; i++; } return textResult; } ArrayList getCombinations5(string word, int size, int komb) { ArrayList result = new ArrayList(); string tempword = word; if (komb == 1) { //перечисление по одному элементу for (int i = 0; i < size; i++) { result.Add(Convert.ToString(word[i])); } } else if (komb >= 2) { //сочетания из двух и более элементов for (int i = 0; i < size; i++) { char c = word[i]; if (word.Length >= 2) { tempword = tempword.Remove(0, 1); ArrayList result2 = new ArrayList(); result2 = getCombinations5(tempword, tempword.Length, komb - 1); for (int j = 0; j < result2.Count; j++) { result.Add(Convert.ToString(c) + result2[j]); } } else { break; } } } return result; } #endregion #region 6 сочетания с повт private void btn6_Click(object sender, RoutedEventArgs e) { int n = int.Parse(tInput6n.Text); int k = int.Parse(tInput6k.Text); decimal a = Factorial(k + n - 1); decimal b = Factorial(n - 1) * Factorial(k); tResult6.Text = (a / b).ToString(); //вывод комбинаций tResult61.Text = Start(tInput1text6.Text, n, k); } private void tInput1text6_TextChanged(object sender, TextChangedEventArgs e) { tInput6n.Text = tInput1text6.Text.Length.ToString(); } bool NextSet(int[] a, int n, int m, string word, string[] s) { int j = m - 1; while (j >= 0 && a[j] == n) j--; if (j < 0) return false; if (a[j] >= n) j--; a[j]++; s[j] = word[a[j]-1].ToString(); if (j == m - 1) return true; for (int k = j + 1; k < m; k++) { a[k] = a[j]; s[k] = s[j]; } return true; } string Print(int[] a, int n, string[] s) { string result = ""; for (int i = 0; i < n; i++) { //result += a[i]; result += s[i]; } result += "\n"; return result; } string Start(string word, int n, int k) { int[] a; string result = ""; int h = n > k ? n : k; // размер массива а выбирается как max(n,m) a = new int[h]; string[] s = new string[h]; for (int i = 0; i < h; i++) { a[i] = 1; s[i] = word[0].ToString(); } result += Print(a, k, s); while (NextSet(a, n, k, word, s)) result += Print(a, k, s); result = Cn6(result); return result; } string Cn6(string result) { int i = 1; string textResult = ""; foreach (string s in result.Split("\n")) { if (s == "") continue; textResult += i.ToString() + " \t" + s + "\n"; i++; } return textResult; } #endregion } }