06 martie 2017

Code jam, for women (solutiile mele, #2)

Which two dancers will be next to dancer number K when the dance is over?

# init
T = 0
i = 1

def solve(caseId, D, K, N):
pos = [0 for i in range(D)]
i = 1
while i<= D:
    # even -> ccw
if i % 2 == 0:
pos[(i - N) % D] = i
# odd -> cw
else:
pos[(i + N) % D] = i

    i += 1
  posK = pos.index(K)
msg = "Case #"+ str(caseId) + ": " + str(pos[(posK+1)%D]) + " " + str(pos[(posK-1)%D])
print msg


with open("B-large-practice.in", "r") as myFile:
        T = eval(myFile.readline())
        for line in myFile:
                D, K, N = line.split(' ')
                solve (i, eval(D), eval(K), eval(N))
                i = i + 1

myFile.close()

# This solution does not scale !!!
# if D is very large, we can't afford to use an array that large!
# hence got this math solution below:

case = 1

def fix(number, D):
  while number <= 0:
    number += D
  while number > D:
    number -= D
  return number

def getLeft(index_K, D, N):
  if index_K == D-1:
    index_left = 0
  else:
    index_left = index_K + 1

  j = 0 # does not matter as we add/subtract as we want
  left = D*j + index_left + N
  if left % 2 == 0:
    return fix(left,D)
    
  left = D*j + index_left - N
  if left % 2 == 1:
    return fix(left,D)
  return -1  


def getRight(index_K, D, N):
  if index_K == 0:
    index_right = D-1
  else:
    index_right = index_K - 1
  
  j = 0
  right = D*j + index_right + N
  if right % 2 == 0:
    return fix(right,D)
    
  right = D*j + index_right - N
  if right % 2 == 1:
    return fix(right,D)
  return -1


def solve(caseId, D, K, N):
  if K % 2 == 0:
    index_K = (K - N) % D # K is at position (K-N)%D
    left = getLeft (index_K, D, N)
    right = getRight (index_K, D, N)
  else:
    index_K = (K + N) % D
    left = getLeft (index_K, D, N)
    right = getRight (index_K, D, N)
  
  msg = "Case #"+ str(caseId) + ": " + str(left) + " " + str(right)
  print msg


with open("B-large-practice.in", "r") as myFile:
        T = eval(myFile.readline())
        for line in myFile:
                D, K, N = line.split(' ')
                solve (case, eval(D), eval(K), eval(N))
                case = case + 1


myFile.close()

Niciun comentariu: