tags:

views:

57

answers:

2

Imagine that I want to take the numbers from 1 to 3 and form a matrix such that each possible pairing is represented, e.g.,

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Here is the monadic verb I formulated in J to do this:

($~ (-:@# , 2:)) , ,"0/~ 1+i.y

Originally I had thought that ,"0/~ 1+i.y would be sufficient, but unfortunately that produces the following output:

1 1
1 2
1 3

2 1
2 2
2 3

3 1
3 2
3 3

In other words, its shape is 3 3 2 and I want something whose shape is 9 2. The only way I could think of to fix it is to pour all of the data into a new shape. I'm convinced there must be a more concise way to do this. Anyone know?

+2  A: 

One way (which uses { as a monad in its capacity for permutation cataloguing):

>,{ 2#<1+i.y

EDIT:

Some fun to be had with this scheme:

All possible permutations:

>,{ y#<1+i.y

Configurable number in sequence:

>,{ x#<1+i.y
MPelletier
Very cool! I just spent a while playing around with `{` and figuring out the meaning of the above syntax, which is now crystal clear to me. I'll wait a few days to see if there are any even more concise answers, but my guess is you've probably nailed this one. Thanks!
Gregory Higley
You're welcome. I can rarely find a good use for `{`, and I find it does not always do what I want, but against the same list it works well.
MPelletier
Yeah, J is not SO's most popular language. Nor is it my favourite. The J community is closely clustered around jsoftware.com, but usually there any question like this spins out of control and expands into a myriad replies on fringe optimisation and special code.
MPelletier
I don't think I have a favorite programming language, though J is among my favorites. It has definitely expanded my horizons as a developer.
Gregory Higley
@GregoryHigley Most of what I do for work is J. J is great for math and matrixes and stuff, but not so much for data modelling, GUI, communication, etc. When you use it as a specialised tool, ok, but as a do-it-all tool, not so much.
MPelletier
I agree completely. I see J being useful as an embedded, domain-specific language, but I couldn't see doing much else with it.
Gregory Higley
+4  A: 

Reshaping your intermediate result can be simplified. Removing the topmost axis is commonly done with ,/ so in your case the completed phrase could be ,/ ,"0/~ 1+i.y

kaleidic
Very clever. J is such a mind-bending language.
Gregory Higley
Now that I've looked into it, it appears that the result of `,/` is to create a result whose shape is equal to the multiplication of the top two axes, e.g., if you apply `,/` to something whose shape is 7 4 2, it becomes 28 2. That's really useful! Thank you.
Gregory Higley
+1 for the `,/` bit. Learn something new every day :)
MPelletier