Count and Say アルゴリズム解析

TypeScript版 - 視覚的解析とデモンストレーション

🔍 アルゴリズム概要

Count and Sayは、前の数列のRun-Length Encoding(RLE)を行うことで次の数列を生成する反復的なシーケンスです。

n=1
"1"
n=2
"11"
n=3
"21"
n=4
"1211"

🎯 Run-Length Encoding の詳細解析

例: "21" → "1211" の変換プロセス

2
1

ステップ1: 文字 "2" を1回カウント → "12"

ステップ2: 文字 "1" を1回カウント → "11"

結果: "12" + "11" = "1211"

より複雑な例: "1112" → "3112" の変換

1
1
1
2

ステップ1: 文字 "1" を3回カウント → "31"

ステップ2: 文字 "2" を1回カウント → "12"

結果: "31" + "12" = "3112"

💻 TypeScript実装コード

/**
 * Count and Say数列のn番目の要素を返す関数
 * @param {number} n - 取得したい数列の位置(1以上30以下)
 * @returns {string} n番目のcount-and-say数列の文字列
 */
function countAndSay(n: number): string {
    let current: string = "1";
    
    if (n === 1) return current;
    
    for (let i: number = 2; i <= n; i++) {
        current = runLengthEncode(current);
    }
    
    return current;
}

/**
 * Run-Length Encoding実装
 * @param {string} str - エンコードする文字列
 * @returns {string} エンコード後の文字列
 */
function runLengthEncode(str: string): string {
    let result: string = "";
    let count: number = 1;
    let currentChar: string = str[0];
    
    for (let i: number = 1; i < str.length; i++) {
        if (str[i] === currentChar) {
            count++;
        } else {
            result += count + currentChar;
            currentChar = str[i];
            count = 1;
        }
    }
    
    result += count + currentChar;
    return result;
}

📊 計算量解析

時間計算量: O(m × k) - m: 各ステップの文字列長, k: ステップ数
空間計算量: O(m) - 各ステップで生成される文字列の長さ
最適化ポイント: 反復的アプローチ、文字列連結の最適化

🚀 インタラクティブデモ

nの値を入力してcount-and-sayシーケンスを生成してください:

結果がここに表示されます
処理ステップがここに表示されます