for i:1 thru 3 step 1 do;
posix:arithsum(li*cos(ri(t))),1,i-1)+(li*cos(ri(t))/2);
posiy:arithsum(li*sin(ri(t))),1,i-1)+(li*sin(ri(t))/2);
What I wanna do is to get 6 position functions(3 x and 3 y). It should give me values like following:
pos1x:l1*cos(r1(t))/2;
pos2x:l1*cos(r1(t))+l2*cos(r2(t))/2;
pos3x:l1*cos(r1(t))+l2*cos(r2(t))+l3*cos(r3(t))/2;
So, why my code is not working?
Couple of things here. (1) for loop takes just one expression as its loop body; typically multiple expressions are combined into one as (e1, e2, e3) or block(e1, e2, e3). Note that for ... do; isn't correct syntax, since it doesn't have a loop body -- the semicolon terminates the for expression. Note also that expressions in the body are separated by commas, not semicolons. (2) You can use subscript notation to index items; Maxima won't automatically construct symbol names such as pos1x. Instead, use subscript notation: posx[1], posy[i], etc.
Given that, here's a solution.
(%i1) load (functs);
(%o1) /Applications/Maxima.app/Contents/Resources/opt/share/maxima/5.41.0/shar\
e/simplification/functs.mac
(%i2) for i:1 thru 3 step 1 do
(posx[i]:arithsum(l[i]*cos(r[i](t)),1,i-1)+(l[i]*cos(r[i](t))/2),
posy[i]:arithsum(l[i]*sin(r[i](t)),1,i-1)+(l[i]*sin(r[i](t))/2));
(%o2) done
(%i3) [posx[1], posx[2], posx[3]];
l cos(r (t)) 3 l cos(r (t)) l cos(r (t))
1 1 2 2 1 3 3
(%o3) [-------------, ---------------, 2 (l cos(r (t)) + -) + -------------]
2 2 3 3 2 2
(%i4) [posy[1], posy[2], posy[3]];
l sin(r (t)) 3 l sin(r (t)) l sin(r (t))
1 1 2 2 1 3 3
(%o4) [-------------, ---------------, 2 (l sin(r (t)) + -) + -------------]
2 2 3 3 2 2
I am guessing that l[i] and r[i] should be subscripted too. I changed the parentheses in order to fix a syntax problem; if you intended something else, of course you can go ahead and change it again.
Note that in this formulation posx and posy are so-called undeclared arrays. Undeclared arrays are suitable for representing subscripted symbolic variables. You can get the list of elements via listarray.
Related
What is the best practice for inserting an element into an array at an arbitrary position in J?
I guess this is sort of a double question: my main issue is figuring out how to provide three arguments to the verb I want to create. The gist of the code that I want to write is
insert =. dyad : '(n {. y) , x , (n }. y)'
for a position n. The best solution to this that I can think of is taking a two-length array of boxes as the right argument and the position as the left, but that seems a bit clunky
insert =. dyad : 0
NB. the array to be inserted is the first argument
i =. > {. y
NB. the original array is the second argument
a =. > {: y
(x {. a) , i , (x }. a)
)
EDIT: Furthermore, would it be possible to take an array of indices to insert the item at and an array of items to be inserted at those indices -- i.e. inserting multiple items at a time? It seems to me like this is something J would be good at, but I'm not sure how it would be done.
Boxing the arguments is an often used technique. You can use multiple assignment for cleaner code:
f =: 3 : 0
'arg1 arg2' =: y
)
f (i.5);(i.9) NB. arg1 is i.5, arg2 is i.9
To insert array a at position n in L, you can more compactly write:
n ({., a, }.) L
Another way to insert an element into an array is to fill with #!.. Some examples:
1 1 1j2 1 (#!.999) 1 2 3 4
1 2 3 999 999 4
1j1 1 1j1 1 (#!.999) 1 2 3 4
1 999 2 3 999 4
1 1 0j1 1 (#!.999) 1 2 3 4
1 2 999 4
Depending on your needs, there are many other tricks you can use, like shifting by n n |. and then undoing the shift with dual &.:
a,&. (n |. ]) L
(reply to the comment that got too long)
Both from readability and performance standpoint the two methods are about the same. I would slightly favor the first as more readable but would probably use the second.
You can use timespacex verb to check the performance: eg.
NB. define the different methods
f1 =: 4 :'x ({., a, }.) y
f2 =: 4 :' a,&. (x |. ]) y'
NB. set some parameters
a =: 1000 $ 9
L =: 1e6 $ 5
n =: 333456
NB. check if the too methods give identical results
(n f1 L) -: (n f2 L)
1
NB. iterate 100 times to get performance averages
100 timespacex'n f1 L'
0.00775349 2.09733e7
100 timespacex'n f2 L'
0.00796431 1.67886e7
Given two (named) arrays x and y, where all dimnames(y) exist in x.
How can I fill (update) x with values from y, but ignoring NAs in y?
I have come so far:
x<-array(1:15,dim=c(5,3),dimnames=list(1:5,1:3))
y<-(NA^!diag(1:3))*diag(1:3)
dimnames(y)<-list(1:3,1:3)
x[match(names(y[,1]),names(x[,1])),match(names(y[1,]),names(x[1,]))]<-y
But this also overwrites x with "NA"s from y.
1 2 3
1 1 NA NA
2 NA 2 NA
3 NA NA 3
4 4 9 14
5 5 10 15
I guess it's something involving a filter !is.na(y) but I haven't found the right place to put it?
Thanks for any hint
We match the rownames of 'y' with rownames of 'x' to create the row index ('rn'), similarly get the corresponding column index ('cn') by matching. Get the index of values in 'y' that are non-NAs ('indx'). Subset the 'x' with row index, column index and resubset with 'indx' and replace those values with the non-NA values in y (y[indx]).
rn <- match(rownames(y), rownames(x))
cn <- match(colnames(y), colnames(x))
indx <- which(!is.na(y), arr.ind=TRUE)
x[rn,cn][indx] <- y[indx]
Or instead of matching, we can subset the 'x' with rownames(y) and colnames(y) and replace it as before.
x[rownames(y), colnames(y)][indx] <- y[indx]
You can index directly with rownames and colnames to get the relevant parts of x covered by y, and replace conditionally using ifelse:
x[rownames(y),colnames(y)] <- ifelse(is.na(y),x[rownames(y),colnames(y)],y)
x
1 2 3
1 1 6 11
2 2 2 12
3 3 8 3
4 4 9 14
5 5 10 15
just for completeness:
The accepted answer works under the assumption that we have a 2d-array (row/colnames).
But as the real problem was in higher dimension space (and this may the case for later readers) I show here how the solution can also be applied to the initial dimension-independent approach:
indx <- !is.na(y)
x[match(names(y[,1]),names(x[,1])),match(names(y[1,]),names(x[1,]))][indx] <- y[indx]
Thanks!
I'm going to create a program that can generate strings from L-system grammars.
Astrid Lindenmayer's original L-System for modelling the growth of algae is:
variables : A B
constants : none
axiom : A
rules : (A → AB), (B → A)
which produces:
iteration | resulting model
0 | A
1 | AB
2 | ABA
3 | ABAAB
4 | ABAABABA
5 | ABAABABAABAAB
that is naively implemented by myself in J like this:
algae =: 1&algae : (([: ; (('AB'"0)`('A'"0) #. ('AB' i. ]))&.>"0)^:[) "1 0 1
(i.6) ([;algae)"1 0 1 'A'
┌─┬─────────────┐
│0│A │
├─┼─────────────┤
│1│AB │
├─┼─────────────┤
│2│ABA │
├─┼─────────────┤
│3│ABAAB │
├─┼─────────────┤
│4│ABAABABA │
├─┼─────────────┤
│5│ABAABABAABAAB│
└─┴─────────────┘
Step-by-step illustration:
('AB' i. ]) 'ABAAB' NB. determine indices of productions for each variable
0 1 0 0 1
'AB'"0`('A'"0)#.('AB' i. ])"0 'ABAAB' NB. apply corresponding productions
AB
A
AB
AB
A
'AB'"0`('A'"0)#.('AB' i. ])&.>"0 'ABAAB' NB. the same &.> to avoid filling
┌──┬─┬──┬──┬─┐
│AB│A│AB│AB│A│
└──┴─┴──┴──┴─┘
NB. finally ; and use ^: to iterate
By analogy, here is a result of the 4th iteration of L-system that generates Thue–Morse sequence
4 (([: ; (0 1"0)`(1 0"0)#.(0 1 i. ])&.>"0)^:[) 0
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
That is the best that I can do so far. I believe that boxing-unboxing method is insufficient here. This is the first time I've missed linked-lists in J - it's much harder to code grammars without them.
What I'm really thinking about is:
a) constructing a list of gerunds of those functions that build final string (in my examples those functions are constants like 'AB'"0 but in case of tree modeling functions are turtle graphics commands) and evoking (`:6) it,
or something that I am able to code:
b) constructing a string of legal J sentence that build final string and doing (".) it.
But I'm not sure if these programs are efficient.
Can you show me a better approach please?
Any hints as well as comments about a) and b) are highly appreciated!
The following will pad the rectangular array with spaces:
L=: rplc&('A';'AB';'B';'A')
L^:(<6) 'A'
A
AB
ABA
ABAAB
ABAABABA
ABAABABAABAAB
Or if you don't want padding:
L&.>^:(<6) <'A'
┌─┬──┬───┬─────┬────────┬─────────────┐
│A│AB│ABA│ABAAB│ABAABABA│ABAABABAABAAB│
└─┴──┴───┴─────┴────────┴─────────────┘
Obviously you'll want to inspect rplc / stringreplace to see what is happening under the covers.
You can use complex values in the left argument of # to expand an array without boxing.
For this particular L-system, I'd probably skip the gerunds and use a temporary substitution:
to =: 2 : 'n (I.m=y) } y' NB. replace n with m in y
ins =: 2 : '(1 j. m=y) #!.n y' NB. insert n after each m in y
L =: [: 'c'to'A' [: 'A'ins'B' [: 'B'to'c' ]
Then:
L^:(<6) 'A'
A
AB
ABA
ABAAB
ABAABABA
ABAABABAABAAB
Here's a more general approach that simplifies the code by using numbers and a gerund composed of constant functions:
'x'-.~"1 'xAB'{~([:,(0:`(1:,2:)`1:)#.]"0)^:(<6) 1
A
AB
ABA
ABAAB
ABAABABA
ABAABABAABAAB
The AB are filled in at the end for display. There's no boxing here because I use 0 as a null value. These get scattered around quite a bit but the -.~"1 removes them. It does pad all the resulting strings with nulls on the right. If you don't want that, you can use <#-.~"1 to box the results instead:
'x'<#-.~"1 'xAB'{~([:,(0:`(1:,2:)`1:)#.]"0)^:(<6) 1
┌─┬──┬───┬─────┬────────┬─────────────┐
│A│AB│ABA│ABAAB│ABAABABA│ABAABABAABAAB│
└─┴──┴───┴─────┴────────┴─────────────┘
Given an array of length n, I need to print out the array's lexicographic index (indexed from zero). The lexicographic index is essentially the location that the given array would have if placed in a super-array containing all possible permutations of the original array.
This doesn't turn out to be all that difficult (Unique Element Permutations), but my problem is now making the same algorithm, but for an array containing duplicates of the same element.
Here's an example chart showing some of the possible permutations of a small array, and their respective expected return values:
[0 1 1 2 2]->0
[0 1 2 1 2]->1
[0 1 2 2 1]->2
[0 2 1 1 2]->3
[0 2 1 2 1]->4
[0 2 2 1 1]->5
[1 0 1 2 2]->6
[1 0 2 1 2]->7
[1 0 2 2 1]->8
[1 1 0 2 2]->9
[1 1 2 0 2]->10
[1 1 2 2 0]->11
..
[2 2 1 0 1]->28
[2 2 1 1 0]->29
Most importantly, I want to do this WITHOUT generating other permutations to solve the problem (for example, I don't want to generate all permutations less than the given permutation).
I'm looking for pseudocode - no specific language needed as long as I can understand the concept. Even the principle for calculation without pseudocode would be fine.
I've seen some implementations that do something similar but for a binary string (containing only two distinct types of elements), and they used binomial coefficients to get the job done. Hopefully that helps.
As an aside, though the answers to the question linked in Daishisan's comment fulfil the multiset case, the algorithm in your link for binary numbers (for which I was searching when I came upon your answer) works for indexing because it's bijective, but doesn't index the binary number within the sorted infinite sequence of those with the same bit count as you may expect. With the following dependencies,
from functools import reduce
fact=(lambda n: reduce(int.__mul__,range(1,n+1)) if n else 1)
choose=(lambda n,*k: fact(n)//(reduce(int.__mul__,map(fact,k))*fact(n-sum(k))) if all(map(lambda k: 0<=k,k+(n-sum(k),))) else 0)
decompose=(lambda n,l=None: (n>>i&1 for i in range(n.bit_length() if l==None else l)))
It is equivalent to
lambda i,n: reduce(lambda m,i: (lambda s,m,i,b: (s,m-1) if b else (s+choose(n+~i,m),m))(*m,*i),enumerate(decompose(i,n)),(0,i.bit_count()-1))[0]
However, I played with it and found a reduced version that does fulfil this purpose (and thus doesn't need a length specified).
lambda i: reduce(lambda m,i: (lambda s,m,i,b: (s+choose(i,m),m) if b else (s,m+1))(*m,*i),enumerate(decompose(i)),(0,-1))[0]
This is equivalent to A079071 in the OEIS.
Edit: More efficient version without fact and choose (instead mutating choose's output in-place with the other variables)
lambda i: reduce(lambda m,i: (lambda s,m,c,i,b: ((s+c,m,c*i//(i-m+1)) if b else (s,m+1,c*i//m)) if m else (s,m+1-b,c))(*m,*i),enumerate(decompose(i),1),(0,0,1))[0]
I want to write prime function for purposes of learning J.
So far I've come up with this:
=&0+/(=&0)(2+i.(-&2)y)|y
It's working great except that I should store number in y variable.
y=.5
=&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
1
y=.13
=&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
1
y=.14
=&0+/(=&0)(2+i.(-&2)y)|y NB. prime cheker
0
How do I write a function that works what takes argument? i.e. f 13 -> 1
You can just define a verb using : 3.
f =: 3 :'=&0+/(=&0)(2+i.(-&2)y)|y'
f 5
1
f 13
1
f 10
0
When using : 3, y always refers to the right hand argument of the verb.
If you want to define a dyadic verb, use : 4 and x for the left argument.
Btw, you can set the value of a variable anywhere:
=&0+/(=&0)(2+i.(-&2)y)|y=.5
1
=&0+/(=&0)(2+i.(-&2)y)|y=.10
0
You might find the Defining Verbs Guide on the J Wiki useful.
As has already been mentioned you can take your sentence and define it as a verb using the following syntax:
isPrime0=: 3 : '=&0+/(=&0)(2+i.(-&2)y)|y'
However it is probably more natural to write it like this:
isPrime1=: 3 : '0 = (+/ 0 = (2 + i. y - 2) | y)'
You could also define a tacit version (doesn't refer to the arguments) like any of the following:
isPrime2=: 0 = [: +/ 0 = ] |~ 2 + [: i. 2 -~ ]
isPrime3=: 0 = [: +/ 0 = ] |~ 2 + i.#:-&2 NB. replace train with verb composed using conjunctions
isPrime4=: 0 = [: +/ 0 = ] |~ i.&.(-&2) NB. use Under to re-add the 2 after Integers
isPrime5=: 0 -.#e. i.&.(-&2) | ] NB. check no zero in result