Contents
LowestAvailableNaturalNumber
Naming Conventions |
|||||
|
Scalar |
Vector |
Matrix |
Any |
Non- |
Boolean |
BS |
BV |
BM |
BA |
BN |
Integer |
IS |
IV |
IM |
IA |
IN |
Float |
FS |
FV |
FM |
FA |
FN |
Numeric |
NS |
NV |
NM |
NA |
NN |
Character |
CS |
CV |
CM |
CA |
CN |
Enclosed |
ES |
EV |
EM |
EA |
EN |
enclosed |
TS |
TV |
TM |
TA |
TN |
Simple |
SS |
SV |
SM |
SA |
SN |
Any |
AS |
AV |
AM |
AA |
AN |
phrase e.g.: .X...Y. ⍝ X←BS; Y←IV |
|||||
combinations: use ISV for Integer scalar∨vector |
|||||
B3, I4 &c. to specify higher ranks. |
|||||
Find the lowest available natural number not in a list of numbers already in use.
This ⎕IO dependent phrase emerged after a brainstorming session involving half a dozen experienced APLers and one relative newbie. We wanted a new algorithm to generate a new file tie-number. Some processes used prescribed "magic" numbers. The common method of 1+0⌈⌈/⎕FNUMS was therefore suspect. Predictably the newbie was the one who hit the mark.
''⍴(⍳1+⍴IV)~IV
Naturally the direct route for the experts was to optimise the search among 1+0⌈⌈/iv possibilities. What could the number of numbers currently in use (⍴iv) possibly have to do with it?
Examples
⎕FX ⍕2 1⍴'r←Next iv' 'r←''''⍴(⍳1+⍴iv)~iv'
Next 0 1 3 4
2
Next⍳0
0
Next⍳9
9
Next 0 1 100 1000 10000 100000 1000000
2It should be noted that an origin of zero does not preclude zero's candidature:
⎕IO←0 ⋄ Next 1 2 3
0
⎕IO←1 ⋄ Next 1 2 3
4
How not to do it!
''⍴(⍳2+0⌈⌈/iv)~iv
A cursory look at the problem leads to examining all the numbers up to 1 greater than the maximum presently in use. Not a good idea if they can be chosen by another process such as a user's date-of-birth.
Conforming Variants
The search for a tie number must exclude zero so we include it in the "in use" list:
''⍴(⍳1+⍴iv)~iv←0,⎕FNUMS
A very similar variant deals with negative ⎕NNUMS:
-''⍴(⍳1+⍴iv)~iv←0,|⎕NNUMS
Another IO dependent (will provide numbers starting at []IO):
((⍳⍴,iv)∊iv)⍳0
Another always providing positive integers:
((⍳1+⍴,iv)∊0,iv)⍳0
Specialities
Both APLX and Dyalog APL offer an alternative method of selecting a free tie number. If you specify a tie number of 0, an operation like ⎕NTIE will select the first available tie number, for example:
tie←'C:\somedir\filename.txt' ⎕NTIE 0
Compatibility
Checked with: APL2, APLX, Dyalog, NARS2000
Test Cases
Show test cases
Test my code, both Examples and Test Cases.
See also: ...
Mentor: PhilLast
Tags: <LowestAvailableNaturalNumber> <NextInteger>
APL Wiki