Created
May 9, 2014 21:52
-
-
Save wookimiii/c28efae8014f32d98655 to your computer and use it in GitHub Desktop.
Erlang solution to the cube permutation problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% permcubes.erl | |
% | |
% Problem statement: | |
% The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). | |
% 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. | |
% | |
% Usage: permcubes:find(N) where N is the number of permutations | |
% permcubes:find(N). => [127035954683,352045367981,373559126408,569310543872, 589323567104] | |
-module(permcubes). | |
-export([find/1]). | |
-export([is_permutation/2]). | |
-export([get_permutations/2]). | |
% returns the list of N cubed numbers that are permutations | |
find(N) -> find(1, N, []). | |
find(X, N, L) -> | |
Cube = trunc(math:pow(X, 3)), | |
Permutations = get_permutations(L, Cube), | |
Count = length(Permutations), | |
if (Count < N-1) -> | |
find(X+1, N, L ++ [Cube]); | |
true -> | |
Permutations ++ [Cube] | |
end. | |
% true is N and M are string permutations of each other | |
is_permutation(N, M) -> | |
ListN = integer_to_list(N), | |
ListM = integer_to_list(M), | |
lists:sort(ListN) == lists:sort(ListM). | |
% returns a list of permutations of N from L | |
get_permutations(L, N) -> get_permutations(L, [], N). | |
get_permutations([], R, N) -> R; | |
get_permutations(L, R, N) -> | |
[M|L2] = L, | |
Isperm = is_permutation(M, N), | |
if (Isperm) -> | |
get_permutations(L2, R ++ [M], N); | |
true -> | |
get_permutations(L2, R, N) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment