Lucky and even lucky numbers: Difference between revisions

(Added Ruby)
(→‎{{header|Tcl}}: Added zkl)
Line 568:
bash$ lucky.tcl 10000 , evenLucky
10000'th even lucky number = 111842
</pre>
 
=={{header|zkl}}==
The lucky number generator works by chaining filters to a even or odd infinite sequence. So it acts like a sieve as each starting number percolates through the filters. It also means there are lots and lots of filters, which doesn't scale well but works for the examples.
<lang zkl>fcn lgen(a){
ns,idx:=[a..*,2],2;
vm.yield(ns.next());
while(1){
n:=ns.next();
vm.yield(n);
ns=ns.tweak(skipper.fp1(n,Ref(idx+=1))); // tack on another filter
}
}
fcn skipper(n,skp,cnt){ z:=cnt.inc(); if(z%skp==0) Void.Skip else n }</lang>
The command line is a bit funky (by Unix standards) so we just hard code it and use exceptions (such as trying to convert "foo" to int) to show the options.
<lang zkl>cmdLineArgs,j,k,start:=vm.arglist,Void,Void,1;
try{
j=cmdLineArgs[0].toInt();
na:=cmdLineArgs.len();
if(na>1){
if(cmdLineArgs[1]==",")
start=cmdLineArgs[2][0].toLower()=="e" and 2 or 1;
else{
k=cmdLineArgs[1].toInt();
if(na>2)
start=cmdLineArgs[2][0].toLower()=="e" and 2 or 1;
}
}
}catch{
fcn options{
"args: j | j , [even]lucky | j k [even]lucky | j -k [even]lucky"
.println();
System.exit(1);
}()
}
luckies:=Utils.Generator(lgen,start);
try{
if(Void==k) luckies.drop(j-1).next().println();
else{
if(k>0) luckies.drop(j-1).walk(k-j+1).println();
else{ k=-k;
while((n:=luckies.next())<j){}
luckies.push(n);
luckies.pump(List,'wrap(n){ n<=k and n or Void.Stop }).println();
}
}
}catch(TheEnd){ options() }</lang>
{{out}}
<pre>
$ zkl lucky
args: j | j , [even]lucky | j k [even]lucky | j -k [even]lucky
$ zkl lucky 1 20
L(1,3,7,9,13,15,21,25,31,33,37,43,49,51,63,67,69,73,75,79)
$ zkl lucky 1 20 evenLucky
L(2,4,6,10,12,18,20,22,26,34,36,42,44,50,52,54,58,68,70,76)
$ zkl lucky 6000 -6100
L(6009,6019,6031,6049,6055,6061,6079,6093)
$ zkl lucky 6000 -6100 Even
L(6018,6020,6022,6026,6036,6038,6050,6058,6074,6090,6092)
$ zkl lucky 10000
115591
$ zkl lucky 10000 , evenLucky
111842
$ zkl lucky 6000 -5000
L()
$ zkl lucky 4 2
args: j | j , [even]lucky | j k [even]lucky | j -k [even]lucky
</pre>
Anonymous user