콘웨이시퀀스 코딩테스트

by skwjdgn

HTML

<script src="//rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

JavaScript

/* 첫 숫자가 R일때, L번째 라인의 숫자를 출력하는 프로그램을 작성하세요
입력 :
Line 1 - 콘웨이 시퀀스의 첫 번째 숫자입니다. 위 예제에서는 1이 되겠네요.
Line 2 - 출력할 L번째 라인입니다. (인덱스는 1부터 시작합니다)
제약 :
0 < R < 100
0 < L ≤ 25
예제 :
Input
1
6
Output
3 1 2 2 1 1 */

const conwaySeq = (startValue, line) => {
	//console.log(`${startValue}의 ${line} 번째 라인은`);
	if(line === 1){
  	return startValue;
  }
  //첫 번째 숫자가 10 이상일 경우 자릿수를 따로 보는 경우
	//let seqArr = startValue.toString().split('');
  
  //첫 번째 숫자가 10 이상일 경우 하나의 숫자로 보는 경우
  let seq = [startValue];
  
   for (let i = 1; i < line; i++) {
      let tempSeq = []; 
      let seqCnt = 1;
      let seqIdx = 1;
      
      while(seqIdx < seq.length) {
          if(seq[seqIdx] != seq[seqIdx-1]) {
              tempSeq.push(seqCnt);
              tempSeq.push(seq[seqIdx-1]);
              seqCnt = 1;
          }else{
              seqCnt++;
          }
          seqIdx++;
      }
      
      tempSeq.push(seqCnt);
      tempSeq.push(seq[seqIdx-1]);
   
      seq = tempSeq;
       
  }
  
  return seq.join(' ');
    
  }

const R = Math.floor(Math.random() * 99) + 1;
const L = Math.floor(Math.random() * 10) + 1;

console.log(conwaySeq(R, L));