3
我在學習一些關於圖論的知識,並且被誤解爲Powershell文本格式。我正在編寫一個腳本,它根據用戶輸入創建一個二維數組,並以表格格式顯示數組。第一部分很簡單:向用戶詢問數組的大小,然後詢問用戶每個元素的值。第二部分 - 以行和列顯示數組 - 很困難。以表格格式顯示二維數組
Powershell以自己的行顯示數組的每個元素。下面的腳本輸出如下:
$a= ,@(1,2,3)
$a+=,@(4,5,6)
$a
1
2
3
4
5
6
我需要的輸出,如:
1 2 3
4 5 6
我可以用scriptblocks正確格式化:
"$($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將其顯示爲一個整潔的小桌子。有任何想法嗎?
這做到了。非常感謝你。 – Bagheera
很高興幫助! –