Reputation: 1
I'm working on a Cipher project for my computer science class, and we are supposed to put a string into a square 2D array, filling remaining spaces with asterisks, and then print out an encoded message by traversing the array diagonally.
For example, with a message "testcipher," the array would be
[t, e, s, t]
[c, i, p, h]
[e, r, *, *]
[*, *, *, *]
And the array would be processed to give "t i * * e p * * s h e * t c r *"
I could really use some help with this. Thanks in advance!
Upvotes: 0
Views: 345
Reputation: 1338
Let's take it step by step:
1) We need to find the dimension of the 2D array. Since it has to be squared we have to find the first squared number greater or equal to the length of the string.
small edit: I assume cipher is a String.
int arrayDimension = 0;
while (arrayDimension * arrayDimension < cipher.length())
{
arrayDimension++;
}
2) Now we place the cipher character by character in the array.
int currentCharacterIndex = 0;
for (int i = 0; i < arrayDimension; i++)
{
for (int j = 0; j < arrayDimension; j++)
{
if (currentCharacterIndex < cipher.length())
array[i][j] = cipher.charAt(currentCharacterIndex++);
else
array[i][j] = '*';
}
}
This could be simplified I guess, but the purpose of this bit of code is for you to understand the idea and hopefully write a better version.
3) We have our array so the easiest thing to do is SHIFT all rows (except for the first one) to the left rowIndex times.
So basically for a row of c i p h
we'll end up with i p h c
. As a result, we now have to print each column and our job here is done.
The code should look like this (it's pretty simple so I'll leave this to you):
//Shift each row
char firstColumnChar;
for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
{
//We shift rowIndex times
for (int timesToShift = rowIndex; timesToShift > 0; timesToShift--)
{
firstColumnChar = array[rowIndex][0]; //We keep the first char in some variable
//We shift all elements to the left - except for the first one
for (int i = 0; i < rowIndex - 1; i++)
array[rowIndex][i] = array[rowIndex][i+1];
//We now shift the first character to the last column
array[rowIndex][arrayDimension - 1] = firstColumnChar;
}
}
//Print columns
for (int columnIndex = 0; columnIndex < arrayDimension; columnIndex++)
{
for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
System.out.print(array[rowIndex][columnIndex] + " ");
//You can print a '\n' here if you want to
}
Upvotes: 1