You are not logged in.
Pages: 1
How to write script which output will be a matrix like mentioned below?
This is an example for argument = 5, where argument means number of columns and rows. Numbers range could be from 1 - 9.
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7
Thx in advance!
Offline
What have you tried?
Offline
So far I managed to display this:
1 2 3 4 5
6 7 8 9
#!/bin/bash
# Defining matrix parameters
# array a = ( 1 2 3 4 ... 9 )
a=({1..9})
cols=$1
rows=$1
# Dispalying matrix
for ((row=1; row<=rows; row++)); do
for ((col=1; col<=cols; col++)); do
echo -n ${a[((cols*((row-1))+col-1))]}$'\t'
done
echo
done
Offline
1. Does it have to be just bash or can you use some coreutils?
2. Random numbers between 1 and 9 or just like you showed in your first post: all numbers from 1 to 9 and from 1 again?
Offline
Try the following:
for ((i=0;i<rows;i++)); do
for((j=0;j<cols;j++)); do
printf "%d\t" ${a[$(((j+rows*i)%${#a[@]}))]};
done;
printf "\n";
done
Offline
Just bash unfortunately...and it has to be just like I showed. So after 9 should me again 1 and in the next line 2 3 4 5 6, etc. It was example for argument = 5, but it has to work for every number in input.
Offline
Is this homework?
It can be done in four clean lines. with only one variable needed. (Or on one line that would fit on an 80-column terminal).
Last edited by Trilby (2013-05-28 11:52:21)
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
yes, but I am learning by myself. I found this exercise on some webpage. If you see different solution I am open to see that.
Offline
for i in $(seq $(($1*$1))); do
printf "%d\t" $((($i-1)%9+1))
[[ $(($i%$1)) -eq 0 ]] && echo
done
EDIT: oops, not quite right, standby. fixed.
Last edited by Trilby (2013-05-28 12:04:01)
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
Thank you for your help. This is what I was looking for:
printf "%d\t" ${a[$(((j+rows*i)%${#a[@]}))]};
Offline
Please mark your thread as [Solved] by editing your first post and prepending it to the title.
Also, please use code tags when pasting to the boards: https://wiki.archlinux.org/index.php/Fo … s_and_Code
Offline
for i in {1..25};do echo $(($RANDOM%9+1)); done|xargs -n 5
how about this?
Apple hater. Panda lover.
Offline
for i in {1..25};do echo $(($RANDOM%9+1)); done|xargs -n 5
how about this?
I asked about this: https://bbs.archlinux.org/viewtopic.php … 9#p1279109
The answer https://bbs.archlinux.org/viewtopic.php … 2#p1279112
Edit: Your code would have to work for any number, not just 5.
Last edited by karol (2013-05-29 08:39:41)
Offline
yes "$(seq 9)" | head -n $((5 * 5)) | pr -aT -5
Offline
Pages: 1