Sha256: c1f477a7788154b5f95c69dc25953ffdb5c8a78f76bd6f24fde7df6735b23151

Contents?: true

Size: 1022 Bytes

Versions: 383

Compression:

Stored size: 1022 Bytes

Contents

module SimpleCipher

open System

let letters = ['a'..'z']
let keyLength = 100

let random = System.Random()

let isInvalidKey key = Seq.length key = 0 || not (Seq.forall (fun c -> List.contains c letters) key)

let generateKey() = 
    let numberOfLetters = letters |> List.length
    let randomLetters = Array.init keyLength (fun _ -> List.item (random.Next(numberOfLetters)) letters)

    new String(randomLetters)

let modulo x y = ((x % y) + y) % y

let charToInt (c:char) = (int c) - (int 'a')
let intToChar (i:int) = (char)((int 'a') + (modulo i 26))

let shiftChar operation key char = operation (charToInt char) (charToInt key) |> intToChar

let shift operation (key:string) (input:string) =     
    if isInvalidKey key then failwith "Invalid key"
    else new String(Seq.map2 (shiftChar operation) key input |> Seq.toArray)
        
let encode key input = shift (+) key input   
let decode key input = shift (-) key input
    
let encodeRandom input = 
    let key = generateKey()
    (key, encode key input)

Version data entries

383 entries across 383 versions & 1 rubygems

Version Path
trackler-2.2.1.166 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.165 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.164 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.163 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.162 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.161 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.160 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.159 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.158 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.157 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.156 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.155 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.154 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.153 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.152 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.151 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.150 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.149 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.148 tracks/fsharp/exercises/simple-cipher/Example.fs
trackler-2.2.1.147 tracks/fsharp/exercises/simple-cipher/Example.fs