Skip to content

Instantly share code, notes, and snippets.

@ConnorBaker
Created November 13, 2019 23:18
Show Gist options
  • Select an option

  • Save ConnorBaker/1f856f64036eb49f5ff2869de8701fe8 to your computer and use it in GitHub Desktop.

Select an option

Save ConnorBaker/1f856f64036eb49f5ff2869de8701fe8 to your computer and use it in GitHub Desktop.
module WeightForWeight
( main
)
where
import Data.Char
import Data.List
-- Inspired by https://raymii.org/s/blog/Weight_for_Weight_a_coding_exersize_that_kept_me_busy.html
tokenize :: Char -> String -> [String]
tokenize _ [] = []
tokenize c s = token : tokenize c rest
where
token = takeWhile (/= c) s
rest = drop (length token + 1) s
sizeThenLexiographic :: (Int, String) -> (Int, String) -> Ordering
sizeThenLexiographic (n0, s0) (n1, s1)
| n0 > n1 = GT
| n1 > n0 = LT
| s0 > s1 = GT
| s1 < s0 = LT
| otherwise = EQ
digitSum :: String -> Int
digitSum = foldr (\c n -> digitToInt c + n) 0
main :: IO ()
main = do
let input = "56 65 74 100 99 68 86 180 90"
let tokenized = tokenize ' ' input
let weighted = map (\s -> (digitSum s, s)) tokenized
let sorted = sortBy sizeThenLexiographic weighted
let result = map snd sorted
mapM_ putStrLn result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment