I need to sort the values according to the following problem:

For every n, determine the triples (i,j,k) that satisfies i+j+k=n, then sort the triples (for every n) with respect to the value of the formula (4*i+5*j+4*k+1) in ascending order. Here is the rough pseudocode:

for n in range(3,N+1):
   for i in range(1,n-1):
        for j in range(1,n-1):
            for k in range(1,n-1):
                    [sort triples in ascending order wrt to the value of (4*i+5*j+4*k+1)]

For now, I can only print the triples that satisfy i+j+k=n.

Is there a way to do the sorting inside the n loop? Or should I store them in an array then bubble sort later?

  • I don't think this is possible. There are infinitely many triples (i, j, k) that satisfy the condition i+j+k == n. Nov 26, 2015 at 13:39

1 Answer 1


For this precise case, (4*i+5*j+4*k+1) = 4*n+j+1. Since n is a constant you need to sort it by j. Or just use j for your outer loop (after n).

Also, you can compute k directly from i and j

for n in range(3,N+1):
   for j in range(1,n-1):
        for i in range(1,n-1):
            k = (n-i-j)
            if (1<=k && k<=n):
                 [print triplet (i,j,k)]
  • And the lesson is: beware the lateral thinking puzzle! This kind of transformation opportunity happens in real life as well, so it's a good idea to be on the look-out for it. Nov 26, 2015 at 12:22
  • This still needs to check if i+j+k=n, right? If you iterate like for(int n = N; n >= 3; n--) then for(int j = n - 2; j >= 1; j--) then for(int i = n - j - 1; i >= 1; i--) and then int k = n - j - i then you don't have to check anymore. (stackoverflow.com/questions/869885/…)
    – Hirle
    Nov 26, 2015 at 12:41
  • @hirle Yes, you can remove the range check. My point was to remove the time-consuming loop.
    – Florian F
    Nov 26, 2015 at 12:59
  • @Florian F Ah wait, when I said "still needs to check if i+j+k=n" I just wasn't paying attention... you got that taken care of. Also you sorted in the correct (ascending order), my version was backwards. So yeah, all thats left to improve is get rid of the range check... for n in range(1,N+1) then for j in range(1,n-2) then for i in range(1,n-j-1) and then k = (n-j)-i ...
    – Hirle
    Nov 26, 2015 at 14:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.