Message Boards Message Boards

0
|
4027 Views
|
1 Reply
|
1 Total Likes
View groups...
Share
Share this post:

Find the mistake in my code and speeding up calculations

Posted 4 years ago

Well, I have the following code:

Needs["Combinatorica`"];
x = 3051;
threetriples = 
  KSubsets[If[
    Length[Select[
       Select[PowersRepresentations[x, 3, 2], Times @@ # != 0 &], 
       Length[#] == Length[Union[#]] &]] >= 7, 
    Select[Select[PowersRepresentations[x, 3, 2], Times @@ # != 0 &], 
     Length[#] == Length[Union[#]] &], Nothing], 3];
testallperms[
   three_] := ({n1, n2, n3, n4, n5, n6, n7, n8, n9} = Flatten[three];
   Do[{n1, n2, n3, n4, n5, n6, n7, n8, n9} = 
     NextPermutation[{n1, n2, n3, n4, n5, n6, n7, n8, n9}];
    If[x == n1^2 + n2^2 + n3^2 == n4^2 + n5^2 + n6^2 == 
      n7^2 + n8^2 + n9^2 == n1^2 + n4^2 + n7^2 == 
      n2^2 + n5^2 + n8^2 == n3^2 + n6^2 + n9^2 == 
      n1^2 + n5^2 + n9^2, {n1, n2, n3, n4, n5, n6, n7, n8, n9}, 
     Nothing], {9!}]);
DeleteCases[Map[testallperms[#] &, threetriples], Null]

This came from a question I had yesterday.

Now, I have two questions about this:

  1. The code takes round about 30 minutes to run, is there a way to speed up the calculation?
  2. The code gave no solution which is not right, because when:

$$n_1=29,n_2=41,n_3=23,n_4=1,n_5=37,n_6=41,n_7=47,n_8=1,n_9=29$$

this must gave a solution to the code. So where is the mistake?

POSTED BY: Jan Eerland
Posted 4 years ago

I can't address speeding it up.

You have found another mistake I've made. Thank you

To make this test go faster I will only check the 9 tuple that should pass.

testallperms[three_]:=({n1,n2,n3,n4,n5,n6,n7,n8,n9}=Flatten[three];
  Union[Table[{n1,n2,n3,n4,n5,n6,n7,n8,n9}=NextPermutation[{n1,n2,n3,n4,n5,n6,n7,n8,n9}];
    If[x==n1^2+n2^2+n3^2==n4^2+n5^2+n6^2==n7^2+n8^2+n9^2==n1^2+n4^2+n7^2==
      n2^2+n5^2+n8^2==n3^2+n6^2+n9^2==n1^2+n5^2+n9^2,
      {n1,n2,n3,n4,n5,n6,n7,n8,n9},Nothing],{9!}]]);
testallperms[{29,41,23,1,37,41,47,1,29}]

and that does, hopefully correctly this time, return

{{29,41,23,1,37,41,47,1,29}}

I apologize for my mistakes.

I am a little concerned about the use of three Select functions in the code, where one of those seems to be looking for lists of length greater than or equal to seven, when Length[Union[{29,41,23,1,37,41,47,1,29}]] returns 6. But the code seems to be accepting your list and I don't believe I wrote those Select functions that way.

POSTED BY: Bill Nelson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract