La foret rouge
Published on

[PS] n-th system game

Authors
  • avatar
    Name
    신주용

Programmers: n-th system game

Conditions

  • The base n, the numbers to be obtained in advance t, the number of participants in the game m, and the sequence p are given.
  • The number t that must be spoken is displayed in sequence without spaces.
  • 10~15 are printed as capital letters A~F respectively.
  • Changes from 0 to n base and creates a string that continues with the value.
  • Since t is required, if the length of the game string is longer that t×m+pt \times m + p, the process of converting to n base stops.
  • The i×m+pi \times m + p -th character is concatenated until the length of answer becomes t.

Brute force

def solution(n, t, m, p):
    answer = ''
    num = 0
    game = ""

    while True:
        numToN = convertN(num, n)
        game += numToN

        if len(game) > (t * m + p):
            break

        num += 1

    for i in range(len(game)):
        if i % m == p - 1:
            answer += game[i]

        if len(answer) == t:
            break

    return answer

def convertN(num, n):
    if num == 0:
        return '0'

    digit = "0123456789ABCDEF"
    temp = ""

    while num:
        q, r = divmod(num, n)
        temp = digit[r] + temp
        num = q

    return temp
  • Max: Test 16 〉 Pass (37.41ms, 10.7MB)

Big-O notation

  • In convertN(), the while statement is repeated logn numlog_n\ num times. Expanding this, convertN() is O(log num)O(log\ num).
  • However, the actual time required for convertN() is 1 when num is 0, 1 when 1, 1 when 2, 2 when 3, 2 when 4 ... increases in logscale in this way. Therefore, the time taken for the while statement is the sum of these values. It will be less than 1+2+3+4+...+n=n(n+1)21+2+3+4+...+n = \frac{n(n+1)}{2}, so it will be roughly close to O(NlogN)O(NlogN).
  • The for statement that makes answer works as much as O(t)O(t).
  • As a result, it operates at O(NlogN)O(NlogN) time.

Optimization

def convertN(num, n):
    if num == 0:
        return '0'

    digit = "0123456789ABCDEF"
    temp = ""

    while num:
        num, r = divmod(num, n)
        temp = digit[r] + temp

    return temp
  • It's a small difference, but don't have to use q.
def solution(n, t, m, p):
    answer = ''
    num = 0
    game = ""
    targetLen = t * m + p

    while len(game) < targetLen:
        game += convertN(num, n)
        num += 1

    for i in range(len(game)):
        if i % m == p - 1:
            answer += game[i]

        if len(answer) == t:
            break

    return answer
  • Removed numToN because it is not necessary to use it.
  • Even t×m+pt \times m + p does not need to be calculated every time.
  • If you change the condition of the while statement, you can also remove the if statement.
  • Max: Test 15 〉 Pass (36.15ms, 10.9MB)

Remember

  • It would be good to remember how to convert the base system.
  • In divmod(a, b), when a is 0, q was not returned. Caution.