American Citizen on Sat, 16 Nov 2024 01:03:50 +0100 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
some questions on mapping from an integer to a vector and inversely |
Hello:My topic is on how to develop mapping from one integer n into n-integers [vector] , or 1-dimensional space to n-dimensional space.
This is a mapping of 1d(n) --> nd[n] and of course, the inverse map which takes the n-dim vector back to the integer.
When writing C or C++ code I commonly use loops for variables such as for ( a = 0; a<100; a++) { for( b = a+1; b<100; b++) { do stuff } } We want a unique n for {a,b} Other times I start the loop at 1 not 0 as the root index for ( i = 1, n, for(j=i+1,n, {do stuff} ) )So similarly we want a unique n. I call these loops zero-based or one-based, which is very similar to how C or C++ code indexes vectors (which is zero-based)
I developed some simple maps on my own map_xy_to_n(x,y) = (y^2 + (2*x + 1)*y + x*(x + 3))/2;map_n_to_xy(n) = S=floor((sqrt(8*n+1)-1)/2);T=S*(S+1)/2;x=n-T;y=S-x;return([x,y]);
bi_Z_to_N(Z)=if(Z<0,return(-2*Z-1),return(2*Z)); bi_N_to_Z(N)=if(N%2==0,return(N/2),return(-(N+1)/2)); \\ Forward map x,y --> n \\ 21 [0,6] \\ 15 [0,5] 22 [1,5] \\ 10 [0,4] 16 [1,4] 23 [2,4] \\ 6 [0,3] 11 [1,3] 17 [2,3] 24 [3,3] \\ 3 [0,2] 7 [1,2] 12 [2,2] 18 [3,2] 25 [4,2] \\ 1 [0,1] 4 [1,1] 8 [2,1] 13 [3,1] 19 [4,1] 26 [5,1] \\ 0 [0,0] 2 [1,0] 5 [2,0] 9 [3,0] 14 [4,0] 20 [5,0] 27 [6,0] \\ Inverse map n --> x,y \\ 21 [0,6] 22 [1,5] 23 [2,4] 24 [3,3] 25 [4,2] 26 [5,1] 27 [6,0] \\ 15 [0,5] 16 [1,4] 17 [2,3] 18 [3,2] 19 [4,1] 20 [5,0] \\ 10 [0,4] 11 [1,3] 12 [2,2] 13 [3,1] 14 [4,0] \\ 6 [0,3] 7 [1,2] 8 [2,1] 9 [3,0] \\ 3 [0,2] 4 [1,1] 5 [2,0] \\ 1 [0,1] 2 [1,0] \\ 0 [0,0] xy_MAP0_n(V)=my(x,y);[x,y]=V;x*(x-1)/2+y; n_MAP0_xy(n)=x=floor(real(polroots('x*('x-1)/2-n)[2]));y=n-x*(x-1)/2;[x,y]; xy_MAP1_n(V)=xy_MAP0_n([V[1]-1,V[2]-1])+1; n_MAP1_xy(n)=[x,y]=n_MAP0_xy(n-1);[x+1,y+1]; but I want to move to 3 or 4 terms involved, not just 2. Is there an easy way to do 1-d mapping to n-d and the inverse, of course? Randall