Skip to content

Instantly share code, notes, and snippets.

@nupamore
Last active October 7, 2016 00:59
Show Gist options
  • Save nupamore/f2c7c87023a2ae36c94efcf10cc4d416 to your computer and use it in GitHub Desktop.
Save nupamore/f2c7c87023a2ae36c94efcf10cc4d416 to your computer and use it in GitHub Desktop.
function show(no, str){
console.log('\n');
console.log('<'+no+'>');
console.log(str);
console.log('\n');
}
function range(length){
return [...Array(length).keys()];
}
// 알파벳 돌리기
function rot(str, num){
const u = [65,90]; // [A-Z]
const l = [97,122]; // [a-z]
return str.split('').map( _ => {
// 아스키 코드 추출
const before = _.charCodeAt();
let after = before;
// 알파벳일 경우
if( _.match(/[A-Za-z]/) ){
after = before + num;
// z를 넘었을 경우 a로 돌림
if( after>l[1] || after>u[1]&&after<l[0] ){
after -= 26;
}
}
// 아스키 코드를 문자로
return String.fromCharCode(after);
}).join('');
}
// 알파벳을 몇번 돌린 암호인지 체크
function isCaesar(cipher, keyword){
for(const i of range(26)){
const decipher = rot(cipher, i);
if( decipher.includes(keyword) ){
return i;
}
}
}
// 포함된 문자들을 반환
function matchChar(str, pattern){
let matched = '';
for(const p of pattern){
if( str.match(p) ){
matched += p;
}
}
return matched;
};
// 순서에 맞는 문자열 반환
function matchSequence(str, pattern){
const regex = pattern.split('').map( c => c + '.*' ).join('');
const matched = str.match( regex.substr(0, regex.length-2) );
if( matched ){
return matched[0];
}
else{
return '';
}
};
// 점수 평가
function getScore(char, sequence){
return (char.length * char.length) / (sequence.length - char.length);
};
// n년 뒤의 이자를 계산
function getInterest(option, rate, year){
let init = 100;
let interest = init;
for(const i of range(year)){
// 복리 단리 구분
interest += (option == 'compound') ? (interest * rate) : (init * rate);
}
return interest - 100 + '%';
}
let result;
/*
<1>
Fvb thf klshf, iba aptl dpss uva.
Lclyfaopun jvtlz av opt dov obzaslz dopsl ol dhpaz.
Aol aptl av ylwhpy aol yvvm pz dolu aol zbu pz zopupun.
Zbjjlzz pz ulcly mpuhs.
Lpnoaf wlyjlua vm zbjjlzz pz zovdpun bw.
위는 카이사르 암호로 쓰여진 격언들이다.
해독하여 시간(time)이라는 단어가 들어간 문장만을 골라 하나의 문자열로 만드시오.
*/
const ciphers =
`Fvb thf klshf, iba aptl dpss uva.
Lclyfaopun jvtlz av opt dov obzaslz dopsl ol dhpaz.
Aol aptl av ylwhpy aol yvvm pz dolu aol zbu pz zopupun.
Zbjjlzz pz ulcly mpuhs.
Lpnoaf wlyjlua vm zbjjlzz pz zovdpun bw.`;
result = ciphers.split('\n')
.filter( _ => isCaesar(_, 'time') )
.map( _ => rot( _, isCaesar(_, 'time') ) )
.reduce( (a, b) => a +' '+ b )
show(1, result);
/*
<2>
문자열 집합 A 가 있다. 여기에서 검색을 하려고한다.
검색규칙은 검색을 위한 어떤 문자열이 있을때, 이것을 구성하는 문자들이 1개이상 포함되며
만약, 여러개가 포함된다면 구성하는 문자들의 순서를 지키는 것만을 필터링한다.
(구성하는 문자들 사이사이에 다른 문자가 있어도 상관없다. 물론 공백도 문자로 취급한다.)
필터링한 결과중에서 우선순위가 높은것 2개를 출력한다. 우선순위 규칙은 다음과같다.
(매칭된문자의 수)^2 / (매칭된 첫문자부터 끝문자까지의 문자수 - 매칭된문자의 수)
(문자열중 여러개의 매칭이 생긴다면 그중 가장 우선순위가 높은것을 선택한다.)
*/
const pattern = 'rte';
const strings = `You may delay,
but time will not.
Everything comes to him
who hustles while he waits.
The time to repair the roof is
when the sun is shining.
Success is never final.
Eighty percent of success is showing up.`;
result = strings.split('\n')
.filter( _ => matchChar(_, pattern) )
.map( _ => {
const char = matchChar(_, pattern);
const sequence = matchSequence(_, pattern);
const point = getScore(char, sequence);
return { origin: _, char, sequence, point }
})
// 필터링한 결과중에서 우선순위가 높은것 2개를 출력한다.
.reduce( (list, obj) => {
if( obj.point > list[1].point ){
list[1] = obj;
}
else if( obj.point > list[2].point ){
list[2] = obj;
}
return list;
}, {
1: { point:0 }, 2: { point:0 }
})
show(2, result);
/*
<3>
다음 5가지의 금융 상품을 비교해 10년 후 가장 수익을 많이 내는 상품 하나를 알아내고자 한다
1. 1.6% 복리
2. 2.6%단리
3. 3%단리
4. 2%단리
5. 1.9%복리
*/
const financials = [
{ option: 'compound', rate: 0.016 },
{ option: 'simple', rate: 0.026 },
{ option: 'simple', rate: 0.03 },
{ option: 'simple', rate: 0.02 },
{ option: 'compound', rate: 0.019 }
];
result = financials
.map( ({option, rate}) => ({
option,
rate,
interest: getInterest(option, rate, 10)
}))
.reduce( (a, b) => a.interest > b.interest ? a : b )
show(3, result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment