task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times to call the integer generator. A 'delta' value of some sort that indicates how close to a flat distribution is close enough. The function should produce: Some indication of the distribution achieved. An 'error' if the distribution is not flat enough. Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice). See also: Verify distribution uniformity/Chi-squared test
#zkl
zkl
fcn rtest(N){ dist:=L(0,0,0,0,0,0,0,0,0,0); do(N){n:=(0).random(10); dist[n]=dist[n]+1} sum:=dist.sum(); dist=dist.apply('wrap(n){n.toFloat()/sum*100}); if (dist.filter((10.0).closeTo.fp1(0.1)).len() == 10) { "Good enough at %,d: %s".fmt(N,dist).println(); return(True); } False }   n:=10; while(not rtest(n)) {n*=2}
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#J
J
1+I.(}:=}.) 1 2 2 3 4 4 5 2 5
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Java
Java
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5};   // There is no output as 'prev' is created anew each time // around the loop and set to zero. for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; // int prev; // triggers "error: variable prev might not have been initialized" if (i > 0 && curr == prev) System.out.println(i); prev = curr; }   int gprev = 0;   // Now 'gprev' is used and reassigned // each time around the loop producing the desired output. for (int i = 0; i < s.length; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) System.out.println(i); gprev = curr; } } }
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#JavaScript
JavaScript
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>variable declaration reset</title> </head> <body> <script> "use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) { let curr = s[i], prev; if (i>0 && (curr===prev)) { console.log(i); } prev = curr; } </script> </body> </html>
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#360_Assembly
360 Assembly
* Van der Corput sequence 31/01/2017 VDCS CSECT USING VDCS,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) " -> LR R13,R15 " addressability ZAP B,=P'2' b=2 (base) ZAP M,=P'-1' m=-1 SR R6,R6 i=0 LOOPI CH R6,=H'10' do i=0 to 10 BH ELOOPI AP M,=P'1' w=m+1 ZAP V,=P'0' v=0 ZAP S,=P'1' s=1 ZAP N,M n=m WHILE CP N,=P'0' do while n<>0 BE EWHILE MP S,B s=s*b ZAP PL16,N n DP PL16,B n/b ZAP W,PL16+8(8) w=n mod b MP W,=P'100000' *100000 ZAP PL16,W w DP PL16,S w/s ZAP W,PL16(8) w=w/s AP V,W v=v+(n mod b)*100000/s ZAP PL16,N n DP PL16,B n/b ZAP N,PL16(8) n=n/b B WHILE EWHILE XDECO R6,XDEC edit i MVC PG+0(3),XDEC+9 output i MVC PG+3(3),=C' 0.' UNPK Z,V unpack v OI Z+L'Z-1,X'F0' edit v MVC PG+6(5),Z+11 output v (v/100000) XPRNT PG,L'PG print buffer LA R6,1(R6) i=i+1 B LOOPI ELOOPI L R13,4(0,R13) epilog LM R14,R12,12(R13) " restore XR R15,R15 " rc=0 BR R14 exit B DS PL8 M DS PL8 V DS PL8 S DS PL8 N DS PL8 W DS PL8 packed Z DS ZL16 zoned PL16 DS PL16 packed max PG DC CL80' ' buffer XDEC DS CL12 work area for xdeco YREGS END VDCS
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Generate(INT value,base REAL POINTER res) REAL denom,rbase,r1,r2   IntToReal(0,res) IntToReal(1,denom) IntToReal(base,rbase) WHILE value#0 DO RealMult(denom,rbase,r1) RealAssign(r1,denom) IntToReal(value MOD base,r1) RealDiv(r1,denom,r2) RealAdd(res,r2,r1) RealAssign(r1,res) value==/base OD RETURN   PROC Main() INT value,base REAL res   Put(125) PutE() ;clear the screen FOR base=2 TO 5 DO PrintF("Base %I:%E",base) FOR value=0 TO 9 DO Generate(value,base,res) PrintR(res) Put(32) OD PutE() PutE() OD RETURN
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#8086_Assembly
8086 Assembly
.data MyVar word 0FFFFh ;the leading zero is just to help the assembler tell that this is a number, it's not actually part of the variable.   .code   mov ax, word ptr [ds:MyVar]
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#8th
8th
  \ declare a variable which is initialized to the number '0' var x   \ declare a variable which is initialized to a string "cat" "cat" var, y   \ Get the value in x, add 20 and store it: x @ 20 n:+ x !   \ Change the cat to a dog: "dog" y !  
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Ada
Ada
with Ada.Text_IO;   procedure Van_Eck_Sequence is   Sequence : array (Natural range 1 .. 1_000) of Natural;   procedure Calculate_Sequence is begin Sequence (Sequence'First) := 0; for Index in Sequence'First .. Sequence'Last - 1 loop Sequence (Index + 1) := 0; for I in reverse Sequence'First .. Index - 1 loop if Sequence (I) = Sequence (Index) then Sequence (Index + 1) := Index - I; exit; end if; end loop; end loop; end Calculate_Sequence;   procedure Show (First, Last : in Positive) is use Ada.Text_IO; begin Put ("Element" & First'Image & " .." & Last'Image & " of Van Eck sequence: "); for I in First .. Last loop Put (Sequence (I)'Image); end loop; New_Line; end Show;   begin Calculate_Sequence; Show (First => 1, Last => 10); Show (First => 991, Last => 1_000); end Van_Eck_Sequence;
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Bracmat
Bracmat
( ( vampire = N len R fangsList .  !arg:@(?N:? [?len) & 1/2*!len:~/:?len & ( R = len numpart left right allowed fangs rdigits , tried digit untried head tail found .  !arg:(?len.?left.?numpart.?allowed) & :?found & (  !len:>0 & ( @( !numpart  :  ?tried ( #%@?digit & !allowed:?head !digit ?tail & !head !tail:?allowed ) ( ?untried & R $ ( !len+-1 . 10*!left+!digit . str$(!tried !untried) . 0 1 2 3 4 5 6 7 8 9 )  : ?fangs & !found !fangs:?found & ~ ) ) | !found ) |  !N*!left^-1:~/?right:~<!left:?rdigits & (!left*1/10:/|!right*1/10:/) & ( @( !numpart  :  ? ( #%@?digit ? & @(!rdigits:?head !digit ?tail) & str$(!head !tail):?rdigits & ~ ) ) | !rdigits:&(!left,!right) ) ) ) & R$(!len.0.!N.1 2 3 4 5 6 7 8 9)  : ( |  ?fangsList & out$(!N !fangsList) & 1+!count:?count ) ) & 0:?count & 10:?i & 16758243290880 24959017348650 14593825548650:?bignums & whl ' ( ( vampire$!i&1+!i:?i | !i*10:?i ) & (!count:<25|!bignums:%?i ?bignums) ) );
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h>   typedef uint64_t xint; typedef unsigned long long ull;   xint tens[20];   inline xint max(xint a, xint b) { return a > b ? a : b; } inline xint min(xint a, xint b) { return a < b ? a : b; } inline int ndigits(xint x) { int n = 0; while (x) n++, x /= 10; return n; }   inline xint dtally(xint x) { xint t = 0; while (x) t += 1<<((x%10) * 6), x /= 10;   return t; }   int fangs(xint x, xint *f) { int n = 0; int nd = ndigits(x); if (nd & 1) return 0; nd /= 2;   xint lo, hi; lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1)); hi = min(x / lo, sqrt(x));   xint a, b, t = dtally(x); for (a = lo; a <= hi; a++) { b = x / a; if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b)) f[n++] = a; }   return n; }   void show_fangs(xint x, xint *f, xint cnt) { printf("%llu", (ull)x); int i; for (i = 0; i < cnt; i++) printf(" = %llu x %llu", (ull)f[i], (ull)(x / f[i])); putchar('\n'); }   int main(void) { int i, j, n; xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0};   tens[0] = 1; for (i = 1; i < 20; i++) tens[i] = tens[i-1] * 10;   for (x = 1, n = 0; n < 25; x++) { if (!(j = fangs(x, f))) continue; printf("%2d: ", ++n); show_fangs(x, f, j); }   putchar('\n'); for (i = 0; bigs[i]; i++) { if ((j = fangs(bigs[i], f))) show_fangs(bigs[i], f, j); else printf("%llu is not vampiric\n", (ull)bigs[i]); }   return 0; }
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#PARI.2FGP
PARI/GP
hex(s)=my(a=10,b=11,c=12,d=13,e=14,f=15);subst(Pol(eval(Vec(s))),'x,16); n1=hex("200000");n2=hex("1fffff"); v1=digits(n1,256) v2=digits(n2,256) subst(Pol(v1),'x,256)==n1 subst(Pol(v2),'x,256)==n2
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#Perl
Perl
  use warnings; use strict;   for my $testcase ( 0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000 ) { my @vlq = vlq_encode($testcase); printf "%8s %12s %8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq); }   sub vlq_encode { my @vlq; my $binary = sprintf "%s%b", 0 x 7, shift; $binary =~ s/(.{7})$//; @vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) ); while ( 0 + $binary ) { $binary =~ s/(.{7})$//; unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 ); } return @vlq; }   sub vlq_decode { my $num; $num .= sprintf "%07b", hex(shift @_) & 0x7f while @_; return oct '0b' . $num; }  
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#D
D
import std.stdio, std.algorithm;   void printAll(TyArgs...)(TyArgs args) { foreach (el; args) el.writeln; }   // Typesafe variadic function for dynamic array void showSum1(int[] items...) { items.sum.writeln; }   // Typesafe variadic function for fixed size array void showSum2(int[4] items...) { items[].sum.writeln; }   void main() { printAll(4, 5.6, "Rosetta", "Code", "is", "awesome"); writeln; showSum1(1, 3, 50); showSum2(1, 3, 50, 10); }
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Delphi
Delphi
func printAll(args...) { for i in args { print(i) } }   printAll("test", "rosetta code", 123, 5.6)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Factor
Factor
USING: layouts memory prettyprint ;   ! Show size in bytes { 1 2 3 } size .  ! 48 1231298302914891021239102 size .  ! 48   ! Doesn't work on fixnums and other immediate objects 10 size .  ! 0   ! Show number of bits in a fixnum fixnum-bits .  ! 60
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Forth
Forth
: .CELLSIZE ( -- ) CR 1 CELLS . ." Bytes" ; VARIABLE X ( creates a variable 1 cell wide)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Fortran
Fortran
INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2) INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4) INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8) INTEGER, PARAMETER :: i64 = SELECTED_INT_KIND(16) INTEGER(i8) :: onebyte = 0 INTEGER(i16) :: twobytes = 0 INTEGER(i32) :: fourbytes = 0 INTEGER(i64) :: eightbytes = 0   WRITE (*,*) BIT_SIZE(onebyte), DIGITS(onebyte) ! prints 8 and 7 WRITE (*,*) BIT_SIZE(twobytes), DIGITS(twobytes) ! prints 16 and 15 WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31 WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63 WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#jq
jq
def polar(r; angle): [ r*(angle|cos), r*(angle|sin) ];   # If your jq allows multi-arity functions, you may wish to uncomment the following line: # def polar(r): [r, 0];   def polar2vector: polar(.[0]; .[1]);   def vector(x; y): if (x|type) == "number" and (y|type) == "number" then [x,y] else error("TypeError") end;   # Input: an array of same-dimensional vectors of any dimension to be added def sum: def sum2: .[0] as $a | .[1] as $b | reduce range(0;$a|length) as $i ($a; .[$i] += $b[$i]); if length <= 1 then . else reduce .[1:][] as $v (.[0] ; [., $v]|sum2) end;   def multiply(scalar): [ .[] * scalar ];   def negate: multiply(-1);   def minus(v): [., (v|negate)] | sum;   def divide(scalar): if scalar == 0 then error("division of a vector by 0 is not supported") else [ .[] / scalar ] end;   def r: (.[0] | .*.) + (.[1] | .*.) | sqrt;   def atan2: def pi: 1 | atan * 4; def sign: if . < 0 then -1 elif . > 0 then 1 else 0 end; .[0] as $x | .[1] as $y | if $x == 0 then $y | sign * pi / 2 else ($y / $x) | if $x > 0 then atan elif . > 0 then atan - pi else atan + pi end end;   def angle: atan2;   def topolar: [r, angle];
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Julia
Julia
module SpatialVectors   export SpatialVector   struct SpatialVector{N, T} coord::NTuple{N, T} end   SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} = SpatialVector{N, T}(e .- s) function SpatialVector(∠::T, val::T) where T θ = atan(∠) x = val * cos(θ) y = val * sin(θ) return SpatialVector((x, y)) end   angularcoef(v::SpatialVector{2, T}) where T = v.coord[2] / v.coord[1] Base.norm(v::SpatialVector) = sqrt(sum(x -> x^2, v.coord))   function Base.show(io::IO, v::SpatialVector{2, T}) where T ∠ = angularcoef(v) val = norm(v) println(io, """2-dim spatial vector - Angular coef ∠: $(∠) (θ = $(rad2deg(atan(∠)))°) - Magnitude: $(val) - X coord: $(v.coord[1]) - Y coord: $(v.coord[2])""") end   Base.:-(v::SpatialVector) = SpatialVector(.- v.coord)   for op in (:+, :-) @eval begin Base.$op(a::SpatialVector{N, T}, b::SpatialVector{N, U}) where {N, T, U} = SpatialVector{N, promote_type(T, U)}(broadcast($op, a.coord, b.coord)) end end   for op in (:*, :/) @eval begin Base.$op(n::T, v::SpatialVector{N, U}) where {N, T, U} = SpatialVector{N, promote_type(T, U)}(broadcast($op, n, v.coord)) Base.$op(v::SpatialVector, n::Number) = $op(n, v) end end   end # module Vectors
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#Tcl
Tcl
package require Tcl 8.5 package require math::statistics   proc isUniform {distribution {significance 0.05}} { set count [tcl::mathop::+ {*}[dict values $distribution]] set expected [expr {double($count) / [dict size $distribution]}] set X2 0.0 foreach value [dict values $distribution] { set X2 [expr {$X2 + ($value - $expected)**2 / $expected}] } set degreesOfFreedom [expr {[dict size $distribution] - 1}] set likelihoodOfRandom [::math::statistics::incompleteGamma \ [expr {$degreesOfFreedom / 2.0}] [expr {$X2 / 2.0}]] expr {$likelihoodOfRandom > $significance} }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Lua
Lua
function Encrypt( _msg, _key ) local msg = { _msg:upper():byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local enc = {}   local j, k = 1, 1 for i = 1, #msg do if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')   k = k + 1 if j == #key then j = 1 else j = j + 1 end end end   return string.char( unpack(enc) ) end   function Decrypt( _msg, _key ) local msg = { _msg:byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local dec = {}   local j = 1 for i = 1, #msg do dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')   if j == #key then j = 1 else j = j + 1 end end   return string.char( unpack(dec) ) end     original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" key = "VIGENERECIPHER";   encrypted = Encrypt( original, key ) decrypted = Decrypt( encrypted, key )   print( encrypted ) print( decrypted )
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   3D   images   etc. Task Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#Ruby
Ruby
  root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]  
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   3D   images   etc. Task Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#Rust
Rust
  extern crate rustc_serialize; extern crate term_painter;   use rustc_serialize::json; use std::fmt::{Debug, Display, Formatter, Result}; use term_painter::ToStyle; use term_painter::Color::*;   type NodePtr = Option<usize>;   #[derive(Debug, PartialEq, Clone, Copy)] enum Side { Left, Right, Up, }   #[derive(Debug, PartialEq, Clone, Copy)] enum DisplayElement { TrunkSpace, SpaceLeft, SpaceRight, SpaceSpace, Root, }   impl DisplayElement { fn string(&self) -> String { match *self { DisplayElement::TrunkSpace => " │ ".to_string(), DisplayElement::SpaceRight => " ┌───".to_string(), DisplayElement::SpaceLeft => " └───".to_string(), DisplayElement::SpaceSpace => " ".to_string(), DisplayElement::Root => "├──".to_string(), } } }   #[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)] struct Node<K, V> { key: K, value: V, left: NodePtr, right: NodePtr, up: NodePtr, }   impl<K: Ord + Copy, V: Copy> Node<K, V> { pub fn get_ptr(&self, side: Side) -> NodePtr { match side { Side::Up => self.up, Side::Left => self.left, _ => self.right, } } }   #[derive(Debug, RustcDecodable, RustcEncodable)] struct Tree<K, V> { root: NodePtr, store: Vec<Node<K, V>>, }   impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> { pub fn get_node(&self, np: NodePtr) -> Node<K, V> { assert!(np.is_some()); self.store[np.unwrap()] }   pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr { assert!(np.is_some()); self.store[np.unwrap()].get_ptr(side) }   // Prints the tree with root p. The idea is to do an in-order traversal // (reverse in-order in this case, where right is on top), and print nodes as they // are visited, one per line. Each invocation of display() gets its own copy // of the display element vector e, which is grown with either whitespace or // a trunk element, then modified in its last and possibly second-to-last // characters in context. fn display(&self, p: NodePtr, side: Side, e: &Vec<DisplayElement>, f: &mut Formatter) { if p.is_none() { return; }   let mut elems = e.clone(); let node = self.get_node(p); let mut tail = DisplayElement::SpaceSpace; if node.up != self.root { // If the direction is switching, I need the trunk element to appear in the lines // printed before that node is visited. if side == Side::Left && node.right.is_some() { elems.push(DisplayElement::TrunkSpace); } else { elems.push(DisplayElement::SpaceSpace); } } let hindex = elems.len() - 1; self.display(node.right, Side::Right, &elems, f);   if p == self.root { elems[hindex] = DisplayElement::Root; tail = DisplayElement::TrunkSpace; } else if side == Side::Right { // Right subtree finished elems[hindex] = DisplayElement::SpaceRight; // Prepare trunk element in case there is a left subtree tail = DisplayElement::TrunkSpace; } else if side == Side::Left { elems[hindex] = DisplayElement::SpaceLeft; let parent = self.get_node(node.up); if parent.up.is_some() && self.get_pointer(parent.up, Side::Right) == node.up { // Direction switched, need trunk element starting with this node/line elems[hindex - 1] = DisplayElement::TrunkSpace; } }   // Visit node => print accumulated elements. Each node gets a line and each line gets a // node. for e in elems.clone() { let _ = write!(f, "{}", e.string()); } let _ = write!(f, "{key:>width$} ", key = Green.bold().paint(node.key), width = 2); let _ = write!(f, "{value:>width$}\n", value = Blue.bold().paint(format!("{:.*}", 2, node.value)), width = 4);   // Overwrite last element before continuing traversal elems[hindex] = tail;   self.display(node.left, Side::Left, &elems, f); } }   impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Display for Tree<K, V> { fn fmt(&self, f: &mut Formatter) -> Result { if self.root.is_none() { write!(f, "[empty]") } else { let mut v: Vec<DisplayElement> = Vec::new(); self.display(self.root, Side::Up, &mut v, f); Ok(()) } } }   /// Decodes and prints a previously generated tree. fn main() { let encoded = r#"{"root":0,"store":[{"key":0,"value":0.45,"left":1,"right":3, "up":null},{"key":-8,"value":-0.94,"left":7,"right":2,"up":0}, {"key":-1, "value":0.15,"left":8,"right":null,"up":1},{"key":7, "value":-0.29,"left":4, "right":9,"up":0},{"key":5,"value":0.80,"left":5,"right":null,"up":3}, {"key":4,"value":-0.85,"left":6,"right":null,"up":4},{"key":3,"value":-0.46, "left":null,"right":null,"up":5},{"key":-10,"value":-0.85,"left":null, "right":13,"up":1},{"key":-6,"value":-0.42,"left":null,"right":10,"up":2}, {"key":9,"value":0.63,"left":12,"right":null,"up":3},{"key":-3,"value":-0.83, "left":null,"right":11,"up":8},{"key":-2,"value":0.75,"left":null,"right":null, "up":10},{"key":8,"value":-0.48,"left":null,"right":null,"up":9},{"key":-9, "value":0.53,"left":null,"right":null,"up":7}]}"#; let tree: Tree<i32, f32> = json::decode(&encoded).unwrap(); println!("{}", tree); }  
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Prolog_2
Prolog
% submitted by Aykayayciti (Earl Lamont Montgomery) % altered from fsaenzperez April 2019 % (swi-prolog.discourse-group) test_run :- proc_dir('C:\\vvvv\\vvvv_beta_39_x64').     proc_dir(Directory) :- format('Directory: ~w~n',[Directory]), directory_files(Directory,Files),!, %cut inserted proc_files(Directory,Files).   proc_files(Directory, [File|Files]) :- proc_file(Directory, File),!, %cut inserted proc_files(Directory, Files). proc_files(_Directory, []).   proc_file(Directory, File) :- ( File = '.', directory_file_path(Directory, File, Path), exists_directory(Path),!,%cut inserted format('Directory: ~w~n',[File]) ; File = '..', directory_file_path(Directory, File, Path), exists_directory(Path),!,%cut inserted format('Directory: ~w~n',[File]) ; directory_file_path(Directory, File, Path), exists_directory(Path),!,%cut inserted proc_dir(Path) ; directory_file_path(Directory, File, Path), exists_file(Path),!,%cut inserted format('File: ~w~n',[File]) ; format('Unknown: ~w~n',[File]) ).
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██ 6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██ 5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████ 4 ██ ██ ████████ 4 ██≈≈██≈≈████████ 3 ██████ ████████ 3 ██████≈≈████████ 2 ████████████████ ██ 2 ████████████████≈≈██ 1 ████████████████████ 1 ████████████████████ In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele Water collected between towers on Stack Overflow, from which the example above is taken) An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
#Rust
Rust
  use std::cmp::min;   fn getfill(pattern: &[usize]) -> usize { let mut total = 0; for (idx, val) in pattern.iter().enumerate() { let l_peak = pattern[..idx].iter().max(); let r_peak = pattern[idx + 1..].iter().max(); if l_peak.is_some() && r_peak.is_some() { let peak = min(l_peak.unwrap(), r_peak.unwrap()); if peak > val { total += peak - val; } } } total }   fn main() { let patterns = vec![ vec![1, 5, 3, 7, 2], vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2], vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], vec![5, 5, 5, 5], vec![5, 6, 7, 8], vec![8, 7, 7, 6], vec![6, 7, 10, 7, 6], ];   for pattern in patterns { println!("pattern: {:?}, fill: {}", &pattern, getfill(&pattern)); } }  
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#AWK
AWK
#!/usr/bin/awk -f BEGIN { a[1] = 3; a[2]= 4; a[3] = 5; b[1] = 4; b[2]= 3; b[3] = 5; c[1] = -5; c[2]= -12; c[3] = -13;   print "a = ",printVec(a); print "b = ",printVec(b); print "c = ",printVec(c); print "a.b = ",dot(a,b); ## upper case variables are used as temporary or intermediate results cross(a,b,D);print "a.b = ",printVec(D); cross(b,c,D);print "a.(b x c) = ",dot(a,D); cross(b,c,D);cross(a,D,E); print "a x (b x c) = ",printVec(E); }   function dot(A,B) { return A[1]*B[1]+A[2]*B[2]+A[3]*B[3]; }   function cross(A,B,C) { C[1] = A[2]*B[3]-A[3]*B[2]; C[2] = A[3]*B[1]-A[1]*B[3]; C[3] = A[1]*B[2]-A[2]*B[1]; }   function printVec(C) { return "[ "C[1]" "C[2]" "C[3]" ]"; }
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#360_Assembly
360 Assembly
* Validate ISIN 08/03/2019 VALISIN CSECT USING VALISIN,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R7,1 j=1 DO WHILE=(C,R7,LE,=A(NN)) do j=1 to hbound(tt) LR R1,R7 j SLA R1,4 ~ LA R4,TT-16(R1) @tt(j) MVC CC,0(R4) cc=tt(j) MVC C,=CL28' ' c=' ' MVC R,=CL28' ' r=' ' MVI ERR,X'00' err=false MVC LCC,=F'0' lcc=0 LA R1,L'CC i=length(cc) LENTRIA LA R5,CC-1 @cc AR R5,R1 +i CLI 0(R5),C' ' if cc[i]=' ' BE LENTRIB then iterate loop ST R1,LCC lcc=lentrim(cc) B LENTRIC leave loop LENTRIB BCT R1,LENTRIA i--; if i<>0 then loop LENTRIC L R4,LCC lcc IF CH,R4,EQ,=H'12' THEN if lcc=12 then MVC LC,=F'0' lc=0 MVC WW,=CL28' ' ww='' LA R10,WW @ww LA R6,1 i=1 DO WHILE=(C,R6,LE,LCC) do i=1 to lcc LA R4,CC-1 @cc AR R4,R6 +i MVC CI(1),0(R4) ci=substr(cc,i,1) LA R2,BASE36 @base36 LA R3,L'BASE36 length(base36) BAL R14,INDEX r0=index(base36,ci) IF LTR,R0,NZ,R0 THEN if p<>0 then LR R1,R0 ip BCTR R1,0 -1 XDECO R1,XDEC str(ip-1) MVC 0(2,R10),XDEC+10 ww=ww||str(p-1) ELSE , else MVI ERR,X'FF' err=true ENDIF , endif LA R10,2(R10) @ww+=2 LA R6,1(R6) i++ ENDDO , enddo i MVC C,=CL28' ' c='' LA R8,WW @ww LA R9,C @c LA R10,0 length(c) LA R6,1 i=1 DO WHILE=(C,R6,LE,=A(L'WW)) do i=1 to length(ww) IF CLI,0(R8),NE,C' ' THEN if ww[i]<>' ' then MVC 0(1,R9),0(R8) c=ww[i] LA R9,1(R9) @c++ LA R10,1(R10) length(c)++ ENDIF , endif LA R8,1(R8) @ww++ LA R6,1(R6) i++ ENDDO , enddo i ST R10,LC lc=length(c) LA R6,1 i=1 DO WHILE=(CH,R6,LE,=H'2') do i=1 to 2 LA R4,CC-1 @cc AR R4,R6 +i MVC CI(1),0(R4) ci=substr(cc,i,1) LA R2,ALPHA @alpha LA R3,L'ALPHA length(alpha) BAL R14,INDEX r0=index(alpha,ci) IF LTR,R0,Z,R0 THEN if index(alpha,ci)=0 then MVI ERR,X'FF' err=true ENDIF , endif LA R6,1(R6) i++ ENDDO , enddo i SR R8,R8 i1=0 SR R9,R9 i2=0 IF CLI,ERR,EQ,X'00' THEN if not err then SR R0,R0 0 L R6,LC i=lc MVC R,=CL28' ' r='' LA R10,C @c LA R11,R-1 @r A R11,LC @r=@r+length(strip((c)) DO WHILE=(CH,R6,GE,=H'1') do i=lc to 1 step -1 MVC 0(1,R11),0(R10) r[k]=c[i] BCTR R11,0 @r-- LA R10,1(R10) @c++ BCTR R6,0 i-- ENDDO , enddo i LA R6,1 i=1 DO WHILE=(C,R6,LE,LC) do i=1 to lc step 2 LA R4,R-1 @r AR R4,R6 +i MVC CI(1),0(R4) ci=substr(r,i,1) MVC XDEC,=CL12' ' ~ MVC XDEC(L'CI),CI ci XDECI R2,XDEC int(ci) AR R8,R2 i1=i1+int(ci) LA R6,2(R6) i+=2 ENDDO , enddo i LA R6,2 i=2 DO WHILE=(C,R6,LE,LC) do i=2 to lc step 2 LA R4,R-1 @r AR R4,R6 +i MVC CI(1),0(R4) ci=substr(r,i,1) MVC XDEC,=CL12' ' ~ MVC XDEC(L'CI),CI ci XDECI R10,XDEC int(ci) SLA R10,1 ii=int(ci)*2 IF CH,R10,GE,=H'10' THEN if ii>=10 then SH R10,=H'9' ii=ii-9 ENDIF , endif AR R9,R10 i2=i2+ii LA R6,2(R6) i++ ENDDO , enddo i LR R2,R8 i1 AR R2,R9 +i2 XDECO R2,XDEC s=str(i1+i2) IF CLI,XDEC+11,EQ,C'0' THEN if substr(s,length(s),1)='0' then MVC MSG,=CL6'OK' msg='ok' ELSE , else MVC MSG,=CL6'?err1' msg='?1' ENDIF , endif ELSE , else MVC MSG,=CL6'?err2' msg='?2' ENDIF , endif ELSE , else MVC MSG,=CL6'?err3' msg='?3' ENDIF , endif XDECO R7,XDEC edit j MVC PG(2),XDEC+10 j MVC PG+3(16),CC cc MVC PG+20(6),MSG msg XPRNT PG,L'PG print buffer LA R7,1(R7) j++ ENDDO , enddo j L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav MVCX MVC 0(0,R4),0(R5) pattern svc INDEX SR R0,R0 index(r2,ci) r3=len LA R1,1 k=1 SINDEXA CR R1,R3 do k=1 to length(ca) BH SINDEXC ~ CLC 0(1,R2),CI if ca[k]=ci BNE SINDEXB then iterate loop LR R0,R1 ii=k B SINDEXC exit loop SINDEXB LA R2,1(R2) @ca++ LA R1,1(R1) k++ B SINDEXA enddo SINDEXC BR R14 end index NN EQU (BASE36-TT)/16 number of items TT DC CL16'US0378331005',CL16'US0373831005' DC CL16'U50378331005',CL16'US03378331005' DC CL16'AU0000XVGZA3',CL16'AU0000VXGZA3' DC CL16'FR0000988040' BASE36 DC CL36'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ALPHA DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ERR DS X error LCC DS F length of cc LC DS F length of c CI DS CL1 CC DS CL16 current element of tt C DS CL28 R DS CL28 WW DS CL28 MSG DS CL6 message PG DC CL80' ' buffer XDEC DS CL12 temp for xdeco and xdeci REGEQU END VALISIN
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Ada
Ada
procedure ISIN is -- Luhn_Test copied from other Task function Luhn_Test (Number: String) return Boolean is Sum  : Natural := 0; Odd  : Boolean := True; Digit: Natural range 0 .. 9; begin for p in reverse Number'Range loop Digit := Integer'Value (Number (p..p)); if Odd then Sum := Sum + Digit; else Sum := Sum + (Digit*2 mod 10) + (Digit / 5); end if; Odd := not Odd; end loop; return (Sum mod 10) = 0; end Luhn_Test;   subtype Decimal is Character range '0' .. '9'; subtype Letter is Character range 'A' .. 'Z'; subtype ISIN_Type is String(1..12);   -- converts a string of decimals and letters into a string of decimals function To_Digits(S: String) return String is -- Character'Pos('A')-Offset=10, Character'Pos('B')-Offset=11, ... Offset: constant Integer := Character'Pos('A')-10;   Invalid_Character: exception; begin if S = "" then return ""; elsif S(S'First) = ' ' then -- skip blanks return To_Digits(S(S'First+1 .. S'Last)); elsif S(S'First) in Decimal then return S(S'First) & To_Digits(S(S'First+1 .. S'Last)); elsif S(S'First) in Letter then return To_Digits(Integer'Image(Character'Pos(S(S'First))-Offset)) & To_Digits(S(S'First+1 .. S'Last)); else raise Invalid_Character; end if; end To_Digits;   function Is_Valid_ISIN(S: ISIN_Type) return Boolean is Number : String := To_Digits(S); begin return S(S'First) in Letter and S(S'First+1) in Letter and S(S'Last) in Decimal and Luhn_Test(Number); end Is_Valid_ISIN;   Test_Cases : constant Array(1..6) of ISIN_Type := ("US0378331005", "US0373831005", "U50378331005", -- excluded by type with fixed length -- "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"); begin for I in Test_Cases'Range loop Ada.Text_IO.Put_Line(Test_Cases(I) & ":" & Boolean'Image(Is_Valid_ISIN(Test_Cases(I)))); end loop; -- using wrong length will result in an exception: Ada.Text_IO.Put("US03378331005:"); Ada.Text_IO.Put_Line(Boolean'Image(Is_Valid_Isin("US03378331005"))); exception when others => Ada.Text_IO.Put_Line("Exception occured"); end ISIN;
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#jq
jq
[1,2,2,3,4,4,5] | . as $array | range(1;length) | select( $array[.] == $array[.-1])  
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Julia
Julia
  s = [1, 2, 2, 3, 4, 4, 5]   for i in eachindex(s) curr = s[i] i > 1 && curr == prev && println(i) prev = curr end  
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Perl
Perl
@s = <1 2 2 3 4 4 5>; for ($i = 0; $i < 7; $i++) { $curr = $s[$i]; if ($i > 1 and $curr == $prev) { print "$i\n" } $prev = $curr; }
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Phix
Phix
with javascript_semantics sequence s = {1,2,2,3,4,4,5} for i=1 to length(s) do integer curr = s[i], prev if i>1 and curr=prev then ?i end if prev = curr end for
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#ActionScript
ActionScript
  package {   import flash.display.Sprite; import flash.events.Event;   public class VanDerCorput extends Sprite {   public function VanDerCorput():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); }   private function init(e:Event = null):void {   removeEventListener(Event.ADDED_TO_STAGE, init);   var base2:Vector.<Number> = new Vector.<Number>(10, true); var base3:Vector.<Number> = new Vector.<Number>(10, true); var base4:Vector.<Number> = new Vector.<Number>(10, true); var base5:Vector.<Number> = new Vector.<Number>(10, true); var base6:Vector.<Number> = new Vector.<Number>(10, true); var base7:Vector.<Number> = new Vector.<Number>(10, true); var base8:Vector.<Number> = new Vector.<Number>(10, true);   var i:uint;   for ( i = 0; i < 10; i++ ) { base2[i] = Math.round( _getTerm(i, 2) * 1000000 ) / 1000000; base3[i] = Math.round( _getTerm(i, 3) * 1000000 ) / 1000000; base4[i] = Math.round( _getTerm(i, 4) * 1000000 ) / 1000000; base5[i] = Math.round( _getTerm(i, 5) * 1000000 ) / 1000000; base6[i] = Math.round( _getTerm(i, 6) * 1000000 ) / 1000000; base7[i] = Math.round( _getTerm(i, 7) * 1000000 ) / 1000000; base8[i] = Math.round( _getTerm(i, 8) * 1000000 ) / 1000000; }   trace("Base 2: " + base2.join(', ')); trace("Base 3: " + base3.join(', ')); trace("Base 4: " + base4.join(', ')); trace("Base 5: " + base5.join(', ')); trace("Base 6: " + base6.join(', ')); trace("Base 7: " + base7.join(', ')); trace("Base 8: " + base8.join(', '));   }   private function _getTerm(n:uint, base:uint = 2):Number {   var r:Number = 0, p:uint, digit:uint; var baseLog:Number = Math.log(base);   while ( n > 0 ) { p = Math.pow( base, uint(Math.log(n) / baseLog) );   digit = n / p; n %= p; r += digit / (p * base); }   return r;   }   }   }  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program variable64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" /*********************************/ /* Initialized data */ /*********************************/ .data szString: .asciz "String définition" sArea1: .fill 11, 1, ' ' // 11 spaces // or sArea2: .space 11,' ' // 11 spaces   cCharac: .byte '\n' // character cByte1: .byte 0b10101 // 1 byte binary value   hHalfWord1: .hword 0xFF // 2 bytes value hexa .align 4 iInteger1: .int 123456 // 4 bytes value decimal iInteger3: .short 0500 // 4 bytes value octal iInteger5: .int 0x4000 // 4 bytes value hexa   iInteger7: .word 0x4000 // 4 bytes value hexa iInteger6: .int 04000 // 4 bytes value octal   TabInteger4: .int 5,4,3,2 // Area of 4 integers = 4 * 4 = 16 bytes   dDoubleInt1: .quad 0xFFFFFFFFFFFFFFFF // 8 bytes value hexa   dfFLOAT1: .double 0f-31415926535897932384626433832795028841971.693993751E-40 // Float 8 bytes sfFLOAT2: .float 0f-31415926535897932384626433832795028841971.693993751E-40 // Float 4 bytes (or use .single)   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sBuffer: .skip 500 // 500 bytes values zero iInteger2: .skip 4 // 4 bytes value zero dDoubleint2: .skip 8 // 8 bytes value zero /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdriInteger2 // load variable address mov x1,#100 str x1,[x0] // init variable iInteger2   100: // standard end of the program mov x0, 0 // return code mov x8, EXIT // request to exit program svc 0 // perform the system call   qAdriInteger2: .quad iInteger2 // variable address iInteger2    
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#ALGOL_68
ALGOL 68
BEGIN # find elements of the Van Eck Sequence - first term is 0, following # # terms are 0 if the previous was the first appearance of the element # # or how far back in the sequence the last element appeared # # returns the first n elements of the Van Eck sequence # OP VANECK = ( INT n )[]INT: BEGIN [ 1 : IF n < 0 THEN 0 ELSE n FI ]INT result; FOR i TO n DO result[ i ] := 0 OD; [ 0 : UPB result ]INT pos; FOR i FROM 0 TO n DO pos[ i ] := 0 OD; FOR i FROM 2 TO n DO INT j = i - 1; INT prev = result[ j ]; IF pos[ prev ] /= 0 THEN # not a new element # result[ i ] := j - pos[ prev ] FI; pos[ prev ] := j OD; result END # VANECK # ; # construct the first 1000 terms of the sequence # []INT seq = VANECK 1000; # show the first and last 10 elements # FOR i TO 10 DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD; print( ( newline ) ); FOR i FROM UPB seq - 9 TO UPB seq DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD; print( ( newline ) ) END
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#C.23
C#
using System;   namespace RosettaVampireNumber { class Program { static void Main(string[] args) { int i, j, n; ulong x; var f = new ulong[16]; var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 }; ulong[] tens = new ulong[20]; tens[0] = 1; for (i = 1; i < 20; i++) tens[i] = tens[i - 1] * 10;   for (x = 1, n = 0; n < 25; x++) { if ((j = fangs(x, f, tens)) == 0) continue; Console.Write(++n + ": "); show_fangs(x, f, j); }   Console.WriteLine(); for (i = 0; bigs[i] > 0 ; i++) { if ((j = fangs(bigs[i], f, tens)) > 0) show_fangs(bigs[i], f, j); else Console.WriteLine(bigs[i] + " is not vampiric."); } Console.ReadLine(); }   private static void show_fangs(ulong x, ulong[] f, int cnt) { Console.Write(x); int i; for (i = 0; i < cnt; i++) Console.Write(" = " + f[i] + " * " + (x / f[i])); Console.WriteLine(); }   private static int fangs(ulong x, ulong[] f, ulong[] tens) { int n = 0; int nd = ndigits(x); if ((nd & 1) > 0) return 0; nd /= 2;   ulong lo, hi; lo = Math.Max(tens[nd - 1], (x + tens[nd] - 2) / (tens[nd] - 1)); hi = Math.Min(x / lo, (ulong) Math.Sqrt(x));   ulong a, b, t = dtally(x); for (a = lo; a <= hi; a++) { b = x / a; if (a * b == x && ((a % 10) > 0 || (b % 10) > 0) && t == dtally(a) + dtally(b)) f[n++] = a; }   return n; }   private static ulong dtally(ulong x) { ulong t = 0; while (x > 0) { t += 1UL << (int)((x % 10) * 6); x /= 10; }   return t; }   private static int ndigits(ulong x) { int n = 0; while (x > 0) { n++; x /= 10; } return n; } } }
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#Phix
Phix
function vlq_encode(sequence s) sequence res = {} for i=length(s) to 1 by -1 do integer n = s[i], msb = 0 if n<0 then crash("unsigned integers only!") end if while 1 do res = prepend(res,msb+and_bits(n,#7F)) n = floor(n/#80) if n=0 then exit end if msb = #80 end while end for return res end function function vlq_decode(sequence s) sequence res = {} for i=1 to length(s) do integer si = s[i], n = n*#80+and_bits(byte,#7F) if not and_bits(si,#80) then res = append(res,n) n = 0 end if end for return res end function function svlg(sequence s) string res = "" for i=1 to length(s) do res &= sprintf("#%02x:",{s[i]}) end for return res[1..$-1] end function constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 } sequence s = vlq_encode(testNumbers), decoded = vlq_decode(s) printf(1,"%s -> %s -> %s\n",{svlg(testNumbers),svlg(s),svlg(decoded)}) if decoded!=testNumbers then crash("something wrong") end if
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Dyalect
Dyalect
func printAll(args...) { for i in args { print(i) } }   printAll("test", "rosetta code", 123, 5.6)
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#D.C3.A9j.C3.A0_Vu
Déjà Vu
show-all(: while /= ) dup:  !. drop   show-all( :foo "Hello" 42 [ true ] )
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Free_Pascal
Free Pascal
' FB 1.05.0 Win64   Dim i As Integer Dim l As Long Dim s As Short Dim b As Byte Print "An integer occupies "; SizeOf(i); " bytes" Print "A long occupies "; SizeOf(l); " bytes" Print "A short occupies "; SizeOf(s); " bytes" Print "A byte occupies "; SizeOf(b); " byte"   ' or use type directly rather than a variable   Print "A boolean occupies "; SizeOf(Boolean); " byte" Print "A single occupies "; SizeOf(Single); " bytes" Print "A double occupies "; SizeOf(Double); " bytes"   Print Print "Press any key to quit" Sleep  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim i As Integer Dim l As Long Dim s As Short Dim b As Byte Print "An integer occupies "; SizeOf(i); " bytes" Print "A long occupies "; SizeOf(l); " bytes" Print "A short occupies "; SizeOf(s); " bytes" Print "A byte occupies "; SizeOf(b); " byte"   ' or use type directly rather than a variable   Print "A boolean occupies "; SizeOf(Boolean); " byte" Print "A single occupies "; SizeOf(Single); " bytes" Print "A double occupies "; SizeOf(Double); " bytes"   Print Print "Press any key to quit" Sleep  
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Kotlin
Kotlin
// version 1.1.2   class Vector2D(val x: Double, val y: Double) { operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y)   operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y)   operator fun times(s: Double) = Vector2D(s * x, s * y)   operator fun div(s: Double) = Vector2D(x / s, y / s)   override fun toString() = "($x, $y)" }   operator fun Double.times(v: Vector2D) = v * this   fun main(args: Array<String>) { val v1 = Vector2D(5.0, 7.0) val v2 = Vector2D(2.0, 3.0) println("v1 = $v1") println("v2 = $v2") println() println("v1 + v2 = ${v1 + v2}") println("v1 - v2 = ${v1 - v2}") println("v1 * 11 = ${v1 * 11.0}") println("11 * v2 = ${11.0 * v2}") println("v1 / 2 = ${v1 / 2.0}") }
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#VBA
VBA
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean 'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level. Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) 'This is exactly the number of different categories minus 1 Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print " Chi-squared test for given frequencies" Debug.Print "X-squared ="; ChiSquared; ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Public Sub test() Dim O() As Variant O = [{199809,200665,199607,200270,199649}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" O = [{522573,244456,139979,71531,21461}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" End Sub
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#Vlang
Vlang
import math   type Ifctn = fn(f64) f64   fn simpson38(f Ifctn, a f64, b f64, n int) f64 { h := (b - a) / f64(n) h1 := h / 3 mut sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*f64(j)) } else { sum += 3 * f(a+h1*f64(j)) } } return h * sum / 8 }   fn gamma_inc_q(a f64, x f64) f64 { aa1 := a - 1 f := Ifctn(fn[aa1](t f64) f64 { return math.pow(t, aa1) * math.exp(-t) }) mut y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.gamma(a))) }   fn chi2ud(ds []int) f64 { mut sum, mut expected := 0.0,0.0 for d in ds { expected += f64(d) } expected /= f64(ds.len) for d in ds { x := f64(d) - expected sum += x * x } return sum / expected }   fn chi2p(dof int, distance f64) f64 { return gamma_inc_q(.5*f64(dof), .5*distance) }   const sig_level = .05   fn main() { for dset in [ [199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461], ] { utest(dset) } }   fn utest(dset []int) { println("Uniform distribution test") mut sum := 0 for c in dset { sum += c } println(" dataset: $dset") println(" samples: $sum") println(" categories: $dset.len")   dof := dset.len - 1 println(" degrees of freedom: $dof")   dist := chi2ud(dset) println(" chi square test statistic: $dist")   p := chi2p(dof, dist) println(" p-value of test statistic: $p")   sig := p < sig_level println(" significant at ${sig_level*100:2.0f}% level? $sig") println(" uniform? ${!sig}\n") }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
encode[text_String, key_String] := Module[{textCode, keyCode}, textCode = Cases[ToCharacterCode[ ToUpperCase@ text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; keyCode = Cases[ToCharacterCode[ ToUpperCase@ key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; keyCode = If[Length[textCode] < Length[keyCode], keyCode[[;; Length@textCode]], PadRight[keyCode, Length@textCode, keyCode]]; FromCharacterCode[Mod[textCode + keyCode, 26] + 65]]   decode[text_String, key_String] := Module[{textCode, keyCode}, textCode = Cases[ToCharacterCode[ ToUpperCase@ text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; keyCode = Cases[ToCharacterCode[ ToUpperCase@ key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; keyCode = If[Length[textCode] < Length[keyCode], keyCode[[;; Length@textCode]], PadRight[keyCode, Length@textCode, keyCode]]; FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   3D   images   etc. Task Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#Sidef
Sidef
func visualize_tree(tree, label, children, indent = '', mids = ['├─', '│ '], ends = ['└─', ' '], ) { func visit(node, pre) { gather { take(pre[0] + label(node)) var chldn = children(node) var end = chldn.end chldn.each_kv { |i, child| if (i == end) { take(visit(child, [pre[1]] ~X+ ends)) } else { take(visit(child, [pre[1]] ~X+ mids)) } } } } visit(tree, [indent] * 2) }   var tree = 'root':['a':['a1':['a11':[]]],'b':['b1':['b11':[]],'b2':[],'b3':[]]] say visualize_tree(tree, { .first }, { .second }).flatten.join("\n")
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Python
Python
  from pathlib import Path   for path in Path('.').rglob('*.*'): print(path)  
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#R
R
dir("/bar/foo", "mp3",recursive=T)
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██ 6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██ 5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████ 4 ██ ██ ████████ 4 ██≈≈██≈≈████████ 3 ██████ ████████ 3 ██████≈≈████████ 2 ████████████████ ██ 2 ████████████████≈≈██ 1 ████████████████████ 1 ████████████████████ In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele Water collected between towers on Stack Overflow, from which the example above is taken) An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
#Scala
Scala
import scala.collection.parallel.CollectionConverters.VectorIsParallelizable   // Program to find maximum amount of water // that can be trapped within given set of bars. object TrappedWater extends App { private val barLines = List( Vector(1, 5, 3, 7, 2), Vector(5, 3, 7, 2, 6, 4, 5, 9, 1, 2), Vector(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1), Vector(5, 5, 5, 5), Vector(5, 6, 7, 8), Vector(8, 7, 7, 6), Vector(6, 7, 10, 7, 6)).zipWithIndex   // Method for maximum amount of water private def sqBoxWater(barHeights: Vector[Int]): Int = { def maxOfLeft = barHeights.par.scanLeft(0)(math.max).tail def maxOfRight = barHeights.par.scanRight(0)(math.max).init   def waterlevels = maxOfLeft.zip(maxOfRight) .map { case (maxL, maxR) => math.min(maxL, maxR) }   waterlevels.zip(barHeights).map { case (level, towerHeight) => level - towerHeight }.sum }   barLines.foreach(barSet => println(s"Block ${barSet._2 + 1} could hold max. ${sqBoxWater(barSet._1)} units."))   }
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#BASIC256
BASIC256
  a={3,4,5}:b={4,3,5}:c={-5,-12,-13}   print "A.B = "+dot_product(ref(a),ref(b)) call cross_product(ref(a),ref(b),ref(y)) Print "AxB = ("+y[0]+","+y[1]+","+y[2]+")" print "A.(BxC) = "+s_tri(ref(a),ref(b),ref(c)) call v_tri(ref(a),ref(b),ref(c),ref(x),ref(y)) Print "A x (BxC) = ("+y[0]+","+y[1]+","+y[2]+")"   function dot_product(ref(x1),ref(x2)) dot_product= 0 for t = 0 to 2 dot_product += x1[t]*x2[t] next t end function   subroutine cross_product(ref(x1),ref(x2),ref(y1)) y1={0,0,0} y1[0]=x1[1]*x2[2]-x1[2]*x2[1] y1[1]=x1[2]*x2[0]-x1[0]*x2[2] y1[2]=x1[0]*x2[1]-x1[1]*x2[0] end subroutine   function s_tri(ref(x1),ref(x2),ref(x3)) call cross_product(ref(x2),ref(x3),ref(y1)) s_tri=dot_product(ref(x1),ref(y1)) end function   subroutine v_tri(ref(x1),ref(x2),ref(x3),ref(y1),ref(y2)) call cross_product(ref(x2),ref(x3),ref(y1)) call cross_product(ref(x1),ref(y1),ref(y2)) end subroutine    
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#ALGOL_W
ALGOL W
begin  % external procedure that returns true if ccNumber passes the Luhn test, false otherwise % logical procedure LuhnTest ( string(32) value ccNumber  ; integer value ccLength ) ; algol "LUHN" ;    % returns true if isin is a valid ISIN, false otherwise  % logical procedure isIsin ( string(32) value isin ) ; if isin( 12 // 20 ) not = "" then false % code is too long % else begin  % the first two characters must be upper-case letters %    % returns the digit corresponding to a character of an ISIN % integer procedure isinDigit ( string(1) value iChar ) ; if iChar >= "0" and iChar <= "9" then ( decode( iChar ) - decode( "0" ) ) else if iChar >= "A" and iChar <= "Z" then ( decode( iChar ) - decode( "A" ) ) + 10 else begin % invalid digit % isValid := false; -1 end isinDigit ;   integer d1, d2; logical isValid; isValid := true; d1  := isinDigit( isin( 0 // 1 ) ); d2  := isinDigit( isin( 1 // 1 ) ); if d1 < 10 or d1 > 35 or d2 < 10 or d2 > 35 then false % invalid first two characters % else begin  % ok so far - conveet from base 36 to base 10 % string(24) base10Isin; integer b10Pos; base10Isin := ""; b10Pos  := 0; for cPos := 0 until 10 do begin integer digit; digit := isinDigit( isin( cPos // 1 ) ); if isValid then begin  % valid digit % if digit > 9 then begin base10Isin( b10Pos // 1 ) := code( ( digit div 10 ) + decode( "0" ) ); b10Pos  := b10Pos + 1; end if_digit_gt_9 ; base10Isin( b10Pos // 1 )  := code( ( digit rem 10 ) + decode( "0" ) ); b10Pos  := b10Pos + 1 end if_isValid end for_cPos ;  % add the check digit as is % base10Isin( b10Pos // 1 ) := isin( 11 // 1 ); isValid and LuhnTest( base10Isin, b10Pos + 1 ) end end isIsin ;    % task test cases %   procedure testIsIsin ( string(32) value isin  ; logical value expected ) ; begin logical isValid; isValid := isIsin( isin ); write( s_w := 0 , isin , if isValid then " is valid" else " is invalid" , if isValid = expected then "" else " NOT as expected ??" ) end testIsin ;   testIsIsin( "US0378331005", true ); testIsIsin( "US0373831005", false ); testIsIsin( "U50378331005", false ); testIsIsin( "US03378331005", false ); testIsIsin( "AU0000XVGZA3", true ); testIsIsin( "AU0000VXGZA3", true ); testIsIsin( "FR0000988040", true ); end.
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation"   on ISINTest(ISIN) -- Check that the input is both text and 12 characters long … if not ((ISIN's class is text) and ((count ISIN) is 12)) then return false -- … and that it has the required format. set ISIN to current application's class "NSMutableString"'s stringWithString:(ISIN) if ((ISIN's rangeOfString:("^[A-Z]{2}[0-9A-Z]{9}[0-9]$") options:(current application's NSRegularExpressionSearch) range:({0, ISIN's |length|()}))'s |length|() is 0) then return false -- Replace all letters with text representations of equivalent decimal numbers in the range 10 to 35. set letterCharacters to characters of "ABCDEFGHIJKLMNOPQRSTUVWXYZ" repeat with i from 1 to 26 tell ISIN to replaceOccurrencesOfString:(item i of letterCharacters) withString:((i + 9) as text) options:(0) range:({0, its |length|()}) end repeat   -- Apply the Luhn test handler from the "Luhn test of credit card numbers" task. -- <https://www.rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Straightforward> return luhnTest(ISIN as text) end ISINTest   -- Test code: set testResults to {} repeat with ISIN in {"US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"} set end of testResults to {testNumber:ISIN's contents, valid:ISINTest(ISIN)} end repeat return testResults
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#PL.2FM
PL/M
100H:   /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END; /* CONSOLE OUTPUT ROUTINES */ PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) ); END; PR$NUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE INITIAL( '.....$' ), W BYTE; N$STR( W := LAST( N$STR ) - 1 ) = '0' + ( ( V := N ) MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL PR$STRING( .N$STR( W ) ); END PR$NUMBER;   /* TASK */ DECLARE S( 6 ) BYTE INITIAL( 1, 2, 2, 3, 4, 4, 5 ); DECLARE I BYTE; DO I = 0 TO LAST( S ); DO; DECLARE ( CURR, PREV ) BYTE; CURR = S( I ); IF I > 1 AND CURR = PREV THEN DO; CALL PR$NUMBER( I ); CALL PR$NL; END; PREV = CURR; END; END;   EOF
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Ada
Ada
with Ada.Text_IO;   procedure Main is package Float_IO is new Ada.Text_IO.Float_IO (Float); function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is Value  : Natural  := N; Result  : Float  := 0.0; Exponent : Positive := 1; begin while Value > 0 loop Result  := Result + Float (Value mod Base) / Float (Base ** Exponent); Value  := Value / Base; Exponent := Exponent + 1; end loop; return Result; end Van_Der_Corput; begin for Base in 2 .. 5 loop Ada.Text_IO.Put ("Base" & Integer'Image (Base) & ":"); for N in 1 .. 10 loop Ada.Text_IO.Put (' '); Float_IO.Put (Item => Van_Der_Corput (N, Base), Exp => 0); end loop; Ada.Text_IO.New_Line; end loop; end Main;
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#AutoHotkey
AutoHotkey
SetFormat, FloatFast, 0.5 for i, v in [2, 3, 4, 5, 6] { seq .= "Base " v ": " Loop, 10 seq .= VanDerCorput(A_Index - 1, v) (A_Index = 10 ? "`n" : ", ") } MsgBox, % seq   VanDerCorput(n, b, r=0) { while n r += Mod(n, b) * b ** -A_Index, n := n // b return, r }
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Ada
Ada
Name: declare -- a local declaration block has an optional name A : constant Integer := 42; -- Create a constant X : String := "Hello"; -- Create and initialize a local variable Y : Integer; -- Create an uninitialized variable Z : Integer renames Y: -- Rename Y (creates a view) function F (X: Integer) return Integer is -- Inside, all declarations outside are visible when not hidden: X, Y, Z are global with respect to F. X: Integer := Z; -- hides the outer X which however can be referred to by Name.X begin ... end F; -- locally declared variables stop to exist here begin Y := 1; -- Assign variable declare X: Float := -42.0E-10; -- hides the outer X (can be referred to Name.X like in F) begin ... end; end Name; -- End of the scope
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#ALGOL-M
ALGOL-M
begin integer array eck[1:1000]; integer i, j;   for i := 1 step 1 until 1000 do eck[i] := 0;   for i := 1 step 1 until 999 do begin j := i - 1; while j > 0 and eck[i] <> eck[j] do j := j - 1; if j <> 0 then eck[i+1] := i - j; end;   for i := 1 step 1 until 10 do writeon(eck[i]); write(""); for i := 991 step 1 until 1000 do writeon(eck[i]);   end
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#ALGOL_W
ALGOL W
begin % find elements of the Van Eck Sequence - first term is 0, following  %  % terms are 0 if the previous was the first appearance of the element %  % or how far back in the sequence the last element appeared  %  % sets s to the first n elements of the Van Eck sequence  % procedure VanEck ( integer array s ( * ) ; integer value n ) ; begin integer array pos ( 0 :: n ); for i := 1 until n do s( i ) := 0; for i := 0 until n do pos( i ) := 0; for i := 2 until n do begin integer j, prev; j  := i - 1; prev := s( j ); if pos( prev ) not = 0 then begin  % not a new element  % s( i ) := j - pos( prev ) end if_pos_prev_ne_0 ; pos( prev ) := j end for_j; end VanEck ;  % construct the first 1000 terms of the sequence  % integer MAX_VAN_ECK; MAX_VAN_ECK := 1000; begin integer array seq ( 1 :: MAX_VAN_ECK ); VanEck( seq, MAX_VAN_ECK );  % show the first and last 10 elements  % for i := 1 until 10 do writeon( i_w := 1, s_w := 0, " ", seq( i ) ); write(); for i := MAX_VAN_ECK - 9 until MAX_VAN_ECK do writeon( i_w := 1, s_w := 0, " ", seq( i ) ); write() end end.
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#C.2B.2B
C++
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath>   bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( numberstream.str( ) ) ; std::sort ( numberstring.begin( ) , numberstring.end( ) ) ; int fanglength = numberstring.length( ) / 2 ; long start = static_cast<long>( std::pow( 10 , fanglength - 1 ) ) ; long end = sqrt(number) ; for ( long i = start ; i <= end ; i++ ) { if ( number % i == 0 ) { long quotient = number / i ; if ( ( i % 10 == 0 ) && ( quotient % 10 == 0 ) ) continue ; numberstream.str( "" ) ; //clear the number stream numberstream << i << quotient ; std::string divisorstring ( numberstream.str( ) ) ; std::sort ( divisorstring.begin( ) , divisorstring.end( ) ) ; if ( divisorstring == numberstring ) { std::pair<long , long> divisors = std::make_pair( i, quotient ) ; solution.push_back( divisors ) ; } } } return !solution.empty( ) ; }   void printOut( const std::pair<long, long> & solution ) { std::cout << "[ " << solution.first << " , " << solution.second << " ]" ; }   int main( ) { int vampireNumbersFound = 0 ; std::vector<std::pair<long , long> > solutions ; double i = 1.0 ; while ( vampireNumbersFound < 25 ) { long start = static_cast<long>( std::pow( 10 , i ) ) ; long end = start * 10 ; for ( long num = start ; num < end ; num++ ) { if ( isVampireNumber( num , solutions ) ) { vampireNumbersFound++ ; std::cout << vampireNumbersFound << " :" << num << " is a vampire number! These are the fangs:\n" ; std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; std::cout << "\n_______________" << std::endl ; solutions.clear( ) ; if ( vampireNumbersFound == 25 ) break ; } } i += 2.0 ; } std::vector<long> testnumbers ; testnumbers.push_back( 16758243290880 ) ; testnumbers.push_back( 24959017348650 ) ; testnumbers.push_back( 14593825548650 ) ; for ( std::vector<long>::const_iterator svl = testnumbers.begin( ) ; svl != testnumbers.end( ) ; svl++ ) { if ( isVampireNumber( *svl , solutions ) ) { std::cout << *svl << " is a vampire number! The fangs:\n" ; std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; std::cout << std::endl ; solutions.clear( ) ; } else { std::cout << *svl << " is not a vampire number!" << std::endl ; } } return 0 ; }
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#PicoLisp
PicoLisp
(de numToVlq (Num) (let Res (cons (& Num 127)) (while (gt0 (setq Num (>> 7 Num))) (push 'Res (| 128 (& Num 127))) ) Res ) )   (de vlqToNum (Vlq) (let Res 0 (for N Vlq (setq Res (| (>> -7 Res) (& N 127))) ) ) )   (for Num (0 15 16 127 128 255 2097151 2097152) (let Vlq (numToVlq Num) (tab (12 12 12) Num (glue ":" (mapcar hex Vlq)) (vlqToNum Vlq)) ) )
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#PL.2FI
PL/I
  test: procedure options(main); declare s character (20) varying; declare c character (1); declare v fixed binary (31); declare (i, k) fixed binary;   get edit (s) (L); s = trim (s); v = 0; do i = 1 to length(s); c = substr(s, i, 1); k = index('0123456789abcdef', c); if k > 0 then v = v*16 + k - 1; end; put skip data (s, v);   /* Convert back to hex */ declare hex character(16) initial ('0123456789abcdef'); declare hs character (20) initial (''); declare d fixed binary;   do i = length(hs) to 1 by -1 until (v = 0); d = mod(v, 16) + 1; substr(hs, i, 1) = substr(hex, d, 1); v = v/16; end; put skip list (hs); end test;  
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#Python
Python
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1)//_group)*_group)[::-1] answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer   def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True)   def toint(vlq): return int(''.join(vlq.split('_1')), 2)   def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:#04x}'.format(i, int(byte,2)))
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#E
E
def example { match [`run`, args] { for x in args { println(x) } } }   example("Mary", "had", "a", "little", "lamb")   E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Egel
Egel
  [ X Y -> "two" | X -> "one" | -> "zero" ]  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Gambas
Gambas
Public Sub Main()   Print "Boolean =\t " & SizeOf(gb.Boolean) Print "Byte =\t\t " & SizeOf(gb.Byte) Print "Short =\t\t " & SizeOf(gb.Short) Print "Integer =\t " & SizeOf(gb.Integer) Print "Single =\t " & SizeOf(gb.Single) Print "Long =\t\t " & SizeOf(gb.Long) Print "Float =\t\t " & SizeOf(gb.Float) Print "Date =\t\t " & SizeOf(gb.Date) Print "String =\t " & SizeOf(gb.String) Print "Object =\t " & SizeOf(gb.Object) Print "Pointer =\t " & SizeOf(gb.Pointer) Print "Variant =\t " & SizeOf(gb.Variant)   End
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Go
Go
import "unsafe"   unsafe.Sizeof(x)
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Lua
Lua
vector = {mt = {}}   function vector.new (x, y) local new = {x = x or 0, y = y or 0} setmetatable(new, vector.mt) return new end   function vector.mt.__add (v1, v2) return vector.new(v1.x + v2.x, v1.y + v2.y) end   function vector.mt.__sub (v1, v2) return vector.new(v1.x - v2.x, v1.y - v2.y) end   function vector.mt.__mul (v, s) return vector.new(v.x * s, v.y * s) end   function vector.mt.__div (v, s) return vector.new(v.x / s, v.y / s) end   function vector.print (vec) print("(" .. vec.x .. ", " .. vec.y .. ")") end   local a, b = vector.new(5, 7), vector.new(2, 3) vector.print(a + b) vector.print(a - b) vector.print(a * 11) vector.print(a / 2)
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#Wren
Wren
import "/math" for Math, Nums import "/fmt" for Fmt   var integrate = Fn.new { |a, b, n, f| var h = (b - a) / n var sum = 0 for (i in 0...n) { var x = a + i*h sum = sum + (f.call(x) + 4 * f.call(x + h/2) + f.call(x + h)) / 6 } return sum * h }   var gammaIncomplete = Fn.new { |a, x| var am1 = a - 1 var f0 = Fn.new { |t| t.pow(am1) * (-t).exp } var h = 1.5e-2 var y = am1 while ((f0.call(y) * (x - y) > 2e-8) && y < x) y = y + 0.4 if (y > x) y = x return 1 - integrate.call(0, y, (y/h).truncate, f0) / Math.gamma(a) }   var chi2UniformDistance = Fn.new { |ds| var expected = Nums.mean(ds) var sum = Nums.sum(ds.map { |d| (d - expected).pow(2) }.toList) return sum / expected }   var chi2Probability = Fn.new { |dof, dist| gammaIncomplete.call(0.5*dof, 0.5*dist) }   var chiIsUniform = Fn.new { |ds, significance| var dof = ds.count - 1 var dist = chi2UniformDistance.call(ds) return chi2Probability.call(dof, dist) > significance }   var dsets = [ [199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461] ] for (ds in dsets) { System.print("Dataset: %(ds)") var dist = chi2UniformDistance.call(ds) var dof = ds.count - 1 Fmt.write("DOF: $d Distance: $.4f", dof, dist) var prob = chi2Probability.call(dof, dist) Fmt.write(" Probability: $.6f", prob) var uniform = chiIsUniform.call(ds, 0.05) ? "Yes" : "No" System.print(" Uniform? %(uniform)\n") }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   pt = 'Attack at dawn!' key = 'LEMON' test(key, pt)   key = 'N' -- rot-13 test(key, pt)   key = 'B' -- Caesar test(key, pt)   pt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' key = 'A' test(key, pt)   pt = sampledata() key = 'Hamlet; Prince of Denmark' test(key, pt)   return   method vigenere(meth, key, text) public static   select when 'encipher'.abbrev(meth.lower, 1) then df = 1 when 'decipher'.abbrev(meth.lower, 1) then df = -1 otherwise signal IllegalArgumentException(meth 'must be "encipher" or "decipher"') end   alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'   text = stringscrubber(text) key = stringscrubber(key) code = '' loop l_ = 1 to text.length() M = alpha.pos(text.substr(l_, 1)) - 1 k_ = (l_ - 1) // key.length() K = alpha.pos(key.substr(k_ + 1, 1)) - 1 C = mod((M + K * df), alpha.length()) C = alpha.substr(C + 1, 1) code = code || C end l_   return code   method vigenere_encipher(key, plaintext) public static   return vigenere('encipher', key, plaintext)   method vigenere_decipher(key, ciphertext) public static   return vigenere('decipher', key, ciphertext)   method mod(N = int, D = int) private static   return (D + (N // D)) // D   method stringscrubber(cleanup) private static   alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'   cleanup = cleanup.upper.space(0) loop label f_ forever x_ = cleanup.verify(alpha) if x_ = 0 then leave f_ cleanup = cleanup.changestr(cleanup.substr(x_, 1), '') end f_   return cleanup   method test(key, pt) private static   ct = vigenere_encipher(key, pt) display(ct) dt = vigenere_decipher(key, ct) display(dt)   return   method display(text) public static   line = '' o_ = 0 loop c_ = 1 to text.length() b_ = o_ // 5 o_ = o_ + 1 if b_ = 0 then line = line' ' line = line || text.substr(c_, 1) end c_   say '....+....|'.copies(8) loop label l_ forever parse line w1 w2 w3 w4 w5 w6 W7 w8 w9 w10 w11 w12 line pline = w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 say pline.strip() if line.strip().length() = 0 then leave l_ end l_ say   return   method sampledata() private static returns Rexx   NL = char('\n') antic_disposition = Rexx[]   antic_disposition = [ - Rexx("To be, or not to be--that is the question:" ), - Rexx("Whether 'tis nobler in the mind to suffer" ), - Rexx("The slings and arrows of outrageous fortune" ), - Rexx("Or to take arms against a sea of troubles" ), - Rexx("And by opposing end them. To die, to sleep--" ), - Rexx("No more--and by a sleep to say we end" ), - Rexx("The heartache, and the thousand natural shocks" ), - Rexx("That flesh is heir to. 'Tis a consummation" ), - Rexx("Devoutly to be wished. To die, to sleep--" ), - Rexx("To sleep--perchance to dream: ay, there's the rub,"), - Rexx("For in that sleep of death what dreams may come" ), - Rexx("When we have shuffled off this mortal coil," ), - Rexx("Must give us pause. There's the respect" ), - Rexx("That makes calamity of so long life." ), - Rexx("For who would bear the whips and scorns of time," ), - Rexx("Th' oppressor's wrong, the proud man's contumely" ), - Rexx("The pangs of despised love, the law's delay," ), - Rexx("The insolence of office, and the spurns" ), - Rexx("That patient merit of th' unworthy takes," ), - Rexx("When he himself might his quietus make" ), - Rexx("With a bare bodkin? Who would fardels bear," ), - Rexx("To grunt and sweat under a weary life," ), - Rexx("But that the dread of something after death," ), - Rexx("The undiscovered country, from whose bourn" ), - Rexx("No traveller returns, puzzles the will," ), - Rexx("And makes us rather bear those ills we have" ), - Rexx("Than fly to others that we know not of?" ), - Rexx("Thus conscience does make cowards of us all," ), - Rexx("And thus the native hue of resolution" ), - Rexx("Is sicklied o'er with the pale cast of thought," ), - Rexx("And enterprise of great pith and moment" ), - Rexx("With this regard their currents turn awry" ), - Rexx("And lose the name of action. -- Soft you now," ), - Rexx("The fair Ophelia! -- Nymph, in thy orisons" ), - Rexx("Be all my sins remembered." ) - ]   melancholy_dane = Rexx('') loop l_ = 0 for antic_disposition.length melancholy_dane = melancholy_dane || antic_disposition[l_] || NL end l_   return melancholy_dane  
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   3D   images   etc. Task Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#Tcl
Tcl
package require struct::tree   proc visualize_tree {tree {nameattr name}} { set path {} $tree walk [$tree rootname] -order both {mode node} { if {$mode eq "enter"} { set s "" foreach p $path { append s [expr {[$tree next $p] eq "" ? " " : "\u2502 "}] } lappend path $node append s [expr { [$tree next $node] eq "" ? "\u2514\u2500" : "\u251c\u2500" }] if {[$tree keyexists $node $nameattr]} { set name [$tree get $node $nameattr] } else { # No node name attribute; use the raw name set name $node } puts "$s$name" } else { set path [lrange $path 0 end-1] } } }
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Racket
Racket
  -> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...  
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Raku
Raku
use File::Find;   .say for find dir => '.', name => /'.txt' $/;
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██ 6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██ 5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████ 4 ██ ██ ████████ 4 ██≈≈██≈≈████████ 3 ██████ ████████ 3 ██████≈≈████████ 2 ████████████████ ██ 2 ████████████████≈≈██ 1 ████████████████████ 1 ████████████████████ In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele Water collected between towers on Stack Overflow, from which the example above is taken) An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
#Scheme
Scheme
(import (scheme base) (scheme write))   (define (total-collected chart) (define (highest-left vals curr) (if (null? vals) (list curr) (cons curr (highest-left (cdr vals) (max (car vals) curr))))) (define (highest-right vals curr) (reverse (highest-left (reverse vals) curr))) ; (if (< (length chart) 3) ; catch the end cases 0 (apply + (map (lambda (l c r) (if (or (<= l c) (<= r c)) 0 (- (min l r) c))) (highest-left chart 0) chart (highest-right chart 0)))))   (for-each (lambda (chart) (display chart) (display " -> ") (display (total-collected chart)) (newline)) '((1 5 3 7 2) (5 3 7 2 6 4 5 9 1 2) (2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1) (5 5 5 5) (5 6 7 8) (8 7 7 6) (6 7 10 7 6)))
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#BBC_BASIC
BBC BASIC
DIM a(2), b(2), c(2), d(2) a() = 3, 4, 5 b() = 4, 3, 5 c() = -5, -12, -13   PRINT "a . b = "; FNdot(a(),b()) PROCcross(a(),b(),d()) PRINT "a x b = (";d(0)", ";d(1)", ";d(2)")" PRINT "a . (b x c) = "; FNscalartriple(a(),b(),c()) PROCvectortriple(a(),b(),c(),d()) PRINT "a x (b x c) = (";d(0)", ";d(1)", ";d(2)")" END   DEF FNdot(A(),B()) LOCAL C() : DIM C(0,0) C() = A().B() = C(0,0)   DEF PROCcross(A(),B(),C()) C() = A(1)*B(2)-A(2)*B(1), A(2)*B(0)-A(0)*B(2), A(0)*B(1)-A(1)*B(0) ENDPROC   DEF FNscalartriple(A(),B(),C()) LOCAL D() : DIM D(2) PROCcross(B(),C(),D()) = FNdot(A(),D())   DEF PROCvectortriple(A(),B(),C(),D()) PROCcross(B(),C(),D()) PROCcross(A(),D(),D()) ENDPROC
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#AWK
AWK
  # syntax: GAWK -f VALIDATE_INTERNATIONAL_SECURITIES_IDENTIFICATION_NUMBER.AWK # converted from Fortran BEGIN { for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value n = split("US0378331005,US0373831005,U50378331005,US03378331005,AU0000XVGZA3,AU0000VXGZA3,FR0000988040",arr,",") for (i=1; i<=n; i++) { printf("%s %s\n",is_isin(arr[i]),arr[i]) } exit(0) } function is_isin(arg, i,j,k,s,v) { for (i=1; i<=12; i++) { # convert to an array of digits k = ord_arr[substr(arg,i,1)] if (k >= 48 && k <= 57) { if (i < 3) { return(0) } k -= 48 s[++j] = k } else if (k >= 65 && k <= 90) { if (i == 12) { return(0) } k = k - 65 + 10 s[++j] = int(k / 10) s[++j] = k % 10 } else { return(0) } } for (i=j-1; i>=1; i-=2) { # compute checksum k = 2 * s[i] if (k > 9) { k -= 9 } v += k } for (i=j; i>=1; i-=2) { v += s[i] } return(v % 10 == 0) }  
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Python
Python
  s = [1, 2, 2, 3, 4, 4, 5]   for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr  
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Raku
Raku
my @s = 1, 2, 2, 3, 4, 4, 5; loop (my $i = 0; $i < 7; $i += 1) { my $curr = @s[$i]; my $prev; if $i > 1 and $curr == $prev { say $i; } $prev = $curr; }
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#Red
Red
Red[] s: [1 2 2 3 4 4 5] repeat i length? s [ curr: s/:i if all [i > 1 curr = prev][ print i ] prev: curr ]
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#AWK
AWK
  # syntax: GAWK -f VAN_DER_CORPUT_SEQUENCE.AWK # converted from BBC BASIC BEGIN { printf("base") for (i=0; i<=9; i++) { printf(" %7d",i) } printf("\n") for (base=2; base<=5; base++) { printf("%-4s",base) for (i=0; i<=9; i++) { printf(" %7.5f",vdc(i,base)) } printf("\n") } exit(0) } function vdc(n,b, s,v) { s = 1 while (n) { s *= b v += (n % b) / s n /= b n = int(n) } return(v) }  
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#BASIC
BASIC
10 DEFINT A-Z 20 FOR B=2 TO 5 30 PRINT USING "BASE #:";B; 40 FOR I=0 TO 9 50 P=0: Q=1: N=I 60 IF N=0 GOTO 110 70 P=P*B+N MOD B 80 Q=Q*B 90 N=N\B 100 GOTO 60 110 X=P: Y=Q 120 IF P=0 GOTO 150 130 N=P: P=Q MOD P: Q=N 140 GOTO 120 150 X=X\Q 160 Y=Y\Q 170 IF X=0 THEN PRINT " 0"; ELSE PRINT USING " ##/##";X;Y; 180 NEXT I 190 PRINT 200 NEXT B
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#ALGOL_68
ALGOL 68
int j;
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#ALGOL_W
ALGOL W
% declare some variables % integer a1, a2; real b; long real c; complex d; long complex f; logical g; bits h; string(32) j;   % assign "initial values" % f := d := c := b := a2 := a1 := 0; % multiple assignment % g := false; h := #a0; j := "Hello, World!";  
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#APL
APL
(10∘↑,[.5]¯10∘↑)(⊢,(⊃∘⌽∊¯1∘↓)∧(1↓⌽)⍳⊃∘⌽)⍣999⊢,0
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#AppleScript
AppleScript
use AppleScript version "2.4" use scripting additions     -- vanEck :: Int -> [Int] on vanEck(n) -- First n terms of the vanEck sequence.   script go on |λ|(xns, i) set {x, ns} to xns set prev to item (1 + x) of ns   if 0 ≠ prev then set v to i - prev else set v to 0 end if   {{v, insert(ns, x, i)}, v} end |λ| end script     {0} & item 2 of mapAccumL(go, ¬ {0, replicate(n, 0)}, enumFromTo(1, n - 1)) end vanEck     --------------------------- TEST --------------------------- on run unlines({¬ "First 10 terms:", ¬ showList(vanEck(10)), ¬ "", ¬ "Terms 990 to 1000:", ¬ showList(items -10 thru -1 of vanEck(1000))}) end run       ------------------------- GENERIC --------------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- insert :: [Int] -> Int -> Int -> [Int] on insert(xs, i, v) -- A list updated at position i with value v. set item (1 + i) of xs to v xs end insert     -- intercalate :: String -> [String] -> String on intercalate(delim, xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, delim} set s to xs as text set my text item delimiters to dlm s end intercalate     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn     -- 'The mapAccumL function behaves like a combination of map and foldl; -- it applies a function to each element of a list, passing an -- accumulating parameter from |Left| to |Right|, and returning a final -- value of this accumulator together with the new list.' (see Hoogle) -- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) on mapAccumL(f, acc, xs) script on |λ|(a, x, i) tell mReturn(f) to set pair to |λ|(item 1 of a, x, i) {item 1 of pair, (item 2 of a) & {item 2 of pair}} end |λ| end script   foldl(result, {acc, []}, xs) end mapAccumL     -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if 1 > n then return out set dbl to {a}   repeat while (1 < n) if 0 < (n mod 2) then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate     -- showList :: [a] -> String on showList(xs) "[" & intercalate(", ", map(my str, xs)) & "]" end showList     -- str :: a -> String on str(x) x as string end str     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s end unlines
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Clojure
Clojure
(defn factor-pairs [n] (for [x (range 2 (Math/sqrt n))  :when (zero? (mod n x))] [x (quot n x)]))   (defn fangs [n] (let [dlen (comp count str) half (/ (dlen n) 2) halves? #(apply = (cons half (map dlen %))) digits #(sort (apply str %))] (filter #(and (halves? %) (= (sort (str n)) (digits %))) (factor-pairs n))))   (defn vampiric? [n] (let [fangs (fangs n)] (if (empty? fangs) nil [n fangs])))   (doseq [n (take 25 (keep vampiric? (range)))] (prn n))   (doseq [n [16758243290880, 24959017348650, 14593825548650]] (println (or (vampiric? n) (str n " is not vampiric."))))
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#Racket
Racket
  #lang racket   (define (try n) (printf "Original number: ~s (0x~x)\n" n n) (define 4octets (integer->integer-bytes n 4 #f)) (printf "Octets: ~a (byte-string: ~s)\n" (string-join (map (λ(o) (~r o #:base 16)) (bytes->list 4octets)) ":") 4octets) (define m (integer-bytes->integer 4octets #f)) (printf "Back to a number: ~s (~a)\n" m (if (= m n) "OK" "BAD")))   (for-each try '(#x200000 #x1fffff))  
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); display these sequences of octets; convert these sequences of octets back to numbers, and check that they are equal to original numbers.
#Raku
Raku
sub vlq_encode ($number is copy) { my $string = ''; my $t = 0x7F +& $number; $number +>= 7; $string = $t.chr ~ $string; while ($number) { $t = 0x7F +& $number; $string = (0x80 +| $t).chr ~ $string; $number +>= 7; } return $string; }   sub vlq_decode ($string is copy) { my $number = '0b'; for $string.ords -> $oct { $number ~= ($oct +& 0x7F).fmt("%07b"); } return :2($number); }   #test encoding and decoding for ( 0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000 ) -> $testcase { my $encoded = vlq_encode($testcase); printf "%8s %12s %8s\n", $testcase, ( join ':', $encoded.ords>>.fmt("%02X") ), vlq_decode($encoded); }
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Elena
Elena
import system'routines; import extensions;   extension variadicOp { printAll(params object[] list) { for(int i := 0, i < list.Length, i+=1) { self.printLine(list[i]) } } }   public program() { console.printAll("test", "rosetta code", 123, 5.6r) }
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Elixir
Elixir
defmodule RC do def print_each( arguments ) do Enum.each(arguments, fn x -> IO.inspect x end) end end   RC.print_each([1,2,3]) RC.print_each(["Mary", "had", "a", "little", "lamb"])
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Haskell
Haskell
import Foreign   sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine) sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine) sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine) sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Icon_and_Unicon
Icon and Unicon
record rec0() record rec4(a,b,c,d)   procedure main() # get size   every i := seq(1) do { a0 := &allocated x := case i of { 1 : "ABCDEFGH" 2 : reverse(x) 10 : &digits 11 : x--x 20 : [] 21 : [1,2] 22 : [1,2,3] 30 : set() 31 : set("X") 32 : set("A","B") 40 : table(1) 50 : rec0() 51 : rec4() 60 : create seq(1) 99 : break default : next } a1 := &allocated write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0) } end
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Maple
Maple
module MyVector() option object; local value := Vector();   export ModuleApply::static := proc( ) Object( MyVector, _passed ); end proc;   export ModuleCopy::static := proc( mv::MyVector, proto::MyVector, v::Vector, $ ) mv:-value := v; end proc;   export ModulePrint::static := proc(mv::MyVector, $ ) mv:-value; end proc;     # operations: export `+`::static := proc( v1::MyVector, v2::MyVector ) MyVector( v1:-value + v2:-value ); end proc;   export `*`::static := proc( v::MyVector, scalar_val::numeric) MyVector( v:-value * scalar_val); end proc;     end module:
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[vector,PrintVector] vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}] vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z] a_ vector[x_,y_]^:=vector[a x,a y] vector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z] PrintVector[vector[x_,y_]]:=Print["vector has first component: ",x," And second component: ",y]   vector[1,2]+vector[3,4] vector[1,2]-vector[3,4] 12vector[1,2] vector[1,2]/3 PrintVector@vector[{Sqrt[2],45Degree}]
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. Reference   an entry at the MathWorld website:   chi-squared distribution.
#zkl
zkl
/* Numerical integration method */ fcn Simpson3_8(f,a,b,N){ // fcn,double,double,Int --> double h,h1:=(b - a)/N, h/3.0; h*[1..3*N - 1].reduce('wrap(sum,j){ l1:=(if(j%3) 3.0 else 2.0); sum + l1*f(a + h1*j); },f(a) + f(b))/8.0; }   const A=12; fcn Gamma_Spouge(z){ // double --> double var coefs=fcn{ // this runs only once, at construction time a,coefs:=A.toFloat(),(A).pump(List(),0.0); k1_factrl:=1.0; coefs[0]=(2.0*(0.0).pi).sqrt(); foreach k in ([1.0..A-1]){ coefs[k]=(a - k).exp() * (a - k).pow(k - 0.5) / k1_factrl; k1_factrl*=-k; } coefs }();   ( [1..A-1].reduce('wrap(accum,k){ accum + coefs[k]/(z + k) },coefs[0]) * (-(z + A)).exp()*(z + A).pow(z + 0.5) ) / z; }   fcn f0(t,aa1){ t.pow(aa1)*(-t).exp() }   fcn GammaIncomplete_Q(a,x){ // double,double --> double h:=1.5e-2; /* approximate integration step size */ /* this cuts off the tail of the integration to speed things up */ y:=a - 1; f:=f0.fp1(y); while((f(y)*(x - y)>2.0e-8) and (y<x)){ y+=0.4; } if(y>x) y=x; 1.0 - Simpson3_8(f,0.0,y,(y/h).toInt())/Gamma_Spouge(a); }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Nim
Nim
import strutils   proc encrypt(msg, key: string): string = var pos = 0 for c in msg: if c in Letters: result.add chr(((ord(key[pos]) + ord(c.toUpperAscii)) mod 26) + ord('A')) pos = (pos + 1) mod key.len   proc decrypt(msg, key: string): string = var pos = 0 for c in msg: result.add chr(((26 + ord(c) - ord(key[pos])) mod 26) + ord('A')) pos = (pos + 1) mod key.len   const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" const key = "VIGENERECIPHER"   let encr = encrypt(text, key) let decr = decrypt(encr, key)   echo text echo encr echo decr
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Objeck
Objeck
  bundle Default { class VigenereCipher { function : Main(args : String[]) ~ Nil { key := "VIGENERECIPHER"; ori := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; enc := encrypt(ori, key); IO.Console->Print("encrypt: ")->PrintLine(enc); IO.Console->Print("decrypt: ")->PrintLine(decrypt(enc, key)); }   function : native : encrypt(text : String, key : String) ~ String { res := ""; text := text->ToUpper(); j := 0;   each(i : text) { c := text->Get(i); if(c >= 'A' & c <= 'Z') { res->Append(((c + key->Get(j) - 2 * 'A') % 26 + 'A')->As(Char)); j += 1; j := j % key->Size(); }; };   return res; }   function : native : decrypt(text : String, key : String) ~ String { res := ""; text := text->ToUpper(); j := 0;   each(i : text) { c := text->Get(i); if(c >= 'A' & c <= 'Z') { res->Append(((c - key->Get(j) + 26) % 26 + 'A')->As(Char)); j += 1; j := j % key->Size(); }; };   return res; } } }  
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or   3D   images   etc. Task Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#Wren
Wren
import "/dynamic" for Struct import "random" for Random   var Stem = Struct.create("Stem", ["str", "next"])   var SDOWN = " |" var SLAST = " `" var SNONE = " "   var rand = Random.new()   var tree // recursive tree = Fn.new { |root, head| var col = Stem.new(null, null) var tail = head while (tail) { System.write(tail.str) if (!tail.next) break tail = tail.next } System.print("--%(root)") if (root <= 1) return if (tail && tail.str == SLAST) tail.str = SNONE if (!tail) { tail = head = col } else { tail.next = col } while (root != 0) { // make a tree by doing something random var r = 1 + rand.int(root) root = root - r col.str = (root != 0) ? SDOWN : SLAST tree.call(r, head) } tail.next = null }   var n = 8 tree.call(n, null)
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#Rascal
Rascal
//usage example: To list just Rascal source files, Walk(|home:///workspace/|, ".rsc"); module Walk import String; import IO; public void Walk(loc a, str pattern){ for (entry <- listEntries(a)) if (endsWith(entry, pattern)) println(entry); elseif (isDirectory(a+entry)) Walk(a+entry, pattern); }
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   (read a single directory).
#REALbasic
REALbasic
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub