Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

J Checker Board

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!

like image 732
Michael Miner Avatar asked Mar 22 '26 05:03

Michael Miner


1 Answers

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:

  1. y=. ,~ N NB. Duplicate N; ,~5 becomes 5,5
  2. y=. i.y NB. NxN table of the first N^2 non-negative integers
  3. y=.2|y NB. y mod 2, so an NxN table of 0 1 0 1 0 1 ...
  4. y=.(a:,<'X') {~ y NB. Map 0 to ace (empty) and 1 to <'X'

Packed up as a re-usable verb:

  1. Explicit: cb =: verb def ' (a:,<'X') {~ 2 | i. ,~ y'
  2. Tacit: 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.

like image 89
Dan Bron Avatar answered Mar 25 '26 01:03

Dan Bron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!