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