Home > Software engineering >  How can I get the 2D array to format correctly?
How can I get the 2D array to format correctly?

Time:12-02

I'm trying to encrypt a message that has been inputted (Up to 36 characters), by writing it letter by letter into a 2D array. The letters are entered row by row but read out column by column to give a distorted version. This is what I've got so far, but it just prints out the original message and the message in the array:

char[,] encrypter = new char[6, 6];
string message;
int count = 0;

Console.Write("Enter a message to encrypt: ");
message = Console.ReadLine();

Char[] messageToEncrypt = message.ToCharArray();

for (int r = 0; r < 6; r  )
{
   for (int c = 0; c < 6; c  )
   {
       encrypter[r, c] = messageToEncrypt[count];
       count  = 1;
   }
}

Console.Write(encrypter);

CodePudding user response:

I think you are looking for Chunk.

Splits the elements of a sequence into chunks of size at most size.

Try it online!

using System;
using System.Linq;

public class Program
{
    static void Main(string[] args)
    {
        var message = "This is a test";
        var chunks = message.Chunk(6);
        var lines = chunks.Select(x => string.Concat(x));
        var output = string.Join(Environment.NewLine, lines);
        Console.WriteLine(output);
    }
}

output

This i
s a te
st

CodePudding user response:

Instead of storing element row column-wise, swap the index position of r and c

...
for (int r = 0; r < 6; r  )
{
   for (int c = 0; c < 6; c  )
   {
       //Swap the index of r and c
       encrypter[c,r] = messageToEncrypt[count];
       count  = 1;
   }
}

Try Online

CodePudding user response:

2D arrays are outputted in row-major order (rows on the same line). Since you also write to the array in the same order, it doesn't appear jumbled when you print it.

Reverse the order of your r and c loops:

for (int c = 0; c < 6; c  )
{
  for (int r = 0; r < 6; r  )
  {
      encrypter[r, c] = messageToEncrypt[count];
      count  = 1;
  }
}

Try it online

  •  Tags:  
  • c#
  • Related