2Max
June 5, 2020
One way to solve this problem is to collect input numbers with similar digit-sums in a hash table, compute the two-maximums of each hash set, and return the maximum. Instead, we solve the problem using the cluster
function of a previous exercise and a few auxiliary functions:
(define (2max xs) (if ( xs))))
(define (sum-digits n) (sum (digits n)))
(define (f x) (apply max (map sum (map 2max (cluster sum-digits <lt; xs)))))
Here are two examples:
> (f '(51 17 71 42)) 93 > (f '(1 2 3 4 5 6)) -1
The pieces are individually small and easy to understand, which makes the whole function equally easy to understand. You can run the program at https://ideone.com/KcT9Ix.
Interesting exercise. Here is my take on it using Julia 1.4: https://pastebin.com/uEPBeKBc
Have a nice weekend!
Scan the array, keeping track of the largest number seen so far for each digit sum:
Here’s a not-particularly efficient, not-particularly readable solution in Python.
Output:
Here’s a Haskell version.