Bagheera
Bagheera

Reputation: 1438

Display a 2-dimensional array in tabular format

I'm learning a little about graph theory and got sidetracked into Powershell text formatting. I'm writing a script that creates a two-dimensional array based on user input and displays the array in a tabular format. The first part is easy: ask the user the size of the array, then ask the user for the values of each element. The second part--displaying the array in rows and columns--is difficult.

Powershell displays each element of an array in its own line. The following script produces the following output:

$a= ,@(1,2,3)
$a+=,@(4,5,6)
$a

1
2
3
4
5
6

I need output like:

1 2 3
4 5 6

I can use scriptblocks to format it correctly:

"$($a[0][0])   $($a[0][1]) $($a[0][2])"
"$($a[1][0])   $($a[1][1]) $($a[1][2])"

1   2   3
4   5   6

But that only works if I know the size of the array. The size is set by the user each time the script runs. It might be 5x5 or it might 100x100. I can adjust for the number of rows by using a foreach loop:

foreach ($i in $a){
     "$($i[0]) $($i[1]) $($i[2])"
     }

However that doesn't adjust for the number of columns. I can't just nest another foreach loop:

foreach ($i in $a){
     foreach($j in $i){
          $j
          }
     }

That just prints each element on its own line again. Nested foreach loops are the method I use to iterate through each element in an array, but in this case they don't help me. Any ideas?

The script as it stands is below:

clear

$nodes = read-host "Enter the number of nodes."

#Create an array with rows and columns equal to nodes
$array = ,@(0..$nodes)
for ($i = 1; $i -lt $nodes; $i++){
     $array += ,@(0..$nodes)
     }

#Ensure all elements are set to 0
for($i = 0;$i -lt $array.count;$i++){
     for($j = 0;$j -lt $($array[$i]).count;$j++){
          $array[$i][$j]=0
          }
     }

#Ask for the number of edges
$edge = read-host "Enter the number of edges"

#Ask for the vertices of each edge
for($i = 0;$i -lt $edge;$i++){
     $x = read-host "Enter the first vertex of an edge"
     $y = read-host "Enter the second vertex of an edge"
     $array[$x][$y] = 1
     $array[$y][$x] = 1
     }

#All this code works. 
#After it completes, I have a nice table in which the columns and rows 
#correspond to vertices, and there's a 1 where each pair of vertices has an edge.

This code produces an adjacency matrix. I can then use the matrix to learn all about graph theory algorithms. In the meantime, I'd just like for Powershell to display this as a neat little table. Any ideas?

Upvotes: 3

Views: 3229

Answers (1)

CB.
CB.

Reputation: 60956

Try this:

$a | % { $_ -join ' ' }

or better

$a | % { $_ -join "`t" }

Upvotes: 1

Related Questions