From 880783e18efe158fcead283047447113f6695b09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan-Iulian=20Alecu?= <165364995+pascalecu@users.noreply.github.com> Date: Tue, 29 Jul 2025 01:18:22 +0300 Subject: [PATCH] Add Transpose Matrix in C# --- archive/c/c-sharp/TransposeMatrix.cs | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 archive/c/c-sharp/TransposeMatrix.cs diff --git a/archive/c/c-sharp/TransposeMatrix.cs b/archive/c/c-sharp/TransposeMatrix.cs new file mode 100644 index 000000000..771caa416 --- /dev/null +++ b/archive/c/c-sharp/TransposeMatrix.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public static class Program +{ + private static void ShowUsage() + { + Console.Error.WriteLine("Usage: please enter the dimension of the matrix and the serialized matrix"); + Environment.Exit(1); + } + + private static List ParseIntegerList(string input) + { + if (string.IsNullOrWhiteSpace(input)) + ShowUsage(); + + var tokens = input + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + var numbers = new List(); + foreach (var token in tokens) + { + if (!int.TryParse(token, out int value)) + ShowUsage(); + + numbers.Add(value); + } + + return numbers; + } + + static List TransposeMatrix(int cols, int rows, List input) + { + var result = new List(new int[rows * cols]); + + for (int i = 0; i < rows; ++i) + { + for (int j = 0; j < cols; ++j) + { + int index = j * rows + i; + result[index] = input[i * cols + j]; + } + } + + return result; + } + + static int Main(string[] args) + { + if (args.Length != 3) + ShowUsage(); + + if (!int.TryParse(args[0], out var cols)) + ShowUsage(); + + if (!int.TryParse(args[1], out var rows)) + ShowUsage(); + + var numbers = ParseIntegerList(args[2]); + if (numbers.Count != cols * rows) + ShowUsage(); + + var transposed = TransposeMatrix(cols, rows, numbers); + Console.WriteLine(string.Join(", ", transposed)); + return 0; + } +}