개미수열이란, 읽고 말하기 수열 <-> 개미수열
우리나라에서는 소설 '개미'에서 소개되면서 유명해졌기 때문에 "개미 수열" 이란 이름으로 알려져 있다.
1, 11, 12, 1121, 122111, 112213, ....
이 수열은 앞의 수를 연속된 같은 수의 개수로 묶어서 읽는 방식이다.
예를 들면,
개미수열과 비슷한 원리를 가진 알고리즘으로는 반복 길이 부호화(Run-length encoding)가 있다. 반복 길이 부호화는 매우 간단한 '비손실 압축 방법'으로 데이터에서 같은 값이 연속해서 나타나는 것을 그 개수와 반복되는 값만으로 표현하는 방법이다. 이 방법은 아이콘, 간단한 이미지와 같이 연속된 값이 많이 있는 데이터에 효과적이다.
using System;
using System.Linq;
using System.Collections.Generic;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
// 개미수열
Console.Write("수 입력 : ");
int len = int.Parse(Console.ReadLine());
List<int> list = new List<int>();
int num = 1;
int count = 0;
list.Add(1);
for (int i = 0; i < len - 1; i++)
{
// 초기화
List<int> tempList = new List<int>();
count = 0;
num = list[0];
for (int j = 0; j < list.Count; j++)
{
if(count == 0)
{
//전에 있던 숫자와 다르면 num에 값 입력
num = list[j];
}
if (list[j] == num)
{
// 같은 숫자가 나오면 count 증가
count++;
}
else
{
// 같은 숫자가 아니라면 리스트에 전에 숫자와 count 입력
tempList.Add(num);
tempList.Add(count);
// count 초기화후 num에 값 입력
count = 1;
num = list[j];
}
}
tempList.Add(num);
tempList.Add(count);
list = tempList.ToList();
}
for(int i = 0; i < list.Count; i++)
{
Console.Write(list[i] + " ");
}
}
}
}