using System;
using System.Collections.Generic;
using System.Linq;
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 LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
namespace numbersystem
{
///
/// Логика взаимодействия для MainWindow.xaml
///
public partial class MainWindow : Window
{
private numbersystemContext _context;
public MainWindow()
{
InitializeComponent();
_context = new numbersystemContext();
str.Focus();
Load();
Diagram();
DataContext = this;
dia.Series = SeriesCollection;
}
// заполнение истории
private void Load()
{
historyGrid.ItemsSource = _context.history.OrderByDescending(I => I.id).ToList();
}
SeriesCollection SeriesCollection { get; set; }
// заполнение диаграммы
private void Diagram()
{
int binCount = _context.history.Where(i => i.notation == "2").Count();
int octCount = _context.history.Where(i => i.notation == "8").Count();
int hexCount = _context.history.Where(i => i.notation == "16").Count();
SeriesCollection = new SeriesCollection
{
new PieSeries
{
Title = "Двоичная",
Values = new ChartValues { new ObservableValue(binCount) },
DataLabels = true,
Fill = System.Windows.Media.Brushes.Lavender
},
new PieSeries
{
Title = "Восьмеричная",
Values = new ChartValues { new ObservableValue(octCount) },
DataLabels = true,
Fill = System.Windows.Media.Brushes.MediumPurple
},
new PieSeries
{
Title = "Шестнадцатеричная",
Values = new ChartValues { new ObservableValue(hexCount) },
DataLabels = true,
Fill = System.Windows.Media.Brushes.Indigo
}
};
}
// выбор системы счисления
int ss = 0;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
if (Convert.ToString(selectedItem.Content) == "Двоичная")
ss = 2;
else if (Convert.ToString(selectedItem.Content) == "Восьмеричная")
ss = 8;
else if (Convert.ToString(selectedItem.Content) == "Шестнадцатиричная")
ss = 16;
str.Focus();
}
string expression; // переменная для выражения
int res; // переменная для результата
// ввод цифр, букв и знаков операций
private void str_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// при нажатии на цифры или буквы
if(Int32.TryParse(e.Text, out int n)
|| e.Text == "a" || e.Text == "b" || e.Text == "c" || e.Text == "d" || e.Text == "e" || e.Text == "f")
{
str.Text += e.Text;
}
// при нажатии на знаки операций
if(e.Text == "+" || e.Text == "-" || e.Text == "/" || e.Text == "*" || e.Text == "%")
{
str.Text += " ";
str.Text += e.Text;
str.Text += " ";
}
// при нажатии на "равно"
if(e.Text == "=")
{
if(ss == 0)
{
MessageBox.Show("Не выбрана система счисления");
return;
}
// записываем выражение в переменную
expression = str.Text;
// разбиваем строку на массив
string[] arr = expression.Split(' ');
try
{
// перебираем массив и считаем высокоприоритетные операции
for (int i = 0; i < arr.Length; i++)
{
// умножение
if (arr[i] == "*")
{
if (arr[i - 1] == "_")
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) * Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 2] = "_";
arr[i + 1] = "_";
}
else
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) * Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 1] = "_";
arr[i + 1] = "_";
}
}
// деление
else if (arr[i] == "/")
{
if (arr[i - 1] == "_")
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) / Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 2] = "_";
arr[i + 1] = "_";
}
else
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) / Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 1] = "_";
arr[i + 1] = "_";
}
}
// остаток от деления
else if (arr[i] == "%")
{
if (arr[i - 1] == "_")
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) % Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 2] = "_";
arr[i + 1] = "_";
}
else
{
arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) % Convert.ToInt32(arr[i + 1], ss), ss);
arr[i - 1] = "_";
arr[i + 1] = "_";
}
}
}
// узнаем размер будущего массива
int l = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != "_")
{
l++;
}
}
// записать в новый массив результат предыдущего шага
string[] arr2 = new string[l];
int j = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != "_")
{
arr2[j] = arr[i];
j++;
}
}
// первое число массива присваиваем переменной
res = Convert.ToInt32(arr2[0], ss);
// перебираем массив и считаем остальные операции
for (int i = 1; i < arr2.Length; i++)
{
// сложение
if (arr2[i] == "+")
{
res += Convert.ToInt32(arr2[i + 1], ss);
}
// вычитание
else if (arr2[i] == "-")
{
res -= Convert.ToInt32(arr2[i + 1], ss);
}
}
// выводим результат
str.Text = Convert.ToString(res, ss);
// добавляем вычисление в бд
history record = new history()
{
inquiry = expression,
result = Convert.ToString(res, ss),
notation = Convert.ToString(ss)
};
_context.history.Add(record);
_context.SaveChanges();
Load();
Diagram();
dia.Series = SeriesCollection;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
// кнопки стереть
private void str_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Delete)
{
str.Text = "";
}
if(e.Key == Key.Back)
{
if (str.Text.Length > 0)
{
if (str.Text[str.Text.Length - 1] == ' ') //если последний символ это знак операции
{
for(int i = 0; i < 3; i++)
str.Text = str.Text.Substring(0, str.Text.Length - 1);
}
else
{
str.Text = str.Text.Substring(0, str.Text.Length - 1);
}
}
}
}
}
}