use min and abs

This commit is contained in:
Christian Ulrich 2021-12-07 22:26:40 +01:00
parent dc76148408
commit 19804b3a8f
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 8 additions and 12 deletions

View File

@ -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:

View File

@ -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: