import std/[sequtils, strutils, tables] # Description of a Bifid cipher. type Bifid[N: static Positive] = object grid: array[1..N, array[1..N, char]] coords: Table[char, (int, int)] proc initBifid(N: static Positive; text: string): Bifid[N] = # Initialize a Bifid cipher. assert text.len == N * N var row, col = 1 for c in text: result.grid[row][col] = c result.coords[c] = (row, col) inc col if col > N: col = 1 inc row if N == 5: result.coords['J'] = result.coords['I'] func encrypt(bifid: Bifid; text: string): string = ## Encrypt "text" using the given cipher. var row1, row2: seq[int] for ch in text: let coords = bifid.coords[ch] row1.add coords[0] row2.add coords[1] let row = row1 & row2 for i in countup(0, row.high, 2): result.add bifid.grid[row[i]][row[i+1]] func decrypt(bifid: Bifid; text: string): string = ## Decrypt "text" using the given cipher. var row: seq[int] for ch in text: let coords = bifid.coords[ch] row.add [coords[0], coords[1]] let m = row.len shr 1 let row1 = row[0..