From 954b2ff314f57c9b76d07464589359ffec42f5fb Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Mon, 13 Feb 2023 11:36:49 +0100 Subject: Challenge 204 Task2 LK Perl Python --- challenge-204/lubos-kolouch/perl/ch-2.pl | 38 ++++++++++++++++++++++++++++++ challenge-204/lubos-kolouch/python/ch-2.py | 28 ++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 challenge-204/lubos-kolouch/perl/ch-2.pl create mode 100644 challenge-204/lubos-kolouch/python/ch-2.py diff --git a/challenge-204/lubos-kolouch/perl/ch-2.pl b/challenge-204/lubos-kolouch/perl/ch-2.pl new file mode 100644 index 0000000000..da5d85d681 --- /dev/null +++ b/challenge-204/lubos-kolouch/perl/ch-2.pl @@ -0,0 +1,38 @@ +use strict; +use warnings; + +sub reshape { + my ($matrix, $r, $c) = @_; + my $m = scalar @$matrix; + my $n = scalar @{$matrix->[0]}; + + if ($m * $n != $r * $c) { + return 0; + } + + my @result; + for my $i (0 .. $r-1) { + for my $j (0 .. $c-1) { + my $idx = $j + $i * $c; + my $x = int($idx / $n); + my $y = $idx % $n; + $result[$i][$j] = $matrix->[$x][$y]; + } + } + return \@result; +} + +my $matrix = [[1, 2], [3, 4]]; +my $r = 1; +my $c = 4; + +my $result = reshape($matrix, $r, $c); +if ($result) { + print "Reshaped matrix:\n"; + for my $row (@$result) { + print join(" ", @$row), "\n"; + } +} else { + print "Cannot reshape matrix\n"; +} + diff --git a/challenge-204/lubos-kolouch/python/ch-2.py b/challenge-204/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..4a49b7a544 --- /dev/null +++ b/challenge-204/lubos-kolouch/python/ch-2.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import numpy as np +from typing import List, Union + + +def reshape(matrix: List[List[int]], r: int, + c: int) -> Union[int, List[List[int]]]: + m, n = np.shape(matrix) + if m * n != r * c: + return 0 + flat_matrix = np.array(matrix).flatten() + reshaped_matrix = np.reshape(flat_matrix, (r, c)) + return reshaped_matrix.tolist() + + +matrix = [[1, 2], [3, 4]] +r = 1 +c = 4 +result = reshape(matrix, r, c) + +if result == 0: + print("Cannot reshape matrix") +else: + print("Reshaped matrix:") + for row in result: + print(row) -- cgit