RosettaCodeData/Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v

36 lines
900 B
Coq
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
import rand
2026-04-30 12:34:36 -04:00
const lo_abc = 'abcdefghijklmnopqrstuvwxyz'
const up_abc = 'ABCDEFGHIJKLMNIPQRSTUVWXYZ'
2023-07-01 11:58:00 -04:00
fn main() {
2026-02-01 16:33:20 -08:00
key := rand.int_in_range(2, 25) or {13}
encrypted := caesar_encrypt('The five boxing wizards jump quickly', key)
println(encrypted)
println(caesar_decrypt(encrypted, key))
2023-07-01 11:58:00 -04:00
}
fn caesar_encrypt(str string, key int) string {
2026-02-01 16:33:20 -08:00
offset := key % 26
if offset == 0 {return str}
mut nchr := u8(0)
mut chr_arr := []u8{}
for chr in str {
if chr.ascii_str() in up_abc.split('') {
nchr = chr + u8(offset)
if nchr > u8(90) {nchr -= 26}
}
else if chr.ascii_str() in lo_abc.split('') {
nchr = chr + u8(offset)
if nchr > u8(122) {nchr -= 26}
}
else {nchr = chr}
chr_arr << nchr
}
return chr_arr.bytestr()
2023-07-01 11:58:00 -04:00
}
fn caesar_decrypt(str string, key int) string {
2026-02-01 16:33:20 -08:00
return caesar_encrypt(str, 26 - key)
2023-07-01 11:58:00 -04:00
}