Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active May 28, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/3ebf88205b58b31252b901888622d13d to your computer and use it in GitHub Desktop.
Save ericnormand/3ebf88205b58b31252b901888622d13d to your computer and use it in GitHub Desktop.

Largest integer from concatenation

If I have a list of integers, I can concatenate their base-10 strings to get one large integer. However, if I reorder them, then concatenate them, I could get a larger integer. The task here is to find the largest integer you can create by concatenating a given set of integers.

Here are some test cases:

(maxcat [1 2 3 4 5 6 7 8 9]) ;=> 987654321
(maxcat [12 34 56 199])      ;=> 563419912
(defn maxcat [s]
(when (seq s)
(->> (map str s)
(sort (comp - compare))
(apply str)
(java.math.BigInteger.))))
(defn maxcat [coll]
(->> coll (map str) sort reverse (apply str)))
(maxcat [1 2 3 4 5 6 7 8 9]) ;=> 987654321
(maxcat [12 34 56 199]) ;=> 563419912
(ns maxcat.core
(:require [clojure.string :as str]))
(defn maxcat [ns]
(->> ns
(map str)
(sort #(compare %2 %1))
(str/join)
(Long/parseLong)))
(ns maxcat.core-test
(:require [clojure.test :refer :all]
[maxcat.core :refer :all]))
(deftest test-maxcat
(testing "(maxcat [1 2 3 4 5 6 7 8 9]) = 987654321"
(is (= (maxcat [1 2 3 4 5 6 7 8 9]) 987654321)))
(testing "(maxcat [12 34 56 199]) = 563419912"
(is (= (maxcat [12 34 56 199]) 563419912))))
(defn maxcat [xs] (->> xs (map str) sort reverse (clojure.string/join "") (Long/valueOf)))
(defn maxcat
"Return largest integer that can be created by concatenating
a collection of integers v in any order."
[v]
(->> v
(sort
(fn [x y]
(compare
(read-string (str y x)) (read-string (str x y)))))
(apply str)
read-string))
(defn maxcat [nums]
(if (= 0 (count nums))
[]
(->> nums
(map str)
sort
reverse
(string/join "")
(Integer.))))
(defn maxcat
"find the biggest int avaliable by concatenation of the elements in coll"
[coll]
(->> coll
(map str)
sort
reverse
clojure.string/join
BigInteger.))
(defn maxcat [l] (->> l (sort-by str) reverse (clojure.string/join "") bigint))
(defn non-negative-integer?
[i]
(and
(integer? i)
(not (neg? i))))
(defn maxcat [is]
{:pre [(seqable? is)
(not (empty? is))
(every? non-negative-integer? is)]}
(->> is
(mapv #(Long/toString % 10))
(sort (fn compare-base10 [s1 s2]
(compare
(Long/parseLong (str s2 s1) 10)
(Long/parseLong (str s1 s2) 10))))
(apply str)
(read-string)))
@vvvvalvalval
Copy link

(Note: my solution isn't the only one that doesn't fail on [90 9], Mark Champine's works exactly the same way.)

@ericnormand
Copy link
Author

Thanks, Val. I was wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment