English: 5D virtual 3^5 sequential move puzzle...

Image via Wikipedia

The problem I’m trying to solve is the simple but lovely euler 62.

The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

A bit of fun coding after a statistics midterm last night and the solution should be in the bag. Except it isn’t, I am doing something wrong somehow and I can’t figure out what! Hopefully someone a bit better than me can shed some light whether my proposed solution is wrong or I just suck at Haskell.

Algorithm

  1. Generate cubes up to 10,000
  2. Every cube is a pair of a digit-ordered string n^3 and n, for instance (“279″,9)
  3. Order cubes by the string number presentation
  4. Group together all cubes with the same n^3
  5. Pick out groups with the size of 5
  6. Sort by n
  7. Pick the smallest number

Should work in principle right? So why doesn’t the website accept my answer (5027)? My guess is I’m doing something wrong in the sorting and grouping department and I was hoping someone with a bit more knowledge of Haskell could point out where I’m being stupid.

Code

import Data.List
 
cubes::(Num a) => a -> [(String, a)]
cubes 1 = [(show 1, 1)]
cubes n = (sort$show(n^3), n):(cubes $ n-1)
 
sortStrNum (s1, n1) (s2, n2)
  | length s1 == length s2 = compare s1 s2
  | otherwise = compare (length s1) (length s2)
 
permuted_cubes n =
  groupBy (\a b -> fst a == fst b) $ sortBy sortStrNum $ cubes n
 
fives n =
  filter (\xs -> length xs == 5) $ permuted_cubes n
 
comparing p x y = compare (p x) (p y)
 
smallest =
  head $ sortBy (comparing snd) $ head $ fives 100000

The whole thing looks kind of alright to me, no matter how much I poke around it doesn’t seem like something is misbehaving … but it still is.

Ideas?

Enhanced by Zemanta
  • http://twitter.com/zidarsk8 Miha Zidar

    Your programming skills are quite good, your reading on the other hand, could use some work.

    Maybe you should check what the problems is asking for

    Hint: Which of these (234^3 =12812904) numbers is considered a cube?
    3 or 234 or 12812904

  • Lol

    Did it ask for 5 of the same cubes? Only way you’re gonna get 5 times same n^3 is if you have 5 times same n.

  • http://swizec.com Swizec

    Yeah I was just being an idiot. The answer isn’t 5027, but 5027^3. Reading the forum at project-euler for this problem … apparently people have this problem a lot :)

  • Guest

     The solution to this problem is very easy. What is an anagram, how do you check for them (one line in java).