Connor
Connor

Reputation: 4844

Why is my APL expression returning 1 2 1 2 instead of 0 1 0 1?

My expression

?(1 2 × 4) ⍴2

Is returning

1 1 1 2 2 1 1 2
1 1 1 1 1 1 2 2
2 2 1 1 2 1 1 2
1 1 2 1 1 1 2 2

but I expected it to return

1 1 0 0 1 0 1 0
0 1 0 1 0 0 0 1
0 0 0 1 0 0 0 0
1 1 1 1 1 1 0 1

Why?

Upvotes: 1

Views: 69

Answers (2)

RikedyP
RikedyP

Reputation: 701

It looks like you're trying to create a random Boolean array.

      ?(1 2 × 4)⍴2
2 2 2 1 1 2 2 2
2 1 1 2 1 2 2 2
1 1 2 1 2 2 2 2
2 1 1 1 2 2 1 1

Many APL implementations have a default index origin of 1, including Dyalog.

Setting ⎕IO (Index Origin) is one way to get your desired result:

      ⎕IO←0
      ?(1 2 × 4)⍴2
0 1 0 0 1 1 0 0
0 1 1 1 1 0 0 0
1 0 1 1 1 0 1 1
0 0 0 0 0 1 0 0

A ⎕IO-independent way of generating random Booleans is to ask equality with 1:

      ⎕IO←1=?2         ⍝ ⎕IO may be 1 or 0
      1=?(1 2 × 4)⍴2   ⍝ Random Boolean matrix
0 1 1 0 0 1 1 1
0 1 0 1 0 1 1 0
1 0 1 0 0 1 0 0
1 0 0 0 1 1 0 1

Upvotes: 1

Connor
Connor

Reputation: 4844

You need to set the index to 0, APL's default index is 1.

Here's how you spell, "Set index to 0":

 ⎕IO←0  

Upvotes: 0

Related Questions