Re: rules on vector sequence
- To: mathgroup at smc.vnet.net
- Subject: [mg98070] Re: rules on vector sequence
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sun, 29 Mar 2009 02:46:30 -0500 (EST)
On 3/28/09 at 5:41 AM, sottosupremo at gmail.com (Filippo Miatto) wrote:
>Dear all, I need to generate all the vectors, of a given length N,
>that have these three properties:
>1- the entries have to be among -2,-1,0,1,2
>2- the sum of all the entries has to be 0
>3- only two or four of the entries can be different from 0
>do you have any suggestions on how i can do that? i tried something
>but without success.. expecially i don't know how to implement the
>third rule.. thank you in advance! Filippo
Rule 1 lists 5 distinct values. So, each vector can be thought
of as a N digit number base 5. And for N = 5, Range[5^4, 5^5 -
1] will be a list of all possible vectors of length 5 encoded as
a number base 5.
I can implement rule 3 as:
test = Pick[Range[5^4, 5^5 - 1],
Total[Unitize[IntegerDigits[#, 5] - 2]] & /@ Range[5^4, 5^5
- 1],
2 | 4];
IntegerDigits[value, 5] - 2
converts each encoded vector to the form specified by rule 1.
Unitize sets each non-zero value to 1. And Pick chooses just
those values with either 2 or 4 non-zero values.
Rule 2 can be implemented as:
Cases[test, _?(Total[IntegerDigits[#, 5]] == 10 &)]
Here, I look for a total of 10 rather than 0 since the digits
for base 5 numbers run from 0 to 4.
There are a total of
In[33]:= Length@Cases[test, _?(Total[IntegerDigits[#, 5]] == 10 &)]
Out[33]= 180
vectors of length 5 meeting your conditions above. The first 5 are:
In[35]:= (IntegerDigits[#, 5] - 2) & /@
Cases[test, _?(Total[IntegerDigits[#, 5]] == 10 &)][[;; 5]]
Out[35]= {{-1, -2, 0, 1, 2}, {-1, -2, 0, 2, 1}, {-1, -2, 1, 0,
2}, {-1, -2, 1, 2, 0}, {-1, -2, 2, 0, 1}}
I'll leave it to you to generalize the above for arbitrary
length vectors. Also, note I've not tried to optimize any of
this code. If N gets large, this code won't run all that fast as
things like IntegerDigits are being done more than once for the
same values.