Alex
Alex

Reputation: 55

Initializing a 2D array - cipher table

I need to create a cipher table and I'm stuck on what to do. This code:

public class Prog3Cipher {
    // INSTANCE VARIABLES
    static char [ ] keyList; // VARIABLE DESCRIPTION COMMENT
    static char [ ][ ] cipherTable; // VARIABLE DESCRIPTION COMMENT
    String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public Prog3Cipher( char code, String key ) {
        String[] keyList = new String []{"key"};
        cipherTable = new char[26][26];
        cipherTable[0][0] = 'H';
        for(int x = 0; x < cipherTable.length; x++){
            for(int y = 0; y < cipherTable.length; y++){
                cipherTable[x][y] = alpha.charAt(y);
            }
        }
        System.out.println(Arrays.deepToString(cipherTable));
    }

outputs:

[[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z], [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z], [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z],

over and over. the code and key will be given in but for now i have 'H' and 'key' as inputs. the table needs to look like this, ignoring the blue row and column:

enter image description here

The code in the pic is 'H', so the [0][0] element is 'H' and the alphabet continues in the adjacent row and column. I will use the completed table to encode and decode messages but for now I just need the table to be correct.

Upvotes: 3

Views: 235

Answers (1)

Mureinik
Mureinik

Reputation: 311978

Based on the image you shared, you could say that for each cell in the cipherTable, the character should be the character in the position of the row index + the column index + 7 (an arbitrary magic number, seemingly), modulo the size of the alphabet, of course. If we express this is Java:

int offset = 'H' - 'A';
cipherTable = new char[26][26];
for (int x = 0; x < cipherTable.length; x++) {
    for(int y = 0; y < cipherTable[0].length; y++) {
        cipherTable[x][y] = alpha.charAt((x + y + offset) % alpha.size());
    }
}

Upvotes: 5

Related Questions