0

I am not able to print values ranging from 30 to 50 both inclusive in APL.

Actually I tried so much operators but not working.

  • Stating which implementation and version of APL you use, will help people to give you the best response. – Adám Apr 19 '23 at 10:28

3 Answers3

2

What are your constraints? Do you want to define a function or do you just want to know how to iterate? Does "print" mean return as result or literally print to somewhere (output/file)?

In the easiest way, use iota to iterate through the distance between the two bounds, then add the lower one to the results. Assuming index origin IO is set to 0:

    30 + ⍳21
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

If IO is set to 1, lower the lower bound:

    29 + ⍳21
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

You can always inspect or set IO using ⎕IO if you wanted to switch:

    ⎕IO ← 0
0
pmf
  • 24,478
  • 2
  • 22
  • 31
1

Actually I wanted to print random 12 values between 8 to 30.

If ⎕IO is set to 1, you can generate a random integer larger or equal to 1 and smaller or equal to 23 using ?23 (or ?1+30-8). Then, add 7 (or 8-1) to the result, and it will be shifted between 8 and 30, both inclusive: 7+?23. (With ⎕IO set to 0, the generated random number will instead range from 0 to 22, so to reach the destination range you'd have to add 8 rather than 7, or (8-⎕IO) more generically if independence from ⎕IO is a concern.)

Now, to draw more than one random number from that range, provide ? in its left argument with the amount of draws you'd like to see. The result is an array of that length.

      7+12?23
23 21 9 8 10 27 12 30 28 19 26 14

Note that these numbers are all unique (no duplicates). To instead get an array of independent random numbers (values can be drawn more than once), use to accordingly reshape the (right) argument of ? which will then be applied onto the whole array:

      7+?12⍴23
9 8 30 16 13 25 26 8 26 19 19 18
pmf
  • 24,478
  • 2
  • 22
  • 31
0

@pmf's solution is simple, but can be very inefficient (for two large, but close values) and fails if any number is negative.

If we call the bounds and then ⍺+¯1+⍳1+⍵-⍺ is both efficient and general. Remove ¯1+ if ⎕IO is 0. You can create a to function using this formula as follows:

      to←{(⍺-⎕IO)+¯1+⍳1+⍵-⍺}
      30 to 50
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Alternatively, if you use Dyalog APL, you can use the to utility function from the dfns workspace, as follows:

      'to' ⎕CY 'dfns'
      30 to 50
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Adám
  • 6,573
  • 20
  • 37
  • As regards your first solution, wouldn't `to←{(⍺-⎕IO)+⍳1+⍵-⍺}` solve it agnostically for `⎕IO`? – Jeff Zeitlin Apr 19 '23 at 11:37
  • @JeffZeitlin It would, of course, but I wanted to keep the formula simple. I'll change the function definition, though. – Adám Apr 19 '23 at 15:27