From 47e253bb4ab8996daa291c3bd07dd645469746a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan-Iulian=20Alecu?= <165364995+pascalecu@users.noreply.github.com> Date: Wed, 13 May 2026 22:38:32 +0300 Subject: [PATCH] Add Transpose Matrix in Ruby --- archive/r/ruby/transpose-matrix.rb | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 archive/r/ruby/transpose-matrix.rb diff --git a/archive/r/ruby/transpose-matrix.rb b/archive/r/ruby/transpose-matrix.rb new file mode 100644 index 000000000..2c91d7e89 --- /dev/null +++ b/archive/r/ruby/transpose-matrix.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +USAGE = "Usage: please enter the dimension of the matrix and the serialized matrix" + +def usage! + warn USAGE + exit 1 +end + +def parse_int(str) + Integer(str) +rescue ArgumentError, NoMethodError + usage! +end + +def parse_list(str) + str.split(",").map { parse_int(it.strip) } +end + +cols_str, rows_str, matrix_str = ARGV + +usage! if cols_str.nil? || rows_str.nil? || matrix_str.nil? +usage! if cols_str.strip.empty? || rows_str.strip.empty? || matrix_str.strip.empty? + +cols = parse_int(cols_str) +rows = parse_int(rows_str) + +usage! if cols <= 0 || rows <= 0 + +flat = parse_list(matrix_str) +usage! if flat.length != cols * rows + +matrix = flat.each_slice(cols).to_a +transposed = matrix.transpose + +puts transposed.flatten.join(", ")