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/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.
#Sidef
Sidef
func max_l(Array a, m = a[0]) { gather { a.each {|e| take(m = max(m, e)) } } }   func max_r(Array a) { max_l(a.flip).flip }   func water_collected(Array towers) { var levels = (max_l(towers) »min« max_r(towers)) (levels »-« towers).grep{ _ > 0 }.sum }   [ [ 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 ], ].map { water_collected(_) }.say
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
#BQN
BQN
Dot ← +´∘× Cross ← 1⊸⌽⊸×{1⌽𝔽˜-𝔽} Triple ← {𝕊a‿b‿c: a Dot b Cross c} VTriple ← Cross´   a←3‿4‿5 b←4‿3‿5 c←¯5‿¯12‿¯13
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
#C
C
#include <stdio.h>   int check_isin(char *a) { int i, j, k, v, s[24];   j = 0; for(i = 0; i < 12; i++) { k = a[i]; if(k >= '0' && k <= '9') { if(i < 2) return 0; s[j++] = k - '0'; } else if(k >= 'A' && k <= 'Z') { if(i == 11) return 0; k -= 'A' - 10; s[j++] = k / 10; s[j++] = k % 10; } else { return 0; } }   if(a[i]) return 0;   v = 0; for(i = j - 2; i >= 0; i -= 2) { k = 2 * s[i]; v += k > 9 ? k - 9 : k; }   for(i = j - 1; i >= 0; i -= 2) { v += s[i]; }   return v % 10 == 0; }   int main() { char *test[7] = {"US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"}; int i; for(i = 0; i < 7; i++) printf("%c%c", check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\n' : ' '); return 0; }   /* will print: T F F F T T T */
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local const array integer: s is [] (1, 2, 2, 3, 4, 4, 5); var integer: i is 0; var integer: curr is 0; var integer: prev is 0; begin for i range 1 to length(s) do curr := s[i]; if i > 1 and curr = prev then writeln(i); end if; prev := curr; end for; end func;
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.
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Option Explicit On   Imports System.IO   Module vMain   Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub   End Module
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
#BBC_BASIC
BBC BASIC
@% = &20509 FOR base% = 2 TO 5 PRINT "Base " ; STR$(base%) ":" FOR number% = 0 TO 9 PRINT FNvdc(number%, base%); NEXT PRINT NEXT END   DEF FNvdc(n%, b%) LOCAL v, s% s% = 1 WHILE n% s% *= b% v += (n% MOD b%) / s% n% DIV= b% ENDWHILE = 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
#bc
bc
/* * Return the _n_th term of the van der Corput sequence. * Uses the current _ibase_. */ define v(n) { auto c, r, s   s = scale scale = 0 /* to use integer division */   /* * c = count digits of n * r = reverse the digits of n */ for (0; n != 0; n /= 10) { c += 1 r = (10 * r) + (n % 10) }   /* move radix point to left of digits */ scale = length(r) + 6 r /= 10 ^ c   scale = s return r }   t = 10 for (b = 2; b <= 4; b++) { "base "; b obase = b for (i = 0; i < 10; i++) { ibase = b " "; v(i) ibase = t } obase = t } quit
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
#Apex
Apex
  // If not initialized at class/member level, it will be set to null Integer x = 0; Integer y; // y is null here Integer p,q,r; // declare multiple variables Integer i=1,j=2,k=3; // declare and initialize   /* * Similar to Integer, below variables can be initialized together separated by ','. */ String s = 'a string'; Decimal d = 0.0; Double dbl = 0.0; Blob blb = Blob.valueOf('Any String'); Boolean b = true; AClassName cls = new AClassName();  
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program vanEckSerie.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ MAXI, 1000   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResultElement: .asciz " @ " szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 TableVanEck: .skip 4 * MAXI /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r2,#0 @ begin first element mov r3,#0 @ current counter ldr r4,iAdrTableVanEck @ table address str r2,[r4,r3,lsl #2] @ store first zéro 1: @ begin loop mov r5,r3 @ init current indice 2: sub r5,#1 @ decrement cmp r5,#0 @ end table ? movlt r2,#0 @ yes, move zero to next element blt 3f ldr r6,[r4,r5,lsl #2] @ load element cmp r6,r2 @ and compare with the last element bne 2b @ not equal sub r2,r3,r5 @ else compute gap 3: add r3,r3,#1 @ increment counter str r2,[r4,r3,lsl #2] @ and store new element cmp r3,#MAXI blt 1b   mov r2,#0 4: @ loop display ten elements ldr r0,[r4,r2,lsl #2] ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrsMessResultElement ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc mov r1,#0 @ final zéro strb r1,[r0,#5] @ bl affichageMess @ display message add r2,#1 @ increment indice cmp r2,#10 @ end ? blt 4b @ no -> loop ldr r0,iAdrszCarriageReturn bl affichageMess   mov r2,#MAXI - 10 5: @ loop display ten elements 990-999 ldr r0,[r4,r2,lsl #2] ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrsMessResultElement ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc mov r1,#0 @ final zéro strb r1,[r0,#5] @ bl affichageMess @ display message add r2,#1 @ increment indice cmp r2,#MAXI @ end ? blt 5b @ no -> loop ldr r0,iAdrszCarriageReturn bl affichageMess   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResultElement: .int sMessResultElement iAdrsZoneConv: .int sZoneConv iAdrTableVanEck: .int TableVanEck   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#Common_Lisp
Common Lisp
(defun trailing-zerop (number) "Is the lowest digit of `number' a 0" (zerop (rem number 10)))   (defun integer-digits (integer) "Return the number of digits of the `integer'" (assert (integerp integer)) (length (write-to-string integer)))   (defun paired-factors (number) "Return a list of pairs that are factors of `number'" (loop :for candidate :from 2 :upto (sqrt number) :when (zerop (mod number candidate)) :collect (list candidate (/ number candidate))))   (defun vampirep (candidate &aux (digits-of-candidate (integer-digits candidate)) (half-the-digits-of-candidate (/ digits-of-candidate 2))) "Is the `candidate' a vampire number?" (remove-if #'(lambda (pair) (> (length (remove-if #'null (mapcar #'trailing-zerop pair))) 1)) (remove-if-not #'(lambda (pair) (string= (sort (copy-seq (write-to-string candidate)) #'char<) (sort (copy-seq (format nil "~A~A" (first pair) (second pair))) #'char<))) (remove-if-not #'(lambda (pair) (and (eql (integer-digits (first pair)) half-the-digits-of-candidate) (eql (integer-digits (second pair)) half-the-digits-of-candidate))) (paired-factors candidate)))))   (defun print-vampire (candidate fangs &optional (stream t)) (format stream "The number ~A is a vampire number with fangs: ~{ ~{~A~^, ~}~^; ~}~%" candidate fangs))   ;; Print the first 25 vampire numbers   (loop :with count := 0 :for candidate :from 0 :until (eql count 25) :for fangs := (vampirep candidate) :do (when fangs (print-vampire candidate fangs) (incf count)))   ;; Check if 16758243290880, 24959017348650, 14593825548650 are vampire numbers   (dolist (candidate '(16758243290880 24959017348650 14593825548650)) (let ((fangs (vampirep candidate))) (when fangs (print-vampire candidate fangs))))  
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.
#REXX
REXX
/*REXX program displays (and also tests/verifies) some numbers as octets. */ nums = x2d(200000) x2d(1fffff) 2097172 2097151 #=words(nums) say ' number hex octet original' say '══════════ ══════════ ══════════ ══════════' ok=1 do j=1 for #; @.j= word(nums,j) onum.j=octet(@.j) orig.j= x2d( space(onum.j, 0) ) w=10 say center(@.j, w) center(d2x(@.j), w) center(onum.j, w) center(orig.j, w) if @.j\==orig.j then ok=0 end /*j*/ say if ok then say 'All ' # " numbers are OK." /*all of the numbers are good. */ else say "Some numbers are not OK." /*some of the numbers are ¬good. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ octet: procedure; parse arg z,$ /*obtain Z from the passed arguments.*/ x=d2x(z) /*convert Z to a hexadecimal octet. */ do j=length(x) by -2 to 1 /*process the "little" end first. */ $= substr(x, j-1, 2, 0) $ /*pad odd hexadecimal characters with */ end /*j*/ /* ··· a zero on the left. */ return strip($)
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
#Emacs_Lisp
Emacs Lisp
(defun my-print-args (&rest arg-list) (message "there are %d argument(s)" (length arg-list)) (dolist (arg arg-list) (message "arg is %S" arg)))   (my-print-args 1 2 3)
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
#Erlang
Erlang
  print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#IDL
IDL
arr = intarr(3,4) print,size(arr) ;=> prints this: 2 3 4 2 12
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#J
J
some_variable =: 42 7!:5<'some_variable'
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Julia
Julia
julia> sizeof(Int8) 1   julia> t = 1 1   julia> sizeof(t) 8
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { /* sizes for variables of the primitive types (except Boolean which is JVM dependent) */ println("A Byte variable occupies: ${java.lang.Byte.SIZE / 8} byte") println("A Short variable occupies: ${java.lang.Short.SIZE / 8} bytes") println("An Int variable occupies: ${java.lang.Integer.SIZE / 8} bytes") println("A Long variable occupies: ${java.lang.Long.SIZE / 8} bytes") println("A Float variable occupies: ${java.lang.Float.SIZE / 8} bytes") println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes") println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes") }
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
#MiniScript
MiniScript
vplus = function(v1, v2) return [v1[0]+v2[0],v1[1]+v2[1]] end function   vminus = function (v1, v2) return [v1[0]-v2[0],v1[1]-v2[1]] end function   vmult = function(v1, scalar) return [v1[0]*scalar, v1[1]*scalar] end function   vdiv = function(v1, scalar) return [v1[0]/scalar, v1[1]/scalar] end function   vector1 = [2,3] vector2 = [4,5]   print vplus(vector1,vector2) print vminus(vector2, vector1) print vmult(vector1, 3) print vdiv(vector2, 2)
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
#Modula-2
Modula-2
MODULE Vector; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Vector = RECORD x,y : REAL; END;   PROCEDURE Add(a,b : Vector) : Vector; BEGIN RETURN Vector{a.x+b.x, a.y+b.y} END Add;   PROCEDURE Sub(a,b : Vector) : Vector; BEGIN RETURN Vector{a.x-b.x, a.y-b.y} END Sub;   PROCEDURE Mul(v : Vector; r : REAL) : Vector; BEGIN RETURN Vector{a.x*r, a.y*r} END Mul;   PROCEDURE Div(v : Vector; r : REAL) : Vector; BEGIN RETURN Vector{a.x/r, a.y/r} END Div;   PROCEDURE Print(v : Vector); VAR buf : ARRAY[0..64] OF CHAR; BEGIN WriteString("<");   RealToStr(v.x, buf); WriteString(buf); WriteString(", ");   RealToStr(v.y, buf); WriteString(buf); WriteString(">") END Print;   VAR a,b : Vector; BEGIN a := Vector{5.0, 7.0}; b := Vector{2.0, 3.0};   Print(Add(a, b)); WriteLn; Print(Sub(a, b)); WriteLn; Print(Mul(a, 11.0)); WriteLn; Print(Div(a, 2.0)); WriteLn;   ReadChar END Vector.
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
#OCaml
OCaml
let cipher src key crypt = let str = String.uppercase src in let key = String.uppercase key in   (* strip out non-letters *) let len = String.length str in let rec aux i j = if j >= len then String.sub str 0 i else if str.[j] >= 'A' && str.[j] <= 'Z' then (str.[i] <- str.[j]; aux (succ i) (succ j)) else aux i (succ j) in let res = aux 0 0 in   let slen = String.length res in let klen = String.length key in   let d = int_of_char in let f = if crypt then fun i -> d res.[i] - d 'A' + d key.[i mod klen] - d 'A' else fun i -> d res.[i] - d key.[i mod klen] + 26 in for i = 0 to pred slen do res.[i] <- char_of_int (d 'A' + (f i) mod 26) done; (res)   let () = let str = "Beware the Jabberwock, my son! The jaws that bite, \ the claws that catch!" in let key = "VIGENERECIPHER" in   let cod = cipher str key true in let dec = cipher cod key false in   Printf.printf "Text: %s\n" str; Printf.printf "key:  %s\n" key; Printf.printf "Code: %s\n" cod; Printf.printf "Back: %s\n" dec; ;;
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.
#Yabasic
Yabasic
clear screen   dim colore$(1)   maxCol = token("white yellow cyan green red", colore$())   showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]") print "\n\n\n" showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")   sub showTree(n, A$) local i, c$ static co   c$ = left$(A$, 1)   if c$ = "" return   switch c$ case "[": co = co + 1 : showTree(n + 1, right$(A$, len(A$) - 1)) break case "]": co = co - 1 : showTree(n - 1, right$(A$, len(A$) - 1)) break default: for i = 2 to n print " "; next i co = max(min(co, maxCol), 1) print color(colore$(co)) "\xc0-", c$ showTree(n, right$(A$, len(A$) - 1)) break end switch end sub  
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.
#zkl
zkl
:Vault.dir() ... Compiler Asm Compiler Dictionary Exception Test UnitTester foo bar ...
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).
#Red
Red
Red []   walk: func [ "Walk a directory tree recursively, setting WORD to each file and evaluating BODY."   'word "For each file, set with the absolute file path." directory [file!] "Starting directory." body [block!] "Block to evaluate for each file, during which WORD is set." /where rules [block!] "Parse rules defining file names to include." ][ foreach file read directory [ if where [if not parse file rules [continue]] either dir? file: rejoin [directory file] [walk item file body] [ set 'word file do body ] ] ]   rules: compose [ any (charset [#"A" - #"Z"]) ".TXT" ]   walk/where file %/home/user/ [print file] rules
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).
#REXX
REXX
/*REXX program shows all files in a directory tree that match a given search criteria.*/ parse arg xdir; if xdir='' then xdir='\' /*Any DIR specified? Then use default.*/ @.=0 /*default result in case ADDRESS fails.*/ dirCmd= 'DIR /b /s' /*the DOS command to do heavy lifting. */ trace off /*suppress REXX error message for fails*/ address system dirCmd xdir with output stem @. /*issue the DOS DIR command with option*/ if rc\==0 then do /*did the DOS DIR command get an error?*/ say '***error!*** from DIR' xDIR /*error message that shows "que pasa". */ say 'return code=' rc /*show the return code from DOS DIR.*/ exit rc /*exit with " " " " " */ end /* [↑] bad ADDRESS cmd (from DOS DIR)*/ #[email protected] /*the number of @. entries generated.*/ if #==0 then #=' no ' /*use a better word choice for 0 (zero)*/ say center('directory ' xdir " has " # ' matching entries.', 79, "─")   do j=1 for #; say @.j /*show all the files that met criteria.*/ end /*j*/ exit @.0+rc /*stick a fork in it, we're all done. */
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.
#Swift
Swift
// Based on this answer from Stack Overflow: // https://stackoverflow.com/a/42821623   func waterCollected(_ heights: [Int]) -> Int { guard heights.count > 0 else { return 0 } var water = 0 var left = 0, right = heights.count - 1 var maxLeft = heights[left], maxRight = heights[right]   while left < right { if heights[left] <= heights[right] { maxLeft = max(heights[left], maxLeft) water += maxLeft - heights[left] left += 1 } else { maxRight = max(heights[right], maxRight) water += maxRight - heights[right] right -= 1 } } return water }   for heights in [[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]] { print("water collected = \(waterCollected(heights))") }
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
#C
C
#include<stdio.h>   typedef struct{ float i,j,k; }Vector;   Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};   float dotProduct(Vector a, Vector b) { return a.i*b.i+a.j*b.j+a.k*b.k; }   Vector crossProduct(Vector a,Vector b) { Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};   return c; }   float scalarTripleProduct(Vector a,Vector b,Vector c) { return dotProduct(a,crossProduct(b,c)); }   Vector vectorTripleProduct(Vector a,Vector b,Vector c) { return crossProduct(a,crossProduct(b,c)); }   void printVector(Vector a) { printf("( %f, %f, %f)",a.i,a.j,a.k); }   int main() { printf("\n a = "); printVector(a); printf("\n b = "); printVector(b); printf("\n c = "); printVector(c); printf("\n a . b = %f",dotProduct(a,b)); printf("\n a x b = "); printVector(crossProduct(a,b)); printf("\n a . (b x c) = %f",scalarTripleProduct(a,b,c)); printf("\n a x (b x c) = "); printVector(vectorTripleProduct(a,b,c));   return 0; }
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
#C.23
C#
using System; using System.Linq; using System.Text.RegularExpressions;   namespace ValidateIsin { public static class IsinValidator { public static bool IsValidIsin(string isin) => IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));   private static readonly Regex IsinRegex = new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled);   private static string Digitize(string isin) => string.Join("", isin.Select(c => $"{DigitValue(c)}"));   private static bool LuhnTest(string number) => number.Reverse().Select(DigitValue).Select(Summand).Sum() % 10 == 0;   private static int Summand(int digit, int i) => digit + (i % 2) * (digit - digit / 5 * 9);   private static int DigitValue(char c) => c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10; }   public class Program { public static void Main() { string[] isins = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" };   foreach (string isin in isins) { string validOrNot = IsinValidator.IsValidIsin(isin) ? "valid" : "not valid"; Console.WriteLine($"{isin} is {validOrNot}"); } } } }
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.
#Vlang
Vlang
fn main() { s := [1, 2, 2, 3, 4, 4, 5]   // There is no output as 'prev' is created anew each time // around the loop and set implicitly to zero. for i := 0; i < s.len; i++ { curr := s[i] mut prev := 0 if i > 0 && curr == prev { println(i) } prev = curr }   // Now 'prev' is created only once and reassigned // each time around the loop producing the desired output. mut prev := 0 for i := 0; i < s.len; i++ { curr := s[i] if i > 0 && curr == prev { println(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.
#Wren
Wren
var s = [1, 2, 2, 3, 4, 4, 5]   // There is no output as 'prev' is created anew each time // around the loop and set implicitly to null. for (i in 0...s.count) { var curr = s[i] var prev if (i > 0 && curr == prev) System.print(i) prev = curr }   // Now 'prev' is created only once and reassigned // each time around the loop producing the desired output. var prev for (i in 0...s.count) { var curr = s[i] if (i > 0 && curr == prev) System.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
#BCPL
BCPL
get "libhdr"   let corput(n, base, num, denom) be $( let p = 0 and q = 1 until n=0 $( p := p * base + n rem base q := q * base n := n / base $)    !num := p  !denom := q   until p=0 $( n := p p := q rem p q := n $)    !num := !num / q  !denom := !denom / q $)   let writefrac(num, denom) be test num=0 do writes(" 0") or writef("  %N/%N", num, denom)   let start() be $( let num = ? and denom = ? for base=2 to 5 $( writef("base %N:", base) for i=0 to 9 $( corput(i, base, @num, @denom) writefrac(num, denom) $) wrch('*N') $) $)
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
#C
C
#include <stdio.h>   void vc(int n, int base, int *num, int *denom) { int p = 0, q = 1;   while (n) { p = p * base + (n % base); q *= base; n /= base; }   *num = p; *denom = q;   while (p) { n = p; p = q % p; q = n; } *num /= q; *denom /= q; }   int main() { int d, n, i, b; for (b = 2; b < 6; b++) { printf("base %d:", b); for (i = 0; i < 10; i++) { vc(i, b, &n, &d); if (n) printf("  %d/%d", n, d); else printf(" 0"); } printf("\n"); }   return 0; }
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
#AppleScript
AppleScript
set x to 1
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program variable.s */   /************************************/ /* Constantes Définition */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*********************************/ /* 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 iPointer1: .int 0x4000 @ 4 bytes value hexa @ or iPointer2: .word 0x4000 @ 4 bytes value hexa iPointer3: .int 04000 @ 4 bytes value octal   TabInteger4: .int 5,4,3,2 @ Area of 4 integers = 4 * 4 = 16 bytes   iDoubleInt1: .quad 0xFFFFFFFFFFFFFFFF @ 8 bytes   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 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdriInteger2 @ load variable address mov r1,#100 str r1,[r0] @ init variable iInteger2   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdriInteger2: .int 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.
#Arturo
Arturo
Max: 1000 a: array.of: Max 0   loop 0..Max-2 'n [ if 0 =< n-1 [ loop (n-1)..0 'm [ if a\[m]=a\[n] [ a\[n+1]: n-m break ] ] ] ]   print "The first ten terms of the Van Eck sequence are:" print first.n:10 a   print "" print "Terms 991 to 1000 of the sequence are:" print last.n:10 a
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.
#AWK
AWK
  # syntax: GAWK -f VAN_ECK_SEQUENCE.AWK # converted from Go BEGIN { limit = 1000 for (i=0; i<limit; i++) { arr[i] = 0 } for (n=0; n<limit-1; n++) { for (m=n-1; m>=0; m--) { if (arr[m] == arr[n]) { arr[n+1] = n - m break } } } printf("terms 1-10:") for (i=0; i<10; i++) { printf(" %d",arr[i]) } printf("\n") printf("terms 991-1000:") for (i=990; i<1000; i++) { printf(" %d",arr[i]) } printf("\n") exit(0) }  
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
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   auto fangs(in long n) pure nothrow @safe { auto pairs = iota(2, cast(int)(n ^^ 0.5)) // n.isqrt .filter!(x => !(n % x)).map!(x => [x, n / x]); enum dLen = (in long x) => x.text.length; immutable half = dLen(n) / 2; enum halvesQ = (long[] p) => p.all!(u => dLen(u) == half); enum digits = (long[] p) => dtext(p[0], p[1]).dup.sort(); const dn = n.to!(dchar[]).sort(); return tuple(n, pairs.filter!(p => halvesQ(p) && dn == digits(p))); }   void main() { foreach (v; int.max.iota.map!fangs.filter!q{ !a[1].empty } .take(25).chain([16758243290880, 24959017348650, 14593825548650].map!fangs)) writefln("%d: (%(%(%s %)) (%))", v[]); }
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.
#Ruby
Ruby
[0x200000, 0x1fffff].each do |i| # Encode i => BER ber = [i].pack("w") hex = ber.unpack("C*").collect {|c| "%02x" % c}.join(":") printf "%s => %s\n", i, hex   # Decode BER => j j = ber.unpack("w").first i == j or fail "BER not preserve integer" end
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.
#Scala
Scala
object VlqCode { def encode(x:Long)={ val result=scala.collection.mutable.Stack[Byte]() result push (x&0x7f).toByte var l = x >>> 7 while(l>0){ result push ((l&0x7f)|0x80).toByte l >>>= 7 } result.toArray }   def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f)   def toString(a:Array[Byte])=a map("%02x".format(_)) mkString("[", ", ", "]")   def test(x:Long)={ val enc=encode(x) println("0x%x => %s => 0x%x".format(x, toString(enc), decode(enc))) }   def main(args: Array[String]): Unit = { val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000, 0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL) xs foreach test } }
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
#Euler_Math_Toolbox
Euler Math Toolbox
  >function allargs () ... $ loop 1 to argn(); $ args(#), $ end $endfunction >allargs(1,3,"Test",1:2) 1 3 Test [ 1 2 ] >function args test (x) := {x,x^2,x^3} >allargs(test(4)) 4 16 64  
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
#Euphoria
Euphoria
procedure print_args(sequence args) for i = 1 to length(args) do puts(1,args[i]) puts(1,' ') end for end procedure   print_args({"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
#Lasso
Lasso
local( mystring = 'Hello World', myarray = array('one', 'two', 3), myinteger = 1234 )   // size of a string will be a character count #mystring -> size '<br />'   // size of an array or map will be a count of elements #myarray -> size '<br />'   // elements within an array can report size #myarray -> get(2) -> size '<br />'   // integers or decimals does not have sizes //#myinteger -> size // will fail // an integer can however be converted to a string first string(#myinteger) -> size
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Lua
Lua
> s = "hello" > print(#s) 5 > t = { 1,2,3,4,5 } > print(#t) 5
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ByteCount["somerandomstring"]
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Modula-3
Modula-3
MODULE Size EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Int;   BEGIN Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n"); Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n"); END Size.
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
#Nanoquery
Nanoquery
class Vector declare x declare y   def Vector(x, y) this.x = float(x) this.y = float(y) end   def operator+(other) return new(Vector, this.x + other.x, this.y + other.y) end   def operator-(other) return new(Vector, this.x - other.x, this.y - other.y) end   def operator/(val) return new(Vector, this.x / val, this.y / val) end   def operator*(val) return new(Vector, this.x * val, this.y * val) end   def toString() return format("[%s, %s]", this.x, this.y) end end   println new(Vector, 5, 7) + new(Vector, 2, 3) println new(Vector, 5, 7) - new(Vector, 2, 3) println new(Vector, 5, 7) * 11 println new(Vector, 5, 7) / 2
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
#Nim
Nim
import strformat   type Vec2[T: SomeNumber] = tuple[x, y: T]   proc initVec2[T](x, y: T): Vec2[T] = (x, y)   func`+`[T](a, b: Vec2[T]): Vec2[T] = (a.x + b.x, a.y + b.y)   func `-`[T](a, b: Vec2[T]): Vec2[T] = (a.x - b.x, a.y - b.y)   func `*`[T](a: Vec2[T]; m: T): Vec2[T] = (a.x * m, a.y * m)   func `/`[T](a: Vec2[T]; d: T): Vec2[T] = if d == 0: raise newException(DivByZeroDefect, "division of vector by 0") when T is SomeInteger: (a.x div d, a.y div d) else: (a.x / d, a.y / d)   func `$`[T](a: Vec2[T]): string = &"({a.x}, {a.y})"   # Three ways to initialize a vector. let v1 = initVec2(2, 3) let v2: Vec2[int] = (-1, 2) let v3 = (x: 4, y: -2)   echo &"{v1} + {v2} = {v1 + v2}" echo &"{v3} - {v2} = {v3 - v2}"   # Float vectors. let v4 = initVec2(2.0, 3.0) let v5 = (x: 3.0, y: 2.0)   echo &"{v4} * 2 = {v4 * 2}" echo &"{v3} / 2 = {v3 / 2}" # Int division. echo &"{v5} / 2 = {v5 / 2}" # Float division.
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
#ooRexx
ooRexx
/* Rexx */ Do alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' key = 'LEMON'   pt = 'Attack at dawn!' Call test key, pt   key = 'N' Call test key, pt   key = 'B' Call test key, pt   pt = alpha key = 'A' Call test key, pt   pt = sampledata() key = 'Hamlet; Prince of Denmark' Call test key, pt   Return End Exit   vigenere: Procedure Expose alpha Do Parse upper Arg meth, key, text   Select When 'ENCIPHER'~abbrev(meth, 1) = 1 then df = 1 When 'DECIPHER'~abbrev(meth, 1) = 1 then df = -1 Otherwise Do Say meth 'invalid. Must be "ENCIPHER" or "DECIPHER"' Exit End End   text = stringscrubber(text) key = stringscrubber(key) code = ''   Do 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   Return End Exit   vigenere_encipher: Procedure Expose alpha Do Parse upper Arg key, plaintext   Return vigenere('ENCIPHER', key, plaintext) End Exit   vigenere_decipher: Procedure Expose alpha Do Parse upper Arg key, ciphertext   Return vigenere('DECIPHER', key, ciphertext) End Exit   mod: Procedure Do Parse Arg N, D   Return (D + (N // D)) // D End Exit   stringscrubber: Procedure Expose alpha Do Parse upper Arg cleanup   cleanup = cleanup~space(0) Do label f_ forever x_ = cleanup~verify(alpha) If x_ = 0 then Leave f_ cleanup = cleanup~changestr(cleanup~substr(x_, 1), '') end f_   Return cleanup End Exit   test: Procedure Expose alpha Do Parse Arg key, pt   ct = vigenere_encipher(key, pt) Call display ct dt = vigenere_decipher(key, ct) Call display dt   Return End Exit   display: Procedure Do Parse Arg text   line = '' o_ = 0 Do 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) Do label l_ forever Parse Var 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 End Exit   sampledata: Procedure Do   NL = '0a'x X = 0 antic_disposition. = '' X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To be, or not to be--that is the question:" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Whether 'tis nobler in the mind to suffer" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The slings and arrows of outrageous fortune" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Or to take arms against a sea of troubles" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And by opposing end them. To die, to sleep--" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "No more--and by a sleep to say we end" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The heartache, and the thousand natural shocks" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That flesh is heir to. 'Tis a consummation" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Devoutly to be wished. To die, to sleep--" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To sleep--perchance to dream: ay, there's the rub," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "For in that sleep of death what dreams may come" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "When we have shuffled off this mortal coil," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Must give us pause. There's the respect" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That makes calamity of so long life." X = X + 1; antic_disposition.0 = X; antic_disposition.X = "For who would bear the whips and scorns of time," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Th' oppressor's wrong, the proud man's contumely" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The pangs of despised love, the law's delay," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The insolence of office, and the spurns" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That patient merit of th' unworthy takes," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "When he himself might his quietus make" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "With a bare bodkin? Who would fardels bear," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To grunt and sweat under a weary life," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "But that the dread of something after death," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The undiscovered country, from whose bourn" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "No traveller returns, puzzles the will," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And makes us rather bear those ills we have" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Than fly to others that we know not of?" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Thus conscience does make cowards of us all," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And thus the native hue of resolution" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Is sicklied o'er with the pale cast of thought," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And enterprise of great pith and moment" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "With this regard their currents turn awry" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And lose the name of action. -- Soft you now," X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The fair Ophelia! -- Nymph, in thy orisons" X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Be all my sins remembered."   melancholy_dane = '' Do l_ = 1 for antic_disposition.0 melancholy_dane = melancholy_dane || antic_disposition.l_ || NL End l_   Return melancholy_dane End Exit  
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.
#PHP
PHP
  <?php   function printTree( array $tree , string $key = "." , string $stack = "" , $first = TRUE , $firstPadding = NULL ) { if ( gettype($tree) == "array" ) { if($firstPadding === NULL) $firstPadding = ( count($tree)>1 ) ? "│ " : " " ; echo $key . PHP_EOL ; foreach ($tree as $key => $value) { if ($key === array_key_last($tree)){ echo (($first) ? "" : $firstPadding ) . $stack . "└── "; $padding = " "; if($first) $firstPadding = " "; } else { echo (($first) ? "" : $firstPadding ) . $stack . "├── "; $padding = "│ "; } if( is_array($value) )printTree( $value , $key , $stack . (($first) ? "" : $padding ) , FALSE , $firstPadding ); else echo $key . " -> " . $value . PHP_EOL; } } else echo $tree . PHP_EOL; }       // ---------------------------------------TESTING FUNCTION-------------------------------------     $sample_array_1 = [ 0 => [ 'item_id' => 6, 'price' => "2311.00", 'qty' => 12, 'discount' => 0 ], 1 => [ 'item_id' => 7, 'price' => "1231.00", 'qty' => 1, 'discount' => 12 ], 2 => [ 'item_id' => 8, 'price' => "123896.00", 'qty' => 0, 'discount' => 24 ] ]; $sample_array_2 = array( array( "name"=>"John", "lastname"=>"Doe", "country"=>"Japan", "nationality"=>"Japanese", "job"=>"web developer", "hobbies"=>array( "sports"=>"soccer", "others"=>array( "freetime"=>"watching Tv" ) )   ) ); $sample_array_3 = [ "root" => [ "first_depth_node1" =>[ "second_depth_node1", "second_depth_node2" => [ "third_depth_node1" , "third_depth_node2" , "third_depth_node3" => [ "fourth_depth_node1", "fourth_depth_node2", ] ], "second_depth_node3", ] , "first_depth_node2" => [ "second_depth_node4" => [ "third_depth_node3" => [1]] ] ] ]; $sample_array_4 = []; $sample_array_5 = ["1"]; $sample_array_5 = ["1"]; $sample_array_6 = [ "T", "Ta", "Tad", "Tada", "Tadav", "Tadavo", "Tadavom", "Tadavomn", "Tadavomni", "Tadavomnis", "TadavomnisT", ];     printTree($sample_array_1); echo PHP_EOL . "------------------------------" . PHP_EOL; printTree($sample_array_2); echo PHP_EOL . "------------------------------" . PHP_EOL; printTree($sample_array_3); echo PHP_EOL . "------------------------------" . PHP_EOL; printTree($sample_array_4); echo PHP_EOL . "------------------------------" . PHP_EOL; printTree($sample_array_5); echo PHP_EOL . "------------------------------" . PHP_EOL; printTree($sample_array_6);     ?>  
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).
#Ring
Ring
  see "Testing DIR() " + nl mylist = dir("C:\Ring") for x in mylist if x[2] see "Directory : " + x[1] + nl else see "File : " + x[1] + nl ok next see "Files count : " + len(mylist)  
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).
#Ruby
Ruby
require 'find'   Find.find('/your/path') do |f| # print file and path to screen if filename ends in ".mp3" puts f if f.match(/\.mp3\Z/) end
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.
#Tailspin
Tailspin
  templates histogramWater $ -> \( @: 0"1"; [$... -> { leftMax: $ -> #, value: ($)"1" } ] ! when <$@..> do @: $; $ ! otherwise $@ ! \) -> \( @: { rightMax: 0"1", sum: 0"1" }; $(last..1:-1)... -> # [email protected] ! when <{ value: <[email protected]..> }> do @.rightMax: $.value; when <{ value: <$.leftMax..> }> do !VOID when <{ leftMax: <[email protected]>}> do @.sum: [email protected] + $.leftMax - $.value; otherwise @.sum: [email protected] + [email protected] - $.value; \) ! end histogramWater   [[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]]... -> '$ -> histogramWater; water in $;$#10;' -> !OUT::write  
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
#C.23
C#
using System; using System.Windows.Media.Media3D;   class VectorProducts { static double ScalarTripleProduct(Vector3D a, Vector3D b, Vector3D c) { return Vector3D.DotProduct(a, Vector3D.CrossProduct(b, c)); }   static Vector3D VectorTripleProduct(Vector3D a, Vector3D b, Vector3D c) { return Vector3D.CrossProduct(a, Vector3D.CrossProduct(b, c)); }   static void Main() { var a = new Vector3D(3, 4, 5); var b = new Vector3D(4, 3, 5); var c = new Vector3D(-5, -12, -13);   Console.WriteLine(Vector3D.DotProduct(a, b)); Console.WriteLine(Vector3D.CrossProduct(a, b)); Console.WriteLine(ScalarTripleProduct(a, b, c)); Console.WriteLine(VectorTripleProduct(a, b, c)); } }
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
#C.2B.2B
C++
    #include <string> #include <regex> #include <algorithm> #include <numeric> #include <sstream>   bool CheckFormat(const std::string& isin) { std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); std::smatch match; return std::regex_match(isin, match, isinRegEpx); }   std::string CodeISIN(const std::string& isin) { std::string coded; int offset = 'A' - 10; for (auto ch : isin) { if (ch >= 'A' && ch <= 'Z') { std::stringstream ss; ss << static_cast<int>(ch) - offset; coded += ss.str(); } else { coded.push_back(ch); } }   return std::move(coded); }   bool CkeckISIN(const std::string& isin) { if (!CheckFormat(isin)) return false;   std::string coded = CodeISIN(isin); // from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.2B.2B11 return luhn(coded); }     #include <iomanip> #include <iostream>   int main() { std::string isins[] = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" }; for (const auto& isin : isins) { std::cout << isin << std::boolalpha << " - " << CkeckISIN(isin) <<std::endl; } return 0; }  
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
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace VanDerCorput { /// <summary> /// Computes the Van der Corput sequence for any number base. /// The numbers in the sequence vary from zero to one, including zero but excluding one. /// The sequence possesses low discrepancy. /// Here are the first ten terms for bases 2 to 5: /// /// base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16 /// base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27 /// base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8 /// base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 /// </summary> /// <see cref="http://rosettacode.org/wiki/Van_der_Corput_sequence"/> public class VanDerCorputSequence: IEnumerable<Tuple<long,long>> { /// <summary> /// Number base for the sequence, which must bwe two or more. /// </summary> public int Base { get; private set; }   /// <summary> /// Maximum number of terms to be returned by iterator. /// </summary> public long Count { get; private set; }   /// <summary> /// Construct a sequence for the given base. /// </summary> /// <param name="iBase">Number base for the sequence.</param> /// <param name="count">Maximum number of items to be returned by the iterator.</param> public VanDerCorputSequence(int iBase, long count = long.MaxValue) { if (iBase < 2) throw new ArgumentOutOfRangeException("iBase", "must be two or greater, not the given value of " + iBase); Base = iBase; Count = count; }   /// <summary> /// Compute nth term in the Van der Corput sequence for the base specified in the constructor. /// </summary> /// <param name="n">The position in the sequence, which may be zero or any positive number.</param> /// This number is always an integral power of the base.</param> /// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns> public Tuple<long,long> Compute(long n) { long p = 0, q = 1; long numerator, denominator; while (n != 0) { p = p * Base + (n % Base); q *= Base; n /= Base; } numerator = p; denominator = q; while (p != 0) { n = p; p = q % p; q = n; } numerator /= q; denominator /= q; return new Tuple<long,long>(numerator, denominator); }   /// <summary> /// Compute nth term in the Van der Corput sequence for the given base. /// </summary> /// <param name="iBase">Base to use for the sequence.</param> /// <param name="n">The position in the sequence, which may be zero or any positive number.</param> /// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns> public static Tuple<long, long> Compute(int iBase, long n) { var seq = new VanDerCorputSequence(iBase); return seq.Compute(n); }   /// <summary> /// Iterate over the Van Der Corput sequence. /// The first value in the sequence is always zero, regardless of the base. /// </summary> /// <returns>A tuple whose items are the Van der Corput value given as a numerator and denominator.</returns> public IEnumerator<Tuple<long, long>> GetEnumerator() { long iSequenceIndex = 0L; while (iSequenceIndex < Count) { yield return Compute(iSequenceIndex); iSequenceIndex++; } }   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } }   class Program { static void Main(string[] args) { TestBasesTwoThroughFive();   Console.WriteLine("Type return to continue..."); Console.ReadLine(); }   static void TestBasesTwoThroughFive() { foreach (var seq in Enumerable.Range(2, 5).Select(x => new VanDerCorputSequence(x, 10))) // Just the first 10 elements of the each sequence { Console.Write("base " + seq.Base + ":"); foreach(var vc in seq) Console.Write(" " + vc.Item1 + "/" + vc.Item2); Console.WriteLine(); } } } }    
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
#Arturo
Arturo
num: 10 str: "hello world"   arrA: [1 2 3] arrB: ["one" "two" "three"] arrC: [1 "two" [3 4 5]] arrD: ["one" true [ print "something" ]]   dict: [ name: "john" surname: "doe" function: $[][ print "do sth" ] ]   inspect symbols
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.
#BASIC
BASIC
10 DEFINT A-Z 20 DIM E(1000) 30 FOR I=0 TO 999 40 FOR J=I-1 TO 0 STEP -1 50 IF E(J)=E(I) THEN E(I+1)=I-J: GOTO 80 60 NEXT J 70 E(I+1)=0 80 NEXT I 90 FOR I=0 TO 9: PRINT E(I);: NEXT 95 PRINT 100 FOR I=990 TO 999: PRINT E(I);: NEXT
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.
#BCPL
BCPL
get "libhdr"   let start() be $( let eck = vec 999   for i = 0 to 999 do eck!i := 0 for i = 0 to 998 do for j = i-1 to 0 by -1 do if eck!i = eck!j then $( eck!(i+1) := i-j break $)   for i = 0 to 9 do writed(eck!i, 4) wrch('*N') for i = 990 to 999 do writed(eck!i, 4) wrch('*N') $)
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
#Eiffel
Eiffel
  class APPLICATION   create make   feature   fang_check (original, fang1, fang2: INTEGER_64): BOOLEAN -- Are 'fang1' and 'fang2' correct fangs of the 'original' number? require original_positive: original > 0 fangs_positive: fang1 > 0 and fang2 > 0 local original_length: INTEGER fang, ori: STRING sort_ori, sort_fang: SORTED_TWO_WAY_LIST [CHARACTER] do create sort_ori.make create sort_fang.make create ori.make_empty create fang.make_empty original_length := original.out.count // 2 if fang1.out.count /= original_length or fang2.out.count /= (original_length) then Result := False elseif fang1.out.ends_with ("0") and fang2.out.ends_with ("0") then Result := False else across 1 |..| original.out.count as c loop sort_ori.extend (original.out [c.item]) end across sort_ori as o loop ori.extend (o.item) end across 1 |..| fang1.out.count as c loop sort_fang.extend (fang1.out [c.item]) sort_fang.extend (fang2.out [c.item]) end across sort_fang as f loop fang.extend (f.item) end Result := fang.same_string (ori) end ensure fangs_right_length: Result implies original.out.count = fang1.out.count + fang2.out.count end   make -- Uses fang_check to find vampire nubmers. local i, numbers: INTEGER fang1, fang2: INTEGER_64 num: ARRAY [INTEGER_64] math: DOUBLE_MATH do create math from i := 1000 until numbers > 25 loop if i.out.count \\ 2 = 0 then from fang1 := 10 until fang1 >= math.sqrt (i) loop if (i \\ fang1 = 0) then fang2 := i // fang1 if i \\ 9 = (fang1 + fang2) \\ 9 then if fang1 * fang2 = i and fang1 <= fang2 and then fang_check (i, fang1, fang2) then numbers := numbers + 1 io.put_string (i.out + ": " + fang1.out + " " + fang2.out) io.new_line end end end fang1 := fang1 + 1 end end i := i + 1 end num := <<16758243290880, 24959017348650, 14593825548650>> across num as n loop from fang1 := 1000000 until fang1 >= math.sqrt (n.item) + 1 loop if (n.item \\ fang1 = 0) then fang2 := (n.item // fang1) if fang1 * fang2 = n.item and fang1 <= fang2 and then fang_check (n.item, fang1, fang2) then io.put_string (n.item.out + ": " + fang1.out + " " + fang2.out + "%N") end end fang1 := fang1 + 1 end end end   end  
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func string: toSequence (in var bigInteger: number) is func result var string: sequence is ""; begin sequence := str(chr(ord(number mod 128_))); number >>:= 7; while number <> 0_ do sequence := str(chr(ord(number mod 128_) + 128)) & sequence; number >>:= 7; end while; end func;   const func bigInteger: fromSequence (in string: sequence) is func result var bigInteger: number is 0_; local var integer: index is 1; begin while ord(sequence[index]) >= 128 do number <<:= 7; number +:= bigInteger conv (ord(sequence[index]) - 128); incr(index); end while; number <<:= 7; number +:= bigInteger conv ord(sequence[index]); end func;   const proc: main is func local const array bigInteger: testValues is [] ( 0_, 10_, 123_, 254_, 255_, 256_, 257_, 65534_, 65535_, 65536_, 65537_, 2097151_, 2097152_); var string: sequence is ""; var bigInteger: testValue is 0_; var char: element is ' '; begin for testValue range testValues do sequence := toSequence(testValue); write("sequence from " <& testValue <& ": [ "); for element range sequence do write(ord(element) radix 16 lpad0 2 <& " "); end for; writeln("] back: " <& fromSequence(sequence)); end for; end func;
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.
#Sidef
Sidef
func vlq_encode(num) { var t = (0x7F & num) var str = t.chr while (num >>= 7) { t = (0x7F & num) str += chr(0x80 | t) } str.reverse }   func vlq_decode(str) { var num = '' str.each_byte { |b| num += ('%07b' % (b & 0x7F)) } Num(num, 2) }   var tests = [0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000]   tests.each { |t| var vlq = vlq_encode(t) printf("%8s %12s %8s\n", t, vlq.bytes.join(':', { "%02X" % _ }), vlq_decode(vlq)) }
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
#Factor
Factor
MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;
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
#Forth
Forth
: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ; 4 3 2 1 4 sum . \ 10
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Nim
Nim
echo "An int contains ", sizeof(int), " bytes."
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#NS-HUBASIC
NS-HUBASIC
10 PRINT LEN(VARIABLE$)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#OCaml
OCaml
(** The result is the size given in word. The word size in octet can be found with (Sys.word_size / 8). (The size of all the datas in OCaml is at least one word, even chars and bools.) *) let sizeof v = let rec rec_size d r = if List.memq r d then (1, d) else if not(Obj.is_block r) then (1, r::d) else if (Obj.tag r) = (Obj.double_tag) then (2, r::d) else if (Obj.tag r) = (Obj.string_tag) then (Obj.size r, r::d) else if (Obj.tag r) = (Obj.object_tag) || (Obj.tag r) = (Obj.closure_tag) then invalid_arg "please only provide datas" else let len = Obj.size r in let rec aux d sum i = if i >= len then (sum, r::d) else let this = Obj.field r i in let this_size, d = rec_size d this in aux d (sum + this_size) (i+1) in aux d (1) 0 in fst(rec_size [] (Obj.repr v)) ;;
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
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Sub(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Mult(11)->ToString()->PrintLine(); Vec2->New(5, 7)->Div(2)->ToString()->PrintLine(); } }   class Vec2 { @x : Float; @y : Float;   New(x : Float, y : Float) { @x := x; @y := y; }   method : GetX() ~ Float { return @x; }   method : GetY() ~ Float { return @y; }   method : public : Add(v : Vec2) ~ Vec2 { return Vec2->New(@x + v->GetX(), @y + v->GetY()); }   method : public : Sub(v : Vec2) ~ Vec2 { return Vec2->New(@x - v->GetX(), @y - v->GetY()); }   method : public : Div(val : Float) ~ Vec2 { return Vec2->New(@x / val, @y / val); }   method : public : Mult(val : Float) ~ Vec2 { return Vec2->New(@x * val, @y * val); }   method : public : ToString() ~ String { return "[{$@x}, {$@y}]"; } }
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
#Pascal
Pascal
  // The Vigenere cipher in reasonably standard Pascal // <no library functions: all conversions hand-coded> PROGRAM Vigenere;   // get a letter's alphabetic position (A=0) FUNCTION letternum(letter: CHAR): BYTE; BEGIN letternum := (ord(letter)-ord('A')); END;   // convert a character to uppercase FUNCTION uch(ch: CHAR): CHAR; BEGIN uch := ch; IF ch IN ['a'..'z'] THEN uch := chr(ord(ch) AND $5F); END;   // convert a string to uppercase FUNCTION ucase(str: STRING): STRING; VAR i: BYTE; BEGIN ucase := ''; FOR i := 1 TO Length(str) DO ucase := ucase + uch(str[i]); END;   // construct a Vigenere-compatible string: // uppercase; no spaces or punctuation. FUNCTION vstr(pt: STRING): STRING; VAR c: Cardinal; s: STRING; BEGIN vstr:= ''; s := ucase(pt); FOR c := 1 TO Length(s) DO BEGIN IF s[c] IN ['A'..'Z'] THEN vstr += s[c]; END; END;   // construct a repeating Vigenere key FUNCTION vkey(pt, key: STRING): STRING; VAR c,n: Cardinal; k : STRING; BEGIN k := vstr(key); vkey := ''; FOR c := 1 TO Length(pt) DO BEGIN n := c mod Length(k); IF n>0 THEN vkey += k[n] ELSE vkey += k[Length(k)]; END; END;   // Vigenere encipher FUNCTION enVig(pt,key:STRING): STRING; VAR ct: STRING; c,n : Cardinal; BEGIN ct := pt; FOR c := 1 TO Length(pt) DO BEGIN n := letternum(pt[c])+letternum(key[c]); n := n mod 26; ct[c]:=chr(ord('A')+n); END; enVig := ct; END;   // Vigenere decipher FUNCTION deVig(ct,key:STRING): STRING; VAR pt : STRING; c,n : INTEGER; BEGIN pt := ct; FOR c := 1 TO Length(ct) DO BEGIN n := letternum(ct[c])-letternum(key[c]); IF n<0 THEN n:=26+n; pt[c]:=chr(ord('A')+n); END; deVig := pt; END;     VAR key: STRING = 'Vigenere cipher'; msg: STRING = 'Beware the Jabberwock! The jaws that bite, the claws that catch!'; vtx: STRING = ''; ctx: STRING = ''; ptx: STRING = '';   BEGIN // make Vigenere-compatible vtx := vstr(msg); key := vkey(vtx,key); // Vigenere encipher / decipher ctx := enVig(vtx,key); ptx := deVig(ctx,key); // display results Writeln('Message  : ',msg); Writeln('Plaintext  : ',vtx); Writeln('Key  : ',key); Writeln('Ciphertext  : ',ctx); Writeln('Plaintext  : ',ptx); END.    
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).
#Rust
Rust
#![feature(fs_walk)]   use std::fs; use std::path::Path;   fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
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).
#Scala
Scala
import java.io.File   object `package` { def walkTree(file: File): Iterable[File] = { val children = new Iterable[File] { def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty } Seq(file) ++: children.flatMap(walkTree(_)) } }   object Test extends App { val dir = new File("/home/user") for(f <- walkTree(dir)) println(f) for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f) }
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.
#Tcl
Tcl
namespace path {::tcl::mathfunc ::tcl::mathop}   proc flood {ground} { set lefts [ set d 0 lmap g $ground { set d [max $d $g] } ] set ground [lreverse $ground] set rights [ set d 0 lmap g $ground { set d [max $d $g] } ] set rights [lreverse $rights] set ground [lreverse $ground] set water [lmap l $lefts r $rights {min $l $r}] set depths [lmap g $ground w $water {- $w $g}] + {*}$depths }   foreach p { {5 3 7 2 6 4 5 9 1 2} {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} } { puts [flood $p]:\t$p }
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
#C.2B.2B
C++
#include <iostream>   template< class T > class D3Vector {   template< class U > friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ;   public : D3Vector( T a , T b , T c ) { x = a ; y = b ; z = c ; }   T dotproduct ( const D3Vector & rhs ) { T scalar = x * rhs.x + y * rhs.y + z * rhs.z ; return scalar ; }   D3Vector crossproduct ( const D3Vector & rhs ) { T a = y * rhs.z - z * rhs.y ; T b = z * rhs.x - x * rhs.z ; T c = x * rhs.y - y * rhs.x ; D3Vector product( a , b , c ) ; return product ; }   D3Vector triplevec( D3Vector & a , D3Vector & b ) { return crossproduct ( a.crossproduct( b ) ) ; }   T triplescal( D3Vector & a, D3Vector & b ) { return dotproduct( a.crossproduct( b ) ) ; }   private : T x , y , z ; } ;   template< class T > std::ostream & operator<< ( std::ostream & os , const D3Vector<T> & vec ) { os << "( " << vec.x << " , " << vec.y << " , " << vec.z << " )" ; return os ; }   int main( ) { D3Vector<int> a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ; std::cout << "a . b : " << a.dotproduct( b ) << "\n" ; std::cout << "a x b : " << a.crossproduct( b ) << "\n" ; std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ; std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ; return 0 ; }
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
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Utils.Check [ Abstract ] {   ClassMethod ISIN(x As %String) As %Boolean { // https://en.wikipedia.org/wiki/International_Securities_Identification_Number IF x'?2U9UN1N QUIT 0 SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1) FOR i=1:1 { SET n=$EXTRACT(x,i) IF n="" QUIT IF n'=+n SET $EXTRACT(x,i)=$CASE(n,"*":36,"@":37,"#":38,:$ASCII(n)-55) } // call into luhn check, appending check digit QUIT ..Luhn(x_cd) }   ClassMethod Luhn(x As %String) As %Boolean { // https://www.simple-talk.com/sql/t-sql-programming/calculating-and-verifying-check-digits-in-t-sql/ SET x=$TRANSLATE(x," "), cd=$EXTRACT(x,*) SET x=$REVERSE($EXTRACT(x,1,*-1)), t=0 FOR i=1:1:$LENGTH(x) { SET n=$EXTRACT(x,i) IF i#2 SET n=n*2 IF $LENGTH(n)>1 SET n=$EXTRACT(n,1)+$EXTRACT(n,2) SET t=t+n } QUIT cd=((t*9)#10) }   }
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
#Clojure
Clojure
(defn luhn? [cc] (let [sum (->> cc (map #(Character/digit ^char % 10)) reverse (map * (cycle [1 2])) (map #(+ (quot % 10) (mod % 10))) (reduce +))] (zero? (mod sum 10))))   (defn is-valid-isin? [isin] (and (re-matches #"^[A-Z]{2}[A-Z0-9]{9}[0-9]$" isin) (->> isin (map #(Character/digit ^char % 36)) (apply str) luhn?)))   (use 'clojure.pprint) (doseq [isin ["US0378331005" "US0373831005" "U50378331005" "US03378331005" "AU0000XVGZA3" "AU0000VXGZA3" "FR0000988040"]] (cl-format *out* "~A: ~:[invalid~;valid~]~%" isin (is-valid-isin? isin)))  
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
#C.2B.2B
C++
#include <cmath> #include <iostream>   double vdc(int n, double base = 2) { double vdc = 0, denom = 1; while (n) { vdc += fmod(n, base) / (denom *= base); n /= base; // note: conversion from 'double' to 'int' } return vdc; }   int main() { for (double base = 2; base < 6; ++base) { std::cout << "Base " << base << "\n"; for (int n = 0; n < 10; ++n) { std::cout << vdc(n, base) << " "; } std::cout << "\n\n"; } }
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Ada
Ada
with Ada.Text_IO;   with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables;   procedure URL_Parser is   procedure Parse (URL : in String) is   use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables;   procedure Put_Cond (Item  : in String; Value  : in String; When_Not : in String := "") is begin if Value /= When_Not then Put (" "); Put (Item); Put_Line (Value); end if; end Put_Cond;   Obj  : Object; List : Table_Type; begin Put_Line ("Parsing " & URL);   Obj  := Parse (URL); List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj)));   Put_Cond ("Scheme: ", Protocol_Name (Obj)); Put_Cond ("Domain: ", Host (Obj)); Put_Cond ("Port: ", Port (Obj), When_Not => "0"); Put_Cond ("Path: ", Path (Obj)); Put_Cond ("File: ", File (Obj)); Put_Cond ("Query: ", Query (Obj)); Put_Cond ("Fragment: ", Fragment (Obj)); Put_Cond ("User: ", User (Obj)); Put_Cond ("Password: ", Password (Obj));   if List.Count /= 0 then Put_Line (" Parameters:"); end if; for Index in 1 .. List.Count loop Put (" "); Put (Get_Name (List, N => Index)); Put (" "); Put ("'" & Get_Value (List, N => Index) & "'"); New_Line; end loop; New_Line; end Parse;   begin Parse ("foo://example.com:8042/over/there?name=ferret#nose"); Parse ("urn:example:animal:ferret:nose"); Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"); Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt"); Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1"); Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"); Parse ("mailto:[email protected]"); Parse ("news:comp.infosystems.www.servers.unix"); Parse ("tel:+1-816-555-1212"); Parse ("telnet://192.0.2.16:80/"); Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); Parse ("ssh://[email protected]"); Parse ("https://bob:[email protected]/place"); Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"); end URL_Parser;
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#11l
11l
F url_encode(s) V r = ‘’ V buf = ‘’   F flush_buf() // this function is needed because strings in 11l are UTF-16 encoded I @buf != ‘’ V bytes = @buf.encode(‘utf-8’) L(b) bytes @r ‘’= ‘%’hex(b).zfill(2) @buf = ‘’   L(c) s I c C (‘0’..‘9’, ‘a’..‘z’, ‘A’..‘Z’, ‘_’, ‘.’, ‘-’, ‘~’) flush_buf() r ‘’= c E buf ‘’= c   flush_buf() R r   print(url_encode(‘http://foo bar/’)) print(url_encode(‘https://ru.wikipedia.org/wiki/Транспайлер’))
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
#AutoHotkey
AutoHotkey
x = hello ; assign verbatim as a string z := 3 + 4 ; assign an expression if !y ; uninitialized variables are assumed to be 0 or "" (blank string) Msgbox %x% ; variable dereferencing is done by surrounding '%' signs fx() { local x ; variable default scope in a function is local anyways global y ; static z=4 ; initialized once, then value is remembered between function calls }
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
#AWK
AWK
BEGIN { # Variables are dynamically typecast, and do not need declaration prior to use: fruit = "banana" # create a variable, and fill it with a string a = 1 # create a variable, and fill it with a numeric value a = "apple" # re-use the above variable for a string print a, fruit   # Multiple assignments are possible from within a single statement: x = y = z = 3 print "x,y,z:", x,y,z   # "dynamically typecast" means the content of a variable is used # as needed by the current operation, e.g. for a calculation: a = "1" b = "2banana" c = "3*4"   print "a,b,c=",a,b,c, "c+0=", c+0, 0+c print "a+b=", a+b, "b+c=", b+c }
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.
#BQN
BQN
EckStep ← ⊢∾(⊑⊑∘⌽∊1↓⌽)◶(0˙)‿((⊑1+⊑⊐˜ 1↓⊢)⌽) Eck ← {(EckStep⍟(𝕩-1))⥊0} (Eck 10)≍990↓Eck 1000
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.
#C
C
#include <stdlib.h> #include <stdio.h>   int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } }   printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n');   return 0; }
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
#Elixir
Elixir
defmodule Vampire do def factor_pairs(n) do first = trunc(n / :math.pow(10, div(char_len(n), 2))) last = :math.sqrt(n) |> round for i <- first .. last, rem(n, i) == 0, do: {i, div(n, i)} end   def vampire_factors(n) do if rem(char_len(n), 2) == 1 do [] else half = div(length(to_char_list(n)), 2) sorted = Enum.sort(String.codepoints("#{n}")) Enum.filter(factor_pairs(n), fn {a, b} -> char_len(a) == half && char_len(b) == half && Enum.count([a, b], fn x -> rem(x, 10) == 0 end) != 2 && Enum.sort(String.codepoints("#{a}#{b}")) == sorted end) end end   defp char_len(n), do: length(to_char_list(n))   def task do Enum.reduce_while(Stream.iterate(1, &(&1+1)), 1, fn n, acc -> case vampire_factors(n) do [] -> {:cont, acc} vf -> IO.puts "#{n}:\t#{inspect vf}" if acc < 25, do: {:cont, acc+1}, else: {:halt, acc+1} end end) IO.puts "" Enum.each([16758243290880, 24959017348650, 14593825548650], fn n -> case vampire_factors(n) do [] -> IO.puts "#{n} is not a vampire number!" vf -> IO.puts "#{n}:\t#{inspect vf}" end end) end end   Vampire.task
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
#Factor
Factor
USING: combinators.short-circuit fry io kernel lists lists.lazy math math.combinatorics math.functions math.primes.factors math.statistics math.text.utils prettyprint sequences sets ; IN: rosetta-code.vampire-number   : digits ( n -- m ) log10 floor >integer 1 + ;   : same-digits? ( n n1 n2 -- ? ) [ 1 digit-groups ] tri@ append [ histogram ] bi@ = ;   : half-len-factors ( n -- seq ) [ divisors ] [ digits ] bi 2/ '[ digits _ = ] filter ;   : same-digit-factors ( n -- seq ) dup half-len-factors 2 <combinations> [ first2 same-digits? ] with filter ;   : under-two-trailing-zeros? ( seq -- ? ) [ 10 mod ] map [ 0 = ] count 2 < ;   : tentative-fangs ( n -- seq ) same-digit-factors [ under-two-trailing-zeros? ] filter ;   : fangs ( n -- seq ) [ tentative-fangs ] [ ] bi '[ product _ = ] filter ;   : vampire? ( n -- ? ) { [ digits even? ] [ fangs empty? not ] } 1&& ;   : first25 ( -- seq ) 25 0 lfrom [ vampire? ] lfilter ltake list>array ;   : .vamp-with-fangs ( n -- ) [ pprint bl ] [ fangs [ pprint bl ] each ] bi nl ;   : part1 ( -- ) first25 [ .vamp-with-fangs ] each ;   : part2 ( -- ) { 16758243290880 24959017348650 14593825548650 } [ dup vampire? [ .vamp-with-fangs ] [ drop ] if ] each ;   : main ( -- ) part1 part2 ;   MAIN: main
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.
#Tcl
Tcl
package require Tcl 8.5   proc vlqEncode number { if {$number < 0} {error "negative not supported"} while 1 { lappend digits [expr {$number & 0x7f}] if {[set number [expr {$number >> 7}]] == 0} break } set out [format %c [lindex $digits 0]] foreach digit [lrange $digits 1 end] { set out [format %c%s [expr {0x80+$digit}] $out] } return $out } proc vlqDecode chars { set n 0 foreach c [split $chars ""] { scan $c %c c set n [expr {($n<<7) | ($c&0x7f)}] if {!($c&0x80)} break } return $n }
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
#Fortran
Fortran
program varargs   integer, dimension(:), allocatable :: va integer :: i   ! using an array (vector) static call v_func() call v_func( (/ 100 /) ) call v_func( (/ 90, 20, 30 /) )   ! dynamically creating an array of 5 elements allocate(va(5)) va = (/ (i,i=1,5) /) call v_func(va) deallocate(va)   contains   subroutine v_func(arglist) integer, dimension(:), intent(in), optional :: arglist   integer :: i   if ( present(arglist) ) then do i = lbound(arglist, 1), ubound(arglist, 1) print *, arglist(i) end do else print *, "no argument at all" end if end subroutine v_func   end program varargs
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Ol
Ol
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#ooRexx
ooRexx
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PARI.2FGP
PARI/GP
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Pascal
Pascal
use Devel::Size qw(size total_size);   my $var = 9384752; my @arr = (1, 2, 3, 4, 5, 6); print size($var); # 24 print total_size(\@arr); # 256
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
#OCaml
OCaml
module Vector = struct type t = { x : float; y : float } let make x y = { x; y } let add a b = { x = a.x +. b.x; y = a.y +. b.y } let sub a b = { x = a.x -. b.x; y = a.y -. b.y } let mul a n = { x = a.x *. n; y = a.y *. n } let div a n = { x = a.x /. n; y = a.y /. n }   let to_string {x; y} = Printf.sprintf "(%F, %F)" x y   let ( + ) = add let ( - ) = sub let ( * ) = mul let ( / ) = div end   open Printf   let test () = let a, b = Vector.make 5. 7., Vector.make 2. 3. in printf "a:  %s\n" (Vector.to_string a); printf "b:  %s\n" (Vector.to_string b); printf "a+b:  %s\n" Vector.(a + b |> to_string); printf "a-b:  %s\n" Vector.(a - b |> to_string); printf "a*11: %s\n" Vector.(a * 11. |> to_string); printf "a/2:  %s\n" Vector.(a / 2. |> to_string)
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
#Perl
Perl
if( @ARGV != 3 ){ printHelp(); }   # translate to upper-case, remove anything else map( (tr/a-z/A-Z/, s/[^A-Z]//g), @ARGV );   my $cipher_decipher = $ARGV[ 0 ];   if( $cipher_decipher !~ /ENC|DEC/ ){ printHelp(); # user should say what to do }   print "Key: " . (my $key = $ARGV[ 2 ]) . "\n";   if( $cipher_decipher =~ /ENC/ ){ print "Plain-text: " . (my $plain = $ARGV[ 1 ]) . "\n"; print "Encrypted: " . Vigenere( 1, $key, $plain ) . "\n"; }elsif( $cipher_decipher =~ /DEC/ ){ print "Cipher-text: " . (my $cipher = $ARGV[ 1 ]) . "\n"; print "Decrypted: " . Vigenere( -1, $key, $cipher ) . "\n"; }   sub printHelp{ print "Usage:\n" . "Encrypting:\n perl cipher.pl ENC (plain text) (key)\n" . "Decrypting:\n perl cipher.pl DEC (cipher text) (key)\n"; exit -1; }   sub Vigenere{ my ($direction, $key, $text) = @_; for( my $count = 0; $count < length $text; $count ++ ){ $key_offset = $direction * ord substr( $key, $count % length $key, 1); $char_offset = ord substr( $text, $count, 1 ); $cipher .= chr 65 + ((($char_offset % 26) + ($key_offset % 26)) % 26); # 65 is the ASCII character code for 'A' } return $cipher; }
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).
#Scheme
Scheme
(use posix) (use files) (use srfi-13)   (define (walk FN PATH) (for-each (lambda (ENTRY) (cond ((not (null? ENTRY))   (let ((MYPATH (make-pathname PATH ENTRY)))   (cond ((directory-exists? MYPATH) (walk FN MYPATH) ))   (FN MYPATH) )))) (directory PATH #t) ))   (walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/")
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).
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: walkDir (in string: dirName, in string: extension) is func local var string: fileName is ""; var string: path is ""; begin for fileName range readDir(dirName) do path := dirName & "/" & fileName; if endsWith(path, extension) then writeln(path); end if; if fileType(path) = FILE_DIR then walkDir(path, extension); end if; end for; end func;   const proc: main is func begin walkDir(".", ".sd7"); end func;
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.
#Visual_Basic_.NET
Visual Basic .NET
' Convert tower block data into a string representation, then manipulate that. Module Module1 Sub Main(Args() As String) Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers. Dim wta As Integer()() = { ' Water tower array (input data). New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8}, New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}} Dim blk As String, ' String representation of a block of towers. lf As String = vbLf, ' Line feed to separate floors in a block of towers. tb = "██", wr = "≈≈", mt = " " ' Tower Block, Water Retained, eMpTy space. For i As Integer = 0 To wta.Length - 1 Dim bpf As Integer ' Count of tower blocks found per floor. blk = "" Do bpf = 0 : Dim floor As String = "" ' String representation of each floor. For j As Integer = 0 To wta(i).Length - 1 If wta(i)(j) > 0 Then ' Tower block detected, add block to floor, floor &= tb : wta(i)(j) -= 1 : bpf += 1 ' reduce tower by one. Else ' Empty space detected, fill when not first or last column. floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt) End If Next If bpf > 0 Then blk = floor & lf & blk ' Add floors until blocks are gone. Loop Until bpf = 0 ' No tower blocks left, so terminate. ' Erode potential water retention cells from left and right. While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While ' Optionaly show towers w/ water marks. If shoTow Then Console.Write("{0}{1}", lf, blk) ' Subtract the amount of non-water mark characters from the total char amount. Console.Write("Block {0} retains {1,2} water units.{2}", i + 1, (blk.Length - blk.Replace(wr, "").Length) \ 2, lf) Next End Sub End Module
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
#Ceylon
Ceylon
shared void run() {   alias Vector => Float[3];   function dot(Vector a, Vector b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];   function cross(Vector a, Vector b) => [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];   function scalarTriple(Vector a, Vector b, Vector c) => dot(a, cross(b, c));   function vectorTriple(Vector a, Vector b, Vector c) => cross(a, cross(b, c));   value a = [ 3.0, 4.0, 5.0 ]; value b = [ 4.0, 3.0, 5.0 ]; value c = [-5.0, -12.0, -13.0 ];   print("``a`` . ``b`` = ``dot(a, b)``"); print("``a`` X ``b`` = ``cross(a, b)``"); print("``a`` . ``b`` X ``c`` = ``scalarTriple(a, b, c)``"); print("``a`` X ``b`` X ``c`` = ``vectorTriple(a, b, c)``"); }
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
#COBOL
COBOL
>>SOURCE FORMAT FREE *> this is gnucobol 2.0 identification division. program-id. callISINtest. data division. working-storage section. 01 ISINtest-result binary-int. procedure division. start-callISINtest. display 'should be valid ' with no advancing call 'ISINtest' using 'US0378331005' ISINtest-result perform display-ISINtest-result display 'should not be valid ' with no advancing call 'ISINtest' using 'US0373831005' ISINtest-result perform display-ISINtest-result display 'should not be valid ' with no advancing call 'ISINtest' using 'U50378331005' ISINtest-result perform display-ISINtest-result display 'should not be valid ' with no advancing call 'ISINtest' using 'US03378331005' ISINtest-result perform display-ISINtest-result display 'should be valid ' with no advancing call 'ISINtest' using 'AU0000XVGZA3' ISINtest-result perform display-ISINtest-result display 'should be valid ' with no advancing call 'ISINtest' using 'AU0000VXGZA3' ISINtest-result perform display-ISINtest-result display 'should be valid ' with no advancing call 'ISINtest' using 'FR0000988040' ISINtest-result perform display-ISINtest-result stop run . display-ISINtest-result. evaluate ISINtest-result when 0 display ' is valid' when -1 display ' invalid length ' when -2 display ' invalid countrycode ' when -3 display ' invalid base36 digit ' when -4 display ' luhn test failed' when other display ' invalid return code ' ISINtest-result end-evaluate . end program callISINtest.   identification division. program-id. ISINtest. data division. working-storage section. 01 country-code-values value 'ADAEAFAGAIALAMAOAQARASATAUAWAXAZBABBBDBEBFBGBHBIBJBLBMBNBOBQBRBS' & 'BTBVBWBYBZCACCCDCFCGCHCICKCLCMCNCOCRCUCVCWCXCYCZDEDJDKDMDODZECEE' & 'EGEHERESETFIFJFKFMFOFRGAGBGDGEGFGGGHGIGLGMGNGPGQGRGSGTGUGWGYHKHM' & 'HNHRHTHUIDIEILIMINIOIQIRISITJEJMJOJPKEKGKHKIKMKNKPKRKWKYKZLALBLC' & 'LILKLRLSLTLULVLYMAMCMDMEMFMGMHMKMLMMMNMOMPMQMRMSMTMUMVMWMXMYMZNA' & 'NCNENFNGNINLNONPNRNUNZOMPAPEPFPGPHPKPLPMPNPRPSPTPWPYQARERORSRURW' & 'SASBSCSDSESGSHSISJSKSLSMSNSOSRSSSTSVSXSYSZTCTDTFTGTHTJTKTLTMTNTO' & 'TRTTTVTWTZUAUGUMUSUYUZVAVCVEVGVIVNVUWFWSYEYTZAZMZW'. 03 country-codes occurs 249 ascending key country-code indexed by cc-idx. 05 country-code pic xx.   01 b pic 99. 01 base36-digits pic x(36) value '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.   01 i pic 99. 01 p pic 99. 01 luhn-number pic x(20). 01 luhntest-result binary-int.   linkage section. 01 test-number any length. 01 ISINtest-result binary-int.   procedure division using test-number ISINtest-result. start-ISINtest. display space test-number with no advancing   *> format test if function length(test-number) <> 12 move -1 to ISINtest-result goback end-if   *> countrycode test search all country-codes at end move -2 to ISINtest-result goback when test-number(1:2) = country-code(cc-idx) continue end-search   *> convert each character from base 36 to base 10 *> and add to the luhn-number move 0 to p perform varying i from 1 by 1 until i > 12 if test-number(i:1) >= '0' and <= '9' move test-number(i:1) to luhn-number(p + 1:1) add 1 to p else perform varying b from 9 by 1 until b > 35 or base36-digits(b + 1:1) = test-number(i:1) continue end-perform if b > 35 move -3 to ISINtest-result goback end-if move b to luhn-number(p + 1:2) add 2 to p end-if end-perform   call 'luhntest' using luhn-number(1:p) luhntest-result if luhntest-result <> 0 move -4 to ISINtest-result goback end-if   move 0 to ISINtest-result goback . end program ISINtest.   identification division. program-id. luhntest. data division. working-storage section. 01 i pic S99. 01 check-sum pic 999. linkage section. 01 test-number any length. 01 luhntest-result binary-int. procedure division using test-number luhntest-result. start-luhntest. display space test-number with no advancing move 0 to check-sum   *> right to left sum the odd numbered digits compute i = function length(test-number) perform varying i from i by -2 until i < 1 add function numval(test-number(i:1)) to check-sum end-perform display space check-sum with no advancing   *> right to left double sum the even numbered digits compute i = function length(test-number) - 1 perform varying i from i by -2 until i < 1 add function numval(test-number(i:1)) to check-sum add function numval(test-number(i:1)) to check-sum *> convert a two-digit double sum number to a single digit if test-number(i:1) >= '5' subtract 9 from check-sum end-if end-perform display space check-sum with no advancing   if function mod(check-sum,10) = 0 move 0 to luhntest-result *> success else move -1 to luhntest-result *> failure end-if goback . end program luhntest.
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
#Clojure
Clojure
(defn van-der-corput "Get the nth element of the van der Corput sequence." ([n] ;; Default base = 2 (van-der-corput n 2)) ([n base] (let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal. ;; We essentially want to reverse the digits of n and put them after the ;; decimal point. So, we repeatedly pull off the lowest digit of n, scale ;; it to the right of the decimal point, and accumulate that. (loop [sum 0 n n scale s] (if (zero? n) sum ;; Base case: no digits left, so we're done. (recur (+ sum (* (rem n base) scale)) ;; Accumulate the least digit (quot n base) ;; Drop a digit of n (* scale s))))))) ;; Move farther past the decimal   (clojure.pprint/print-table (cons :base (range 10)) ;; column headings (for [base (range 2 6)] ;; rows (into {:base base} (for [n (range 10)] ;; table entries [n (van-der-corput n base)]))))
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#ALGOL_68
ALGOL 68
PR read "uriParser.a68" PR   PROC test uri parser = ( STRING uri )VOID: BEGIN URI result := parse uri( uri ); print( ( uri, ":", newline ) ); IF NOT ok OF result THEN # the parse failed # print( ( " ", error OF result, newline ) ) ELSE # parsed OK # print( ( " scheme: ", scheme OF result, newline ) ); IF userinfo OF result /= "" THEN print( ( " userinfo: ", userinfo OF result, newline ) ) FI; IF host OF result /= "" THEN print( ( " host: ", host OF result, newline ) ) FI; IF port OF result /= "" THEN print( ( " port: ", port OF result, newline ) ) FI; IF path OF result /= "" THEN print( ( " path: ", path OF result, newline ) ) FI; IF query OF result /= "" THEN print( ( " query: ", query OF result, newline ) ) FI; IF fragment id OF result /= "" THEN print( ( " fragment id: ", fragment id OF result, newline ) ) FI FI; print( ( newline ) ) END # test uri parser # ;   BEGIN test uri parser( "foo://example.com:8042/over/there?name=ferret#nose" ) ; test uri parser( "urn:example:animal:ferret:nose" ) ; test uri parser( "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" ) ; test uri parser( "ftp://ftp.is.co.za/rfc/rfc1808.txt" ) ; test uri parser( "http://www.ietf.org/rfc/rfc2396.txt#header1" ) ; test uri parser( "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" ) ; test uri parser( "mailto:[email protected]" ) ; test uri parser( "news:comp.infosystems.www.servers.unix" ) ; test uri parser( "tel:+1-816-555-1212" ) ; test uri parser( "telnet://192.0.2.16:80/" ) ; test uri parser( "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ) ; test uri parser( "ssh://[email protected]" ) ; test uri parser( "https://bob:[email protected]/place" ) ; test uri parser( "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ) END
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Action.21
Action!
BYTE FUNC MustEncode(CHAR c CHAR ARRAY ex) BYTE i   IF c>='a AND c<='z OR c>='A AND c<='Z OR c>='0 AND c<='9 THEN RETURN (0) FI IF ex(0)>0 THEN FOR i=1 TO ex(0) DO IF ex(i)=c THEN RETURN (0) FI OD FI RETURN (1)   PROC Append(CHAR ARRAY s CHAR c) s(0)==+1 s(s(0))=c RETURN   PROC Encode(CHAR ARRAY in,out,ex BYTE spaceToPlus) CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F] BYTE i CHAR c   out(0)=0 FOR i=1 TO in(0) DO c=in(i) IF spaceToPlus=1 AND c=32 THEN Append(out,'+) ELSEIF MustEncode(c,ex) THEN Append(out,'%) Append(out,hex(c RSH 4)) Append(out,hex(c&$0F)) ELSE Append(out,c) FI OD RETURN   PROC EncodeRaw(CHAR ARRAY in,out) Encode(in,out,"",0) RETURN   PROC EncodeRFC3986(CHAR ARRAY in,out) Encode(in,out,"-._~",0) RETURN   PROC EncodeHTML5(CHAR ARRAY in,out) Encode(in,out,"-._*",1) RETURN   PROC PrintInv(CHAR ARRAY a) BYTE i   IF a(0)>0 THEN FOR i=1 TO a(0) DO Put(a(i)%$80) OD FI RETURN   PROC Test(CHAR ARRAY in) CHAR ARRAY out(256)   PrintInv("input ") PrintF(" %S%E",in)   EncodeRaw(in,out) PrintInv("encoded ") PrintF(" %S%E",out)   EncodeRFC3986(in,out) PrintInv("RFC 3986") PrintF(" %S%E",out)   EncodeHTML5(in,out) PrintInv("HTML 5 ") PrintF(" %S%E%E",out) RETURN   PROC Main() Test("http://foo bar/") Test("http://www.rosettacode.org/wiki/URL_encoding") Test("http://foo bar/*_-.html") RETURN
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Ada
Ada
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Encode is Normal : constant String := "http://foo bar/"; begin Put_Line (AWS.URL.Encode (Normal)); end Encode;
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
#Axe
Axe
1→A