Solution based in permutation method from StackOverflow.