티스토리 뷰

Hobby/Code

[C] Caesar Cipher

생각많은 소심남 2014. 5. 25. 01:56

CS50 강의 과제중에 cipher에 대한 내용이 나온다.크게 언급되는게 Caesar cipher와 Vigenere cipher 방식인데

그중 Caesar cipher 에 대한 구현이다. 

내용도 엄청 간단하다. 그냥 k값을 입력으로 주면 그 값만큼 shift 한 결과에 대한 alphabet의 mapping value가 다시 들어가는 것이다. 즉 ASCII 코드 이상으로 넘어가는 값에 대한 처리만 해주면 되는 방식이다. Vigenere 방식은 쪼금 복잡하지만.. 아무튼 modulo 연산만 잘 쓰면 되는거 같다.

대충 짜느라 코드가 지저분하다. 


#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

#define LOWER   97
#define UPPER   65

int main(int argc, char* argv[])
{
    if(argc != 2){
        printf("you must enter single parameter to execute\n");
        return 1;
    }

    int k = atoi(argv[1]);
    
    string input = GetString();
    for ( int i = 0; i < strlen(input); i++){
        if(isalpha(input[i])){
            if(islower(input[i])) printf("%c", LOWER + (input[i] - LOWER + k) % 26);
            else printf("%c", UPPER + (input[i] - UPPER + k) % 26);
        } 
        else printf("%c", input[i]);
    }
    printf("\n"); 
    
    return 0; 

}


'Hobby > Code' 카테고리의 다른 글

[C] matrix multiplication using dynamic memory allocation  (0) 2014.05.27
[C] fifteen game  (0) 2014.05.26
[C] vigenere cipher  (1) 2014.05.25
[ruby] Rock-Paper-Scissors class  (0) 2014.05.19
[ruby] Very simple class for dessert  (0) 2014.05.19
[Ruby] Palindrome, dictionary, anagram  (0) 2014.05.18
[python] count inversion with mergesort  (0) 2014.05.18
댓글