以表格格式显示二维数组



我正在学习一些图论,并转向了Powershell文本格式。我正在编写一个脚本,根据用户输入创建一个二维数组,并以表格格式显示该数组。第一部分很简单:询问用户数组的大小,然后询问用户每个元素的值。第二部分——在行和列中显示数组——很困难。

Powershell在其自己的行中显示数组的每个元素。以下脚本生成以下输出:

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

我需要像这样的输出

1 2 3
4 5 6

我可以使用脚本块来正确格式化:

"$($a[0][0])   $($a[0][1]) $($a[0][2])"
"$($a[1][0])   $($a[1][1]) $($a[1][2])"
1   2   3
4   5   6

但只有当我知道数组的大小时,这才有效。大小由用户在每次运行脚本时设置。它可能是5x5,也可能是100x100。我可以使用foreach循环调整行数:

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

但是,这不会根据列数进行调整。我不能只嵌套另一个foreach循环:

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

这只是将每个元素再次打印到自己的行上。嵌套foreach循环是我用来迭代数组中每个元素的方法,但在这种情况下,它们对我没有帮助。有什么想法吗?

目前的脚本如下:

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.

此代码生成一个邻接矩阵。然后我可以使用矩阵来学习所有关于图论算法的知识。同时,我只想让Powershell把它展示成一张整洁的小桌子。有什么想法吗?

试试这个:

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

或更好的

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

最新更新