[英]C#. How to transform 1D array to 2D array
我知道這已經被問過無數次了,但是我找不到我要尋找的東西。 我目前正在嘗試編寫c#方法,該方法在控制台上將int數組顯示為豎線。 我的想法是將1D數組轉換為2D。 如果input = {2, 1, 3}
; 輸出應如下所示:
{{0, 0, 1},
{1, 0, 1},
{1, 1, 1}}
然后,我可以用自己選擇的字符替換1和0,以在控制台上顯示圖像。 到目前為止,我的方法如下所示:
public static void DrawGraph()
{
int[] randomArray = new int[3]{ 2, 1, 3 };
int[,] graphMap = new int[3, 3];
for(int i = 0; i < graphMap.GetLength(0); i++)
{
for(int j = 0; j < graphMap.GetLength(1); j++)
{
graphMap[i, j] = randomArray[j];
Console.Write(graphMap[i, j]);
}
Console.WriteLine();
}
}
並產生輸出:
2 1 3
2 1 3
2 1 3
如果2D陣列僅作為幫助您進行打印的工具而相關,則可以完全省略它。
private static readonly char GraphBackgroundChar = '0';
private static readonly char GraphBarChar = '1';
void Main()
{
int[] input = {4, 1, 6, 2};
int graphHeight = input.Max(); // using System.Linq;
for (int currentHeight = graphHeight - 1; currentHeight >= 0; currentHeight--)
{
OutputLayer(input, currentHeight);
}
}
private static void OutputLayer(int[] input, int currentLevel)
{
foreach (int value in input)
{
// We're currently printing the vertical level `currentLevel`.
// Is this value's bar high enough to be shown on this height?
char c = currentLevel >= value
? GraphBackgroundChar
: GraphBarChar;
Console.Write(c);
}
Console.WriteLine();
}
它的基本作用是從輸入中找到“最高條”,然后從上到下遍歷每個垂直級別,並在當前高度處每次看到input
的圖形條時打印GraphBarChar
。
一些樣本:
輸入= {2,1,3};
001
101
111
輸入= {2,4,1,0,3};
01000
01001
11001
11101
如果目標平台支持終端仿真器中的框形繪圖字符,則可以將以下字符用於一些令人信服的條形圖:
private static readonly char GraphBackgroundChar = '░';
private static readonly char GraphBarChar = '█';
輸入= {2,1,3};
░░█
█░█
███
輸入= {2,4,1,0,3};
░█░░░
░█░░█
██░░█
███░█
這是比已經給出的功能更好的功能,
static void DrawGraph(int[] array)
{
int maxElementValue = 0;
foreach (int i in array)
{
if (i > maxElementValue) maxElementValue = i;
}
for (int rowIndex= 0; rowIndex < maxElementValue; ++rowIndex)
{
foreach (int i in array)
{
Console.Write((i < rowIndex - columnIndex ? 0 : 1) + " ");
}
Console.WriteLine();
}
}
它可以按需工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.