Task 1: Show Matrix / Matrix Transpose
Write a script to transpose a given matrix representation, so that columns become rows and rows become columns.
Example Output
Input: "[1 2 3][4 5 6]"
Output:
1 4
2 5
3 6
Logic
Parse the input string of nested arrays into a 2D array structure. Then swap the row and column coordinates, creating a transposed matrix, and print the results row by row.
Perl Solution
ch-1.pl
my $i=0;
for (split /\]/, $arr[0]) {
$_ =~ s/\[//g;
push @{$all_array[$i]}, split / /;
$arr_size = scalar @{$all_array[$i]} unless $arr_size;
die "arrays are not of the same size" unless scalar @{$all_array[$i]} == $arr_size;
$i++;
}
for my $key (0..$arr_size-1) {
for my $arr (0..scalar @all_array -1) {
print $all_array[$arr][$key]." ";
}
say '';
}
Python Solution
ch-1.py
import numpy as np
arr = np.empty(0)
arr1 = np.array(sys.argv[1].split(' ]'))
for elem in arr1[:-1]:
arr = np.append(arr, elem[2:].split(' '))
arr = np.reshape(arr, (len(arr1)-1, int(len(arr)/(len(arr1)-1))))
arr = np.rot90(arr, 3)
arr = np.flip(arr, 1)
print(arr)
Task 2: Sort Sublist
Write a script to sort a sublist of elements in an array at specified indices, leaving all other elements in their original positions.
Example Output
Input: Array: [10 4 1 8 12 3], Indices: [0 2 5]
Output: [1 4 3 8 12 10] (Sorted elements 10, 1, 3 at indices 0, 2, 5)
Logic
Extract the elements at the specified indices from the first array. Sort these extracted elements. Finally, replace the elements at the specified indices in the original array with the sorted elements in order.
Perl Solution
ch-2.pl
my @sort_array;
for (@{$all_array[1]}) {
push @sort_array, $all_array[0][$_];
}
@sort_array = sort {$a <=> $b} @sort_array;
$i=0;
for (@{$all_array[1]}) {
$all_array[0][$all_array[1][$i]] = $sort_array[$i];
$i++;
}
Python Solution
ch-2.py
arr_sort = np.empty(0, int)
for key in arr2:
arr_sort = np.append(arr_sort, int(arr1[int(key)]))
arr_sort = np.sort(arr_sort)
i = -1
for key in arr2:
i += 1
arr1[int(key)] = arr_sort[i]
print(arr1)