Machineboy空
Excercism - Simple Cipher, 아스키 코드, 시저암호, 비젠네르 암호 본문
문제요약
주어진 key에 맞게 원본 문자열을 변형시킨 암호를 출력하라.
난이도
Medium
풀이 포인트
- random 키 생성
- 아스키 코드 활용
- 문제 이해
REVIEW
문제 이해를 한참 못했다.
Step 2 그러니까 a: 0 , d:3 의 식으로 암호에 따른 shift가 어떻게 이루어진다는 것인지 이해하는 데 오래 걸렸다.
그리고 순환되는 값에는 나머지를 잘 활용해야한다는 것! 또 명심.
뭔가 익숙해진듯, 계속 까먹는 아이디어들이 생긴다.
CODE
using System;
public class SimpleCipher
{
private string key;
// 기본 생성자 (랜덤 키 생성)
public SimpleCipher()
{
Random rand = new Random();
char[] keyChars = new char[100];
for (int i = 0; i < 100; i++)
{
keyChars[i] = (char)('a' + rand.Next(26));
}
key = new string(keyChars);
}
// 사용자 지정 키 생성자
public SimpleCipher(string key)
{
this.key = key;
}
public string Key
{
get { return key; }
}
public string Encode(string plaintext)
{
char[] encoded = new char[plaintext.Length];
for (int i = 0; i < plaintext.Length; i++)
{
char p = plaintext[i];
char k = key[i % key.Length];
encoded[i] = Shift(p, k - 'a');
}
return new string(encoded);
}
public string Decode(string ciphertext)
{
char[] decoded = new char[ciphertext.Length];
for (int i = 0; i < ciphertext.Length; i++)
{
char c = ciphertext[i];
char k = key[i % key.Length];
decoded[i] = Shift(c, -(k - 'a'));
}
return new string(decoded);
}
private char Shift(char c, int shift)
{
shift = (shift + 26) % 26; // 음수 이동 처리
return (char)('a' + (c - 'a' + shift + 26) % 26);
}
}
'Computer > Coding Test' 카테고리의 다른 글
Excercism - LargestSeriesProduct LINQ 연습 Skip Take (0) | 2025.02.27 |
---|---|
Excercism - Raindrop (0) | 2025.02.27 |
Excercism - Wordy 문자열 다루기, Split, Replace, int.tryParse (0) | 2025.02.20 |
Excercism - Matching Brackets 괄호닫기 (0) | 2025.02.19 |
Excercism - State of Tic-Tac-Toe (0) | 2025.02.17 |