Created
February 6, 2022 13:24
-
-
Save elderica/78f1bc506514bd2cdeea83ce8c67827d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket/base | |
(module+ test (require rackunit)) | |
(require (only-in srfi/13 | |
string-index)) | |
(define *symbols-downcase* | |
"abcdefghijklmnopqrstuvwxyz") | |
(define *symbols-upcase* | |
(string-upcase *symbols-downcase*)) | |
(define *symbols-digit* | |
"0123456789") | |
;; Character Integer -> Character | |
;; ch を key だけ辞書caesar順にずらす | |
(define (char-shift ch key) | |
(let* ([symbols (cond [(char-lower-case? ch) *symbols-downcase*] | |
[(char-upper-case? ch) *symbols-upcase*] | |
[(char-numeric? ch) *symbols-digit*] | |
[else ""])] | |
[symbol-index (string-index symbols ch)]) | |
(if (not symbol-index) | |
ch | |
(let ([translated-index | |
(let ([i (+ symbol-index key)] | |
[symbols-length (string-length symbols)]) | |
(if (< i 0) | |
(+ i symbols-length) | |
(if (<= symbols-length i) | |
(- i symbols-length) | |
i)))]) | |
(string-ref symbols translated-index))))) | |
(module+ test | |
(check-eqv? (char-shift #\a 0) #\a) | |
(check-eqv? (char-shift #\c 2) #\e) | |
(check-eqv? (char-shift #\z 3) #\c) | |
(check-eqv? (char-shift #\c -3) #\z) | |
(check-eqv? (char-shift #\e 3) #\h)) | |
;; String Key -> String | |
;; key を鍵とするシーザー暗号処理を行う | |
(define (caesar code key) | |
(for/fold ([translated ""]) | |
([ch (in-string code)]) | |
(string-append translated | |
(string (char-shift ch key))))) | |
(module+ test | |
(check-equal? (caesar "hello" -3) "ebiil") | |
(check-equal? (caesar "HELLO" -3) "EBIIL") | |
(check-equal? (caesar "abcdefg" -3) "xyzabcd") | |
(check-equal? (caesar "ABCDEFG" -3) "XYZABCD")) | |
(module+ main | |
(define *message* "cvpbPGS{laxbbrwpcqnadkrlxweoqbstxd}") | |
(for ([key (in-range 26)]) | |
(displayln | |
(cons key (caesar *message* (- 0 key)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment