Skip to content

Conversation

@akmhmgc
Copy link
Owner

@akmhmgc akmhmgc commented Oct 3, 2025

解いた問題

779. K-th Symbol in Grammar

使用言語

Ruby

次に解く問題

3. Longest Substring Without Repeating Characters

@akmhmgc akmhmgc added the ruby label Oct 3, 2025
else
1
end
end

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私が慣れてないからかもしれませんが、ネストされた長い if 式の値が返り値になっているのが初見では少し読みにくかったです。慣れている人は L17を見て返り値になりそうと読むので大丈夫かもしれないとも思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメントありがとうございます!

# @param {Integer} n
# @param {Integer} k
# @return {Integer}
def kth_grammar(n, k)
    return -1 if n <= 0 || k <= 0 || k > 2 ** (n - 1) # 不正な値は-1を返す
    return 0 if n == 1 && k == 1

    prev = kth_grammar(n - 1, (k + 1) / 2)
    return 1 if prev.zero? && k.even?
    return 0 if prev.zero? || k.even?
    1
end

こんな感じでネストは浅くなりますが、これはこれで対称性が少し見えづらいですが好みの問題かもしれません。

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そうですね。色々書き方があり好みの問題だと思います。
個人的には step2 で書かれているような感じが好みです。

    symbol = kth_grammar(n - 1, (k + 1) / 2)
    if k.even?
        symbol ^= 1
    end
    symbol 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants