Pages

Monday 5 October 2015

CodeEval - Magic Numbers - Moderate

import sys

def is_magic(x):
    arr_char = list(str(x))
    arr_sorted = ''.join(sorted(arr_char))
    n = len (arr_char)
    for i in range(n-1):
        if arr_sorted[i] == arr_sorted[i+1]:
            return False
    arr_checked = [False]*n
    pos = 0
    while True:
        if  arr_checked[pos]:
            break
        arr_checked[pos] = True
        index = int(arr_char[pos])
        pos = (pos + index) % n
    if not pos == 0:
        return False
    for checked in arr_checked:
        if not checked:
            return False
    return True

test_cases = open(sys.argv[1], 'r')
arr = []
for i in range(1,10001):
    if is_magic(i):
        arr.append(i)
for test in test_cases:
    bound = test.split()
    a = int (bound[0])
    b = int (bound[1])
    sol = ""
    for x in arr:
        if a > x :
            continue
        if b < x :
            break
        if not sol == "" :
            sol += " "
        sol += str(x)
    if sol ==  "":
        print -1
    else :
        print sol
test_cases.close()

No comments:

Post a Comment