Search code examples
c#.netvigenere

Generate Vigenere Cipher Table in C#


I tried to create the Vigenere Cipher Table as shown in the link: Vigenere Table Image

Here is the code snippet I have completed so far:

using System;
using System.Linq;
class VigenereTable
{
    public static void Main(string[] args)
    {
        int k = 26;
       
            for (char i = 'A'; i <= 'Z'; i++)
            {
                Enumerable.Range(i, k).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.Write(c.A));
                Console.WriteLine();
                k--;
            }       
    }
}

Can someone explain how I can loop the alphabets as shown in image above(like if "Z" is printed and then it loops and prints again from "A")?


Solution

  • This is a modular arithmetic problem. You want to start your count at a number like 20 keep counting, until you get to 25 and then you want to loop back around.

    For example the count might go 20, 21, 22, 23, 24, 25, 0, 1, etc.

    You can get this effect by using the modulo operator.

    29 % 26 = 3.

    int alphabetSize = 26;
    
    int a = (int)'A';
    int z = (int)'Z';
    
    for (int i = 0; i < alphabetSize; i++)
    {
        var getCharacterOffset = (int start, int offset) => a + ((start + offset) % alphabetSize);
        Enumerable.Range(0, alphabetSize).Select(j => (char)getCharacterOffset(i, j)).ToList().ForEach(character => Console.Write(character));
    
        Console.WriteLine();
    }