Pages

Wednesday 21 October 2015

CodeEval - One zero, two zeros... - Easy

import sys

def have_zeroes(num,val):
    val_bin = bin(val)[2:]
    counter = 0
    for c in val_bin:
        if c == '0':
            counter += 1
    return counter == num

def range_vals(num,val):
    counter = 0
    for i in range(1,val+1):
        if have_zeroes(num,i):
            counter += 1
    return counter

test_cases = open(sys.argv[1], 'r')
for test in test_cases:
   arr = map(int, test.split())
   print range_vals(arr[0],arr[1])

test_cases.close()

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()

Sunday 4 October 2015

CodeEval - Matrix Rotation - Easy

import sys
import math

test_cases = open(sys.argv[1], 'r')
for test in test_cases:
    arr = test.split()
    values = []
    n = int(math.sqrt(len(arr)))
    matrix = [0]*n
    for i in range(n):
        array = [0]*n
        for j in range(n):
            array[j] = arr[i*n + j]
        matrix[i] = array
    sol = [0]*n
    for i in range(n):
        array = [0]*n
        for j in range(n):
            array[j] = matrix[n-j-1][i]
        sol[i] = array
    ans = ""
    for i in range(n):
        for j in range(n):
            if i > 0 or j > 0 :
                ans += " "
            ans += sol[i][j]
    print ans

test_cases.close()