iThinks

Google Code Jam 2014 Qualifiers

Google Code Jam has always been a competition I have cherished, simply because the problems they post are brilliant and the closest to reality as compared to problems of other competitions. They’re always fun to read, disect & solve, more often than not, the solutions are reasonably trivial (especially for the qualifiers) yet extremely subtle & deceptive.

Today I want to share the solutions of 3 problems I was able to solve, the code should pretty much speak for itself because none of it is very complex.

Magic Trick

This one was the easiest of all, more of a warmup I suppose. Here’s the solution :

Ruby

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

defget_ans

gets.to_i

end

defget_arr

arr=[]

4.timesdo

arr<<gets.split.map(&:to_i)

end

arr

end

defget_ans_arr

[get_ans,get_arr]

end

defpout(x,y)

puts"Case ##{x}: #{y}"

end

defsolve(a1,arr1,a2,arr2)

int=arr1[a1-1]&arr2[a2-1]

caseint.size

when0

'Volunteer cheated!'

when1

int[0]

when2..4

'Bad magician!'

end

end

gets.to_i.timesdo|i|

a1,arr1=get_ans_arr

a2,arr2=get_ans_arr

pout(i+1,solve(a1,arr1,a2,arr2))

end

Cookie Clicker Alpha

Based on Cookie Clicker game developed by Orteil, this one was slightly trickier, and required a little bit of math. I solved it with a recursive algorithm first, then optimized it into an iterative one to pass for the large input. Here’s my solution with both recursive and iterative parts :

Ruby

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

RATE=2.0

deftrunc(y)

returny.round(7)

end

defpout(x,y)

puts"Case ##{x}: #{trunc(y)}"

end

defsolve_rec(c,f,x,r,t)

returnt+(x/r)ifx<=c||(t+c/r+x/(r+f))>=(t+x/r)

t+=c/r

r+=f

solve_rec(c,f,x,r,t)

end

defsolve_itr(c,f,x)

t,r=0.0,RATE

returnx/rifx<=c

while(t+c/r+x/(r+f))<(t+x/r)

t+=c/r

r+=f

end

t+x/r

end

gets.to_i.timesdo|i|

c,f,x=gets.split.map(&:to_f)

# pout(i+1, solve_rec(c, f, x, RATE, 0.0))

pout(i+1,solve_itr(c,f,x))

end

Deceitful War

This one was really subtle, easy enough to understand but hard to implement. It took me a while to put my understanding of how much being deceitful at the game called War translated to my points. Here too I solved both the normal game War and Deceitful War recursively first (it’s just easier to think recursively thanks to Lisp), then translated those to their iterative counterparts. Here is my solution with both recursive & iterative parts :