Saturday, 14 October 2017

My CodeInGame Adventures - Horse Racing

Another CodeInGame puzzle I solved. This one wasn't too hard, only an afternoon. Don't tease me, I'm still getting back into the swing of things. What bugs me most is learning all the built-ins and special quirks.

Input
Line 1: Number N of horses

The N following lines: the strength Pi of each horse. Pi is an integer.

Output
The difference D between the two closest strengths. D is an integer greater than or equal to 0.
Constraints
1 < N < 100000
0 < Pi ≤ 10000000
Example
Input
9

Output
1
And the code I submitted:

import sys
import math

## Helper functions
def mycompare(horse_a, horse_b):
    if horse_a > horse_b:
        return horse_a - horse_b, horse_b
    elif horse_a < horse_b:
        return horse_b - horse_a, horse_a
    else:
        return 0, horse_b

## get all the data
last_horse, closest = 99999999,99999999
horse_list=[]
horses = int(input())
for horse in range(horses):
    this_horse = int(input())
    horse_list.append(this_horse)

## let's sort the strengths
temp = sorted(horse_list,reverse=True)

## test for differences in strength
for this_horse in temp:
    ## compare the differences
    this_compare, last_horse = mycompare(this_horse,last_horse)
    if this_compare < closest:
        ## put the lessor difference into our flag
        closest = this_compare

print(str(closest))


Again, if you wanna talk code, just drop a comment below.
~ Friar Greg

No comments: