문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

I realize this question is old, but there is a simpler way to do it: count to 9 in trinary, and add 1.

   1 + 3 3 #: i.9
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

The 3 3 & #: gives you two digits. The general 'base 3' verb is 3 & #.^:_1.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top