Где ошибка при самостоятельном вводе массива? - C#
Формулировка задачи:
Добрый вечер. Не судите строго. Кучу раз уже пришлось переделать...Поэтому мозги кипят) Подскажите пожалуйста не могу разобраться, где допускаю ошибку при самостоятельном вводе массива?И как можно сделать работу более "красивой"?
/*
Алгоритмы работы с многомерными массивами
(матрицы, кубы и т.д., срезы многомерных массивов, сложение,
разность, умножение матриц, нахождение обратной матрицы,
определителя для матриц произвольной размерности)
*/
class Program
{
// Динамическое сложение
private static T Add<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a + b;
}
// Динамическая разность
private static T Sub<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a - b;
}
// Динамическое умножение
private static T Mult<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a * b;
}
// Динамическое деление
private static T Division<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a / b;
}
// Конвертация массива в простейший JSON
public static string ArrToBasicJSON<T>(T[] arr)
{
string str = "";
str += "[";
for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
{
if (x > 0) { str += ", "; };
str += arr[x].ToString();
}
str += "]";
return str;
}
public static string Arr2DToBasicJSON<T>(T[,] arr)
{
string str = "";
for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
{
if (x > 0) { str += ", \n"; };
str += "[";
for (int y = 0, lenY = arr.GetLength(1); y < lenY; y++)
{
if (y > 0) { str += ", "; };
str += arr[x, y].ToString();
}
str += "]";
}
return str;
}
// Срез массива
public static T[] Slice<T>(T[] source, int start, int end)
{
int count;
count = end - start;
T[] target = null;
if (count > 0)
{
target = new T[count];
for (int i = start; i < end; i++)
{
target[i - start] = source[i];
}
}
return target;
}
// Срез двумерного массива
public static T[,] Slice2D<T>(T[,] source, int startY, int endY, int startX, int endX)
{
int countX;
int countY;
countX = endX - startX;
countY = endY - startY;
T[,] target = new T[countX, countY];
for (int x = 0; x < countX; x++)
{
for (int y = 0; y < countY; y++)
{
target[x, y] = source[x + startY, y + startX];
}
}
return target;
}
// Сумма матриц
public static T[,] Add2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2, lenX_max;
int lenY_1, lenY_2, lenY_max;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
lenX_max = Math.Max(lenX_1, lenX_2);
lenY_max = Math.Max(lenY_1, lenY_2);
T[,] target = new T[lenX_max, lenY_max];
for (int x = 0; x < lenX_max; x++)
{
for (int y = 0; y < lenY_max; y++)
{
if (x < lenX_1 && y < lenY_1)
{
T item_1 = arr_1[x, y];
// Замена нулей
target[x, y] = Add<T>(target[x, y], item_1);
}
if (x < lenX_2 && y < lenY_2)
{
T item_2 = arr_2[x, y];
target[x, y] = Add<T>(target[x, y], item_2);
}
}
}
return target;
}
// Разность матриц
public static T[,] Sub2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2, lenX_max;
int lenY_1, lenY_2, lenY_max;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
lenX_max = Math.Max(lenX_1, lenX_2);
lenY_max = Math.Max(lenY_1, lenY_2);
T[,] target = new T[lenX_max, lenY_max];
for (int x = 0; x < lenX_max; x++)
{
for (int y = 0; y < lenY_max; y++)
{
if (x < lenX_1 && y < lenY_1)
{
T item_1 = arr_1[x, y];
// Замена нулей
target[x, y] = Add<T>(target[x, y], item_1);
}
if (x < lenX_2 && y < lenY_2)
{
T item_2 = arr_2[x, y];
target[x, y] = Sub<T>(target[x, y], item_2);
}
}
}
return target;
}
// Умножение матриц
public static T[,] Mult2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2;
int lenY_1, lenY_2;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
// Проверка на допустимость операции
if (lenY_1 != lenX_2)
{
throw new System.InvalidOperationException("Нельза умножать несогласованные матрицы.");
}
T[,] target = new T[lenX_1, lenY_2];
for (int k = 0; k < lenY_2; k++)
{
for (int i = 0; i < lenX_1; i++)
{
for (int j = 0; j < lenX_2; j++)
{
T item_1 = arr_1[i, j];
T item_2 = arr_2[j, k];
target[i, k] = Add<T>(target[i, k], Mult<T>(item_1, item_2));
}
}
}
return target;
}
// Транспонирование матрицы
public static T[,] Trans<T>(T[,] arr)
{
int lenX = arr.GetLength(0);
int lenY = arr.GetLength(1);
T[,] target = new T[lenY, lenX];
for (int i = 0; i < lenX; i++)
{
for (int j = 0; j < lenY; j++)
{
target[j, i] = arr[i, j];
}
}
return target;
}
// Определитель матрицы
// public static T Determinant<T>(T[,] arr){
// int N = arr.GetLength(0);
// dynamic denom = 1;
// int exchanges = 0;
//
// dynamic target = Trans<T>(arr);
//
// for (int i = 0; i < N-1; i++){
// dynamic maxN = i;
// dynamic maxValue = Math.Abs(target[i, i]);
//
// for (dynamic j = i + 1; j < N; j++){
// dynamic value = Math.Abs(target[j, i]);
//
// if (value > maxValue){
// maxN = j;
// maxValue = value;
// }
// }
//
// if (maxN > i){
// dynamic temp = target[i];
// target[i] = target[maxN];
// target[maxN] = temp;
//
// exchanges++;
// } else {
// if (maxValue == 0){
// return maxValue;
// }
// }
//
// dynamic value1 = target[i, i];
// for (int j = i + 1; j < N; j++){
// dynamic value2 = target[j, i];
// target[j, i] = 0;
//
// for (int k = i + 1; k < N; k++){
// target[j, k] = (target[j, k] * value1 - target[i, k] * value2) / denom;
// }
// }
//
// denom = value1;
// }
//
// if (exchanges % 2 == 0){
// return -target[N-1, N-1];
// } else {
// return target[N-1, N-1];
// }
// }
// Определитель матрицы 2 x 2
public static int Determinant2(int[,] x1)
{
int md2 = x1[0, 0] * x1[1, 1]
- x1[1, 0] * x1[0, 1];
return md2;
}
// Определитель матрицы 3 x 3
public static int Determinant3(int[,] x1)
{
int md3 = x1[0, 0] * x1[1, 1] * x1[2, 2]
+ x1[2, 0] * x1[0, 1] * x1[1, 2]
+ x1[1, 0] * x1[2, 1] * x1[0, 2]
- x1[2, 0] * x1[1, 1] * x1[0, 2]
- x1[0, 0] * x1[2, 1] * x1[1, 2]
- x1[1, 0] * x1[0, 1] * x1[2, 2];
return md3;
}
public static bool Str_to_bool(string str)
{
bool ans = false;
switch (str)
{
case "y":
case "Y":
case "yes":
case "Yes":
case "д":
case "Д":
case "да":
case "Да":
ans = true;
break;
default:
ans = false;
break;
}
return ans;
}
static void Main()
{
Console.WriteLine("Введите размерность массива: ");
Console.WriteLine("x: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("y: ");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("нужен ли второй массив? y/n: ");
bool has_seccond_arr = Str_to_bool(Console.ReadLine());
Console.WriteLine("желаете воодить сами (n) или ввести случайные значения (y)? y/n: ");
bool is_auto_fill = Str_to_bool(Console.ReadLine());
// 1
int[,] array2D_1 = new int[x, y];
// 2
int[,] array2D_2 = new int[x, y];
if (is_auto_fill)
{
Random random = new Random();
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < x; c_y++)
{
array2D_1[c_x, c_y] = random.Next(-42, 42);
if (has_seccond_arr)
{
array2D_2[c_x, c_y] = random.Next(-42, 42);
}
}
}
}
else
{
Console.WriteLine("Первый массив");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < x; c_y++)
{
array2D_1[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Второй массив");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < x; c_y++)
{
array2D_2[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
}
Console.WriteLine("\n\n");
Console.WriteLine("Первый массив");
Console.WriteLine(Arr2DToBasicJSON(array2D_1));
Console.WriteLine("Второй массив");
Console.WriteLine(Arr2DToBasicJSON(array2D_2));
Console.WriteLine("\n\n");
Console.WriteLine("Выбирите операцию:");
Console.WriteLine(
" 1) Срез двумерного массива \n"
+ " 2) Сложение матриц \n"
+ " 3) Разность матриц \n"
+ " 4) Умножение матриц \n"
+ " 5) Транспонирование матрицы \n"
+ " 6) Определитель матрицы 2 x 2 \n"
+ " 7) Определитель матрицы 3 x 3 \n"
);
int variant = Convert.ToInt32(Console.ReadLine());
switch (variant)
{
// Срез двумерного массива
case 1:
Console.WriteLine("Введите начала среза по Y:");
int slice_y_start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите конец среза по Y:");
int slice_y_end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите начала среза по X:");
int slice_x_start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите конец среза по X:");
int slice_x_end = Convert.ToInt32(Console.ReadLine());
array2D_1 = Slice2D(
array2D_1
, slice_y_start
, slice_y_end
, slice_x_start
, slice_x_end
);
Console.WriteLine(Arr2DToBasicJSON(array2D_1));
break;
// Сложение матриц
case 2:
Console.WriteLine(Arr2DToBasicJSON(Add2D(array2D_1, array2D_2)));
break;
// Разность матриц
case 3:
Console.WriteLine(Arr2DToBasicJSON(Sub2D(array2D_1, array2D_2)));
break;
// Умножение матриц
case 4:
Console.WriteLine(Arr2DToBasicJSON(Mult2D(array2D_1, array2D_2)));
break;
// Транспонирование матрицы
case 5:
Console.WriteLine(Arr2DToBasicJSON(Trans(array2D_1)));
break;
// Определитель матрицы 2 x 2
case 6:
Console.WriteLine(Determinant2(array2D_1));
break;
// Определитель матрицы 3 x 3
case 7:
default:
Console.WriteLine(Determinant3(array2D_1));
break;
}
Console.ReadLine();
}
}Решение задачи: «Где ошибка при самостоятельном вводе массива?»
textual
Листинг программы
else
{
Console.WriteLine(has_seccond_arr ? "Первый массив" : "Введите элементы массива");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < y; c_y++)
{
array2D_1[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
if (has_seccond_arr)
{
Console.WriteLine("Второй массив");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < y; c_y++)
{
array2D_2[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
}
}
Console.WriteLine("\n\n");
Console.WriteLine(has_seccond_arr ? "Первый массив" : "Массив");
Console.WriteLine(Arr2DToBasicJSON(array2D_1));
if (has_seccond_arr)
{
Console.WriteLine("Второй массив");
Console.WriteLine(Arr2DToBasicJSON(array2D_2));
}
Console.WriteLine("\n\n");
Console.WriteLine("Выберите операцию:");