use min and abs
This commit is contained in:
parent
dc76148408
commit
19804b3a8f
|
@ -18,16 +18,14 @@
|
|||
import sequtils
|
||||
import strutils
|
||||
|
||||
proc distance(a, b: uint16): int =
|
||||
result = if a < b: int(b - a) else: int(a - b)
|
||||
proc distance(a, b: int16): int =
|
||||
result = int(abs(b - a))
|
||||
|
||||
proc minimizeFuel(): int =
|
||||
let crabs = readLine(stdin).split(',').mapIt(uint16(parseUint(it)))
|
||||
let crabs = readLine(stdin).split(',').mapIt(int16(parseUint(it)))
|
||||
result = high(int)
|
||||
for pos in crabs.min() .. crabs.max():
|
||||
let sum = crabs.foldl(a + distance(b, pos), 0)
|
||||
if sum < result:
|
||||
result = sum
|
||||
result = min(result, crabs.foldl(a + distance(b, pos), 0))
|
||||
|
||||
proc main(): int =
|
||||
try:
|
||||
|
|
|
@ -18,18 +18,16 @@
|
|||
import sequtils
|
||||
import strutils
|
||||
|
||||
proc distance(a, b: uint16): int =
|
||||
let linearDistance = if a < b: int(b - a) else: int(a - b)
|
||||
proc distance(a, b: int16): int =
|
||||
let linearDistance = int(abs(b - a))
|
||||
# 1 + 2 + 3 + ... + n - 1 is the binomial coefficient (n over k) with k = 2
|
||||
result = (linearDistance + 1) * linearDistance div 2
|
||||
|
||||
proc minimizeFuel(): int =
|
||||
let crabs = readLine(stdin).split(',').mapIt(uint16(parseUint(it)))
|
||||
let crabs = readLine(stdin).split(',').mapIt(int16(parseUint(it)))
|
||||
result = high(int)
|
||||
for pos in crabs.min() .. crabs.max():
|
||||
let sum = crabs.foldl(a + distance(b, pos), 0)
|
||||
if sum < result:
|
||||
result = sum
|
||||
result = min(result, crabs.foldl(a + distance(b, pos), 0))
|
||||
|
||||
proc main(): int =
|
||||
try:
|
||||
|
|
Loading…
Reference in New Issue