For a given length $n$ and a maximum positive integer value $N$, I'd like to generate a list that contains all $n$-vectors with entries between $-N$ and $N$ (of which there are $(2N+1)^n$. Further, the list should be sorted in such a way that first the element with all zeroes appears, then the elements with a single non-zero entry, then two non-zero entries, and so on. How the elements are ordered within a block with a specific amount of non-zero entries is unimportant.

  • $\begingroup$ What have you tried so far? Generally, people here appreciate if questions show a minimum level of effort on the askers part. To get you started, take a look at Range, Tuples, SortBy and Count. $\endgroup$
    – Lukas Lang
    Aug 9 at 10:08
  • $\begingroup$ You surely mean $(2N+1)^n$ not $n^{2N+1}$? $\endgroup$
    – yarchik
    Aug 9 at 10:10
  • $\begingroup$ @yarchik indeed, thanks, editied $\endgroup$
    – Latrace
    Aug 9 at 10:12
  • $\begingroup$ @LukasLang I'm stuck in the stage of confusion. I will look at the functions you mention $\endgroup$
    – Latrace
    Aug 9 at 10:14
  • $\begingroup$ Try to sort Table[IntegerDigits[i, k, n] - ConstantArray[1, n], {i, 0, k^n - 1}]. $\endgroup$
    – yarchik
    Aug 9 at 10:22

1 Answer 1


Thanks to LukasLang:

ReverseSortBy[Tuples[Range[-nmax, nmax], n], Count[#, 0] &]

does the job. Here nmax = $N$ from the question.

  • 2
    $\begingroup$ This is almost exactly what I had in mind. One minor improvement: You can write Count[0] instead of Count[#, 0]& (this is the third usage form in the documentation of Count) $\endgroup$
    – Lukas Lang
    Aug 9 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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