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.
1 Answer
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 ofCount[#, 0]&
(this is the third usage form in the documentation ofCount
) $\endgroup$ Aug 9, 2022 at 10:25
Range
,Tuples
,SortBy
andCount
. $\endgroup$Table[IntegerDigits[i, k, n] - ConstantArray[1, n], {i, 0, k^n - 1}]
. $\endgroup$