summaryrefslogtreecommitdiff
path: root/columnar.py
blob: 4b23255880f359d8086b0c02567dd372cef3c366 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import numpy as np
message = input("Enter a message: ")
key = input("Key: ")
counter = 0
length = len(message)//len(key)
width = len(key)
cipher = np.empty([length, width])

for i in range(length):
    for j in range(width):
        cipher[i][j] = ord(message[counter])
        counter+=1

for i in range(length):
    for j in range(width):
        print(chr(round(cipher[i][j])), end="\t")
    print()

def column_order(key):
    sorted_key = sorted(enumerate(key), key=lambda x: x[1])  # Sort by letter
    order = {index: rank + 1 for rank, (index, _) in enumerate(sorted_key)}
    return [order[i] for i in range(len(key))]

position  = column_order(key)
print(position)

def minimum(arr):
    min = arr[0]
    for i in range(len(arr)):
        if(arr[i]<min):
            min=arr[i]
    return min
ciphertext = ""
while position:
    mini = minimum(position)
    output = mini
    for i in range(len(position)):
        if position[i] == mini:
            output=i
            break
    for i in range(length):
        ciphertext += chr(round(cipher[i][output]))
    position.pop(output)

print(ciphertext)