I need to use J to print a checker board, my function given an odd number needs to create a NxN matrix and place an 'X' in every other box. I have the matrix made but I can not figure out the every other box part.
What I have so far
N =: 3
checker =: (2$N)$ <'X'
If anyone could help, I would appreciate it!
The simplest route is to use a:,<'X' in place of <'X':
(2$N)$ a:,<'X'
The reason this works is because x $ y (reshape) reuses y cyclically if */x is greater than the number of items in y.
Having said that, it might be more interesting to approach this analytically using a fundamental pattern in array programming, which will be much more widely applicable than a fixed number of repetitions or pattern.
Try this:
(a:,<'X') {~ 2 | i. ,~ N
For example:
(a:,<'X') {~ 2|i.,~5
+-+-+-+-+-+
| |X| |X| |
+-+-+-+-+-+
|X| |X| |X|
+-+-+-+-+-+
| |X| |X| |
+-+-+-+-+-+
|X| |X| |X|
+-+-+-+-+-+
| |X| |X| |
+-+-+-+-+-+
Broken down from right-to-left:
y=. ,~ N NB. Duplicate N; ,~5 becomes 5,5y=. i.y NB. NxN table of the first N^2 non-negative integersy=.2|y NB. y mod 2, so an NxN table of 0 1 0 1 0 1 ...y=.(a:,<'X') {~ y NB. Map 0 to ace (empty) and 1 to <'X'Packed up as a re-usable verb:
cb =: verb def ' (a:,<'X') {~ 2 | i. ,~ y'cb =: (a:,<'X') {~ 2 | i.@,~This pattern of creating an array of all possible results, and indexing all outputs into them simultaneously, is one of the fundamental mechanics of array programming, and widely used in a number of different idioms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With