Maciek Gorywoda
1 min readDec 21, 2016

--

One more solution in Scala, this time focused on isolating parts of functionality which do not have to belong to the same method.

def cubesMap(n: Int) = (1 to n).map(x => x*x*x -> x).toMapdef sumPairsMap(map: Map[Int, Int]) = {
val triples = map.keys.toList.sorted
triples.flatMap( x =>
triples.dropWhile(_ <= x)
.map( y => ( (x + y), (map(x), map(y)) ) )
)
}
def findNonUnique(lst: List[(Int, (Int, Int))]) =
lst.groupBy(_._1).collect{
case (x, ys) if ys.lengthCompare(1) > 0 => x -> ys.map(_._2)
}
def ramtaxi(n: Int) = {
val result = findNonUnique(sumPairsMap(cubesMap(n)))
if(result.nonEmpty) result(result.keys.min)
else Nil
}
  • cubesMap creates a map of cubed integers to their cube roots. We could replace it with a simple list of cubed integers (it would simplify the code a bit), but then we would have to calculate the cube roots at the end. So let’s stick to this version.
  • sumPairsMap runs through the map of cubes, calculating the sum of each unique pair (so O(n²)) and returning a map of these sums to a pair of the original cube roots, which created the sum.
  • findNonUnique runs through the map of sums looking for entries with the same values and returning a list of such sums and their pairs of the original cube roots.
  • ramtaxi , finally, puts them all together and seeks the minimum of these sums.

For ramtaxi(12) the result is List((1,12), (9,10)).

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Maciek Gorywoda
Maciek Gorywoda

Written by Maciek Gorywoda

Scala. Rust. Bicycles. Trying to mix kickboxing with aikido. Trying to be a better person too. Similar results in both cases. 🇪🇺 🇵🇱

No responses yet

Write a response