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/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
#Lingo
Lingo
put urlencode("http://foo bar/") -- "http%3a%2f%2ffoo+bar%2f"
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
#LiveCode
LiveCode
urlEncode("http://foo bar/") -- http%3A%2F%2Ffoo+bar%2F
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
#HolyC
HolyC
U8 i;
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
#Icon_and_Unicon
Icon and Unicon
global gvar # a global   procedure main(arglist) # arglist is a parameter of main local a,b,i,x # a, b, i, x are locals withing main static y # a static (silly in main)   x := arglist[1] a := 1.0 i := 10 b := [x,a,i,b]   # ... rest of program end
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Python
Python
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 #%% if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
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
#zkl
zkl
fcn fangs(N){ //-->if Vampire number: (N,(a,b,c,...)), where a*x==N var [const] tens=[0 .. 18].pump(List,(10.0).pow,"toInt");   (half:=N.numDigits) : if (_.isOdd) return(T);; half/=2; digits:=N.toString().sort(); lo:=tens[half-1].max((N+tens[half])/(tens[half])); hi:=(N/lo).min(N.toFloat().sqrt()); fs:=[lo .. hi].filter('wrap(n){ N%n==0 and (n%10!=0 or (N/n)%10!=0) and (n.toString()+(N/n).toString()).sort()==digits }); fs and T(N,fs) or T; }
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
#Python
Python
def print_all(*things): for x in things: print x
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
#Qi
Qi
  (define varargs-func A -> (print A))   (define varargs [varargs | Args] -> [varargs-func [list | Args]] A -> A)   (sugar in varargs 1)  
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
#Go
Go
package main   import "fmt"   type vector struct { x, y, z float64 }   var ( a = vector{3, 4, 5} b = vector{4, 3, 5} c = vector{-5, -12, -13} )   func dot(a, b vector) float64 { return a.x*b.x + a.y*b.y + a.z*b.z }   func cross(a, b vector) vector { return vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x} }   func s3(a, b, c vector) float64 { return dot(a, cross(b, c)) }   func v3(a, b, c vector) vector { return cross(a, cross(b, c)) }   func main() { fmt.Println(dot(a, b)) fmt.Println(cross(a, b)) fmt.Println(s3(a, b, c)) fmt.Println(v3(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
#Ring
Ring
  # Project : Validate International Securities Identification Number   decimals(0)   test = ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]   for n = 1 to len(test) testold = test[n] ascii1 = ascii(left(test[n],1)) ascii2 = ascii(substr(test[n],2,1)) if len(test[n]) != 12 or (ascii1 < 65 or ascii1 > 90) or (ascii2 < 65 or ascii2 > 90) see test[n] + " -> Invalid" + nl loop ok for m = 1 to len(test[n]) if ascii(test[n][m]) > 64 and ascii(test[n][m]) < 91 asc = ascii(test[n][m]) - 55 test[n] = left(test[n],m-1) + string(asc) + right(test[n],len(test[n])-m) ok next see testold + " -> " + cardtest(test[n]) + nl next   func cardtest(numstr) revstring = revstr(numstr) s1 = revodd(revstring) s2 = reveven(revstring) s3 =right(string(s1+s2), 1) if s3 = "0" return "Valid" else return "Invalid" ok   func revstr(str) strnew = "" for nr = len(str) to 1 step -1 strnew = strnew + str[nr] next return strnew   func revodd(str) strnew = "" for nr = 1 to len(str) step 2 strnew = strnew + str[nr] next sumodd = 0 for p = 1 to len(strnew) sumodd = sumodd + number(strnew[p]) next return sumodd   func reveven(str) strnew = "" for nr = 2 to len(str) step 2 strnew = strnew + str[nr] next lsteven = [] for p = 1 to len(strnew) add(lsteven, string(2*number(strnew[p]))) next arreven = list(len(lsteven)) for q = 1 to len(lsteven) sum = 0 for w = 1 to len(lsteven[q]) sum = sum + lsteven[q][w] next arreven[q] = sum next sumarr = 0 for x = 1 to len(arreven) sumarr = sumarr + arreven[x] next return sumarr  
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
#Ruby
Ruby
RE = /\A[A-Z]{2}[A-Z0-9]{9}[0-9]{1}\z/   def valid_isin?(str) return false unless str =~ RE luhn(str.chars.map{|c| c.to_i(36)}.join) end   p %w(US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 FR0000988040).map{|tc| valid_isin?(tc) }   # => [true, false, false, false, true, true, true]
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
#PicoLisp
PicoLisp
(scl 6)   (de vdc (N B) (default B 2) (let (R 0 A 1.0) (until (=0 N) (inc 'R (* (setq A (/ A B)) (% N B))) (setq N (/ N B)) ) R ) )   (for B (2 3 4) (prinl "Base: " B) (for N (range 0 9) (prinl N ": " (round (vdc N B) 4)) ) )
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
#PL.2FI
PL/I
  vdcb: procedure (an) returns (bit (31)); /* 6 July 2012 */ declare an fixed binary (31); declare (n, i) fixed binary (31); declare v bit (31) varying;   n = an; v = ''b; do i = 1 by 1 while (n > 0); if iand(n, 1) = 1 then v = v || '1'b; else v = v || '0'b; n = isrl(n, 1); end; return (v); end vdcb;   declare i fixed binary (31);   do i = 0 to 10; put skip list ('0.' || vdcb(i)); end;  
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Kotlin
Kotlin
// version 1.1.2   import java.net.URLDecoder   fun main(args: Array<String>) { val encoded = arrayOf("http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1") for (e in encoded) println(URLDecoder.decode(e, "UTF-8")) }
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Ksh
Ksh
  url_decode() { decode="${*//+/ }" eval print -r -- "\$'${decode//'%'@(??)/'\'x\1"'\$'"}'" 2>/dev/null }   url_decode "http%3A%2F%2Ffoo%20bar%2F" url_decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1"  
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#Julia
Julia
const pat1 = (" ## #", " ## #", " # ##", " #### #", " # ##", " ## #", " # ####", " ### ##", " ## ###", " # ##") const pat2 = [replace(x, r"[# ]" => (x) -> x == " " ? "#" : " ") for x in pat1] const ptod1 = Dict((b => a - 1) for (a, b) in enumerate(pat1)) const ptod2 = Dict((b => a - 1) for (a, b) in enumerate(pat2)) const reg = Regex("^\\s*# #\\s*((?:" * join(pat1, "|") * "){6})\\s*# #\\s*((?:" * join(pat2, "|") * "){6})\\s*# #\\s*") const lines = [ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", ]   function decodeUPC(line) if (m = match(reg, line)) != nothing mats, dig = filter(!isempty, m.captures), Int[] for mat in mats append!(dig, [ptod1[x.match] for x in eachmatch(r"(.......)", mat) if haskey(ptod1, x.match)]) append!(dig, [ptod2[x.match] for x in eachmatch(r"(.......)", mat) if haskey(ptod2, x.match)]) end dsum = sum([(isodd(i) ? 3 : 1) * n for (i, n) in enumerate(dig)]) (dsum % 10 == 0) && return prod(string.(dig)) end return "" end   for line in lines println((s = decodeUPC(line)) != "" ? s : (s = decodeUPC(reverse(line))) != "" ? s : "Invalid") end  
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#PHP
PHP
<?php   $conf = file_get_contents('update-conf-file.txt');   // Disable the needspeeling option (using a semicolon prefix) $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);   // Enable the seedsremoved option by removing the semicolon and any leading whitespace $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);   // Change the numberofbananas parameter to 1024 $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);   // Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) { $conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf); } else { $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL; }   echo $conf;
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Fortran
Fortran
character(20) :: s integer :: i   print*, "Enter a string (max 20 characters)" read*, s print*, "Enter the integer 75000" read*, i
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s As String Dim i AS Integer Input "Please enter a string : "; s Do Input "Please enter 75000  : "; i Loop Until i = 75000 Print Print s, i Sleep
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Def aName$="No Name", Num$ \\ we open a new stack, and hold old Stack New { If Ask$("Give your name:",,,,,aName$)="OK" Then Read aName$ If Ask$("Give a Number: (75000)",,,,,"")="OK" Then Read Num$ if Num$<>"75000" or aName$="" Then loop } \ now old stack came back Print Num$, aName$ Print Letter$ \\ Letter$ pop a string from stack } CheckIt "Thank You"    
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
str = InputString["Input a string"]; nb = InputString["Input a number"]; Print[str, " " , ToString@nb]
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Nim
Nim
import unicode, sequtils, strformat, strutils   const UChars = ["\u0041", "\u00F6", "\u0416", "\u20AC", "\u{1D11E}"]   proc toSeqByte(r: Rune): seq[byte] = let s = r.toUTF8 result = @(s.toOpenArrayByte(0, s.high))   proc toRune(s: seq[byte]): Rune = s.mapIt(chr(it)).join().toRunes[0]   echo "Character Unicode UTF-8 encoding (hex)" for uchar in UChars: # Convert the UTF-8 string to a rune (codepoint). var r = uchar.toRunes[0] # Convert the rune to a sequence of bytes. let s = r.toSeqByte # Convert back the sequence of bytes to a rune. r = s.toRune # Display. echo &"""{uchar:>5} U+{r.int.toHex(5)} {s.map(toHex).join(" ")}"""
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Perl
Perl
#!/usr/bin/perl use strict; use warnings; use Unicode::UCD 'charinfo'; # getting the unicode name of the character use utf8; # using non-ascii-characters in source code binmode STDOUT, ":encoding(UTF-8)"; # printing non-ascii-characters to screen   my @chars = map {ord} qw/A ö Ж € 𝄞/; # @chars contains the unicode points my $print_format = '%5s  %-35s'; printf "$print_format %8s  %s\n" , 'char', 'name', 'unicode', 'utf-8 encoding'; map{ my $name = charinfo($_)->{'name'}; # get unicode name printf "$print_format  %06x " , chr, lc $name, $_; my $utf8 = chr; # single char (using implicit $_) utf8::encode($utf8); # inplace encoding into utf8 parts map{ # for each utf8 char print ord printf " %x", ord; } split //, $utf8; print "\n"; } @chars;
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
#Scala
Scala
import java.net.URI   object WebAddressParser extends App {   parseAddress("foo://example.com:8042/over/there?name=ferret#nose") parseAddress("ftp://ftp.is.co.za/rfc/rfc1808.txt") parseAddress("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64") parseAddress("http://www.ietf.org/rfc/rfc2396.txt#header1") parseAddress("https://bob:[email protected]/place") parseAddress("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") parseAddress("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") parseAddress("ldap://[2001:db8::7]/c=GB?objectClass?one") parseAddress("mailto:[email protected]") parseAddress("news:comp.infosystems.www.servers.unix") parseAddress("ssh://[email protected]") parseAddress("tel:+1-816-555-1212") parseAddress("telnet://192.0.2.16:80/") parseAddress("urn:example:animal:ferret:nose") parseAddress("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") parseAddress("This is not a URI!")   private def parseAddress(a: String): Unit = { print(f"Parsing $a%-72s") try { val u = new URI(a) print("\u2714\tscheme = " + u.getScheme) print("\tdomain = " + u.getHost) print("\tport = " + (if (-1 == u.getPort) "default" else u.getPort)) print("\tpath = " + (if (u.getPath == null) u.getSchemeSpecificPart else u.getPath)) print("\tquery = " + u.getQuery) println("\tfragment = " + u.getFragment) } catch { case ex: Throwable => println('\u2718') } } }
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
#Lua
Lua
function encodeChar(chr) return string.format("%%%X",string.byte(chr)) end   function encodeString(str) local output, t = string.gsub(str,"[^%w]",encodeChar) return output end   -- will print "http%3A%2F%2Ffoo%20bar%2F" print(encodeString("http://foo bar/"))
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function decodeUrl$(a$) { DIM a$() a$()=Piece$(a$, "%") if len(a$())=1 then =str$(a$):exit k=each(a$(),2) acc$=str$(a$(0)) While k { acc$+=str$(Chr$(Eval("0x"+left$(a$(k^),2)))+Mid$(a$(k^),3)) } =string$(acc$ as utf8dec) } Group Parse$ { all$, c=1 tc$="" Enum UrlType {None=0, RFC3986, HTML5} variation TypeData=("","-._~","-._*") Function Next { .tc$<=mid$(.all$,.c,1) .c++ =.tc$<>"" } Value { =.tc$ } Function DecodeOne$ { if .tc$="" then exit if .tc$ ~"[A-Za-z0-9]" then =.tc$ : exit If .tc$=" " Then =if$(.variation=.HTML5->"+","%20") :exit if instr(.TypeData#val$(.variation),.tc$)>0 then =.tc$ :exit ="%"+hex$(asc(.tc$), 1) } Function Decode$ { acc$="" .c<=1 While .Next() { acc$+=.DecodeOne$() } =acc$ } Set () { \\ using optional argument var=.None Read a$, ? var a$=chr$(string$(a$ as utf8enc)) .variation<=var .all$<=a$ .c<=1 } } \\ MAIN Parse$()="http://foo bar/" Print Quote$(Parse.Decode$()) Parse.variation=Parse.HTML5 Print Quote$(Parse.Decode$()) Parse.variation=Parse.RFC3986 Print Quote$(Parse.Decode$()) Parse$(Parse.RFC3986) ={mailto:"Irma User" <[email protected]>} Print Quote$(Parse.Decode$()) Parse$(Parse.RFC3986) ={http://foo.bar.com/~user-name/_subdir/*~.html} m=each(Parse.UrlType) while m { Parse.variation=eval(m) Print Quote$(Parse.Decode$()) Print decodeUrl$(Parse.Decode$()) } } CheckIt  
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
#J
J
val=. 0
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Quackery
Quackery
[ ' [ 0 ] swap 1 - times [ dup behead swap find 1+ 2dup swap found * swap join ] reverse ] is van-eck ( n --> [ )   10 van-eck echo cr 1000 van-eck -10 split echo drop
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.
#Racket
Racket
#lang racket (require racket/stream)   (define (van-eck) (define (next val n seen) (define val1 (- n (hash-ref seen val n))) (stream-cons val (next val1 (+ n 1) (hash-set seen val n)))) (next 0 0 (hash)))   (define (get m n s) (stream->list (stream-take (stream-tail s m) (- n m))))   "First 10 terms:" (get 0 10 (van-eck)) "Terms 991 to 1000 terms:" (get 990 1000 (van-eck)) ; counting from 0
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
#Quackery
Quackery
[ pack witheach [ echo$ cr ] ] is counted-echo$ ( $ ... n --> )   [ this ] is marker ( --> m )   [ [] [ swap dup marker oats iff drop done nested swap join again ] ] is gather ( m x ... --> [ )   [ gather witheach [ echo$ cr ] ] is markered-echo$ ( m $ ... --> )     $ "this" $ "is" $ "a" $ "formica" $ "table" 5 counted-echo$ cr marker $ "green" $ "is" $ "its" $ "colour" markered-echo$
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
#R
R
printallargs1 <- function(...) list(...) printallargs1(1:5, "abc", TRUE) # [[1]] # [1] 1 2 3 4 5 # # [[2]] # [1] "abc" # # [[3]] # [1] TRUE
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
#Groovy
Groovy
def pairwiseOperation = { x, y, Closure binaryOp -> assert x && y && x.size() == y.size() [x, y].transpose().collect(binaryOp) }   def pwMult = pairwiseOperation.rcurry { it[0] * it[1] }   def dotProduct = { x, y -> assert x && y && x.size() == y.size() pwMult(x, y).sum() }
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
#Rust
Rust
extern crate luhn_cc;   use luhn_cc::compute_luhn;   fn main() { assert_eq!(validate_isin("US0378331005"), true); assert_eq!(validate_isin("US0373831005"), false); assert_eq!(validate_isin("U50378331005"), false); assert_eq!(validate_isin("US03378331005"), false); assert_eq!(validate_isin("AU0000XVGZA3"), true); assert_eq!(validate_isin("AU0000VXGZA3"), true); assert_eq!(validate_isin("FR0000988040"), true); }   fn validate_isin(isin: &str) -> bool { // Preliminary checks to avoid working on non-ASCII stuff if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len() != 12 { return false; } if !isin[..2].chars().all(|x| x.is_alphabetic()) || !isin[2..12].chars().all(|x| x.is_alphanumeric()) || !isin.chars().last().unwrap().is_numeric() { return false; }   // Converts the alphanumeric string in a numeric-only string let bytes = isin.as_bytes();   let s2 = bytes.iter() .flat_map(|&c| { if c.is_ascii_digit() { vec![c] } else { (c + 10 - ('A' as u8)).to_string().into_bytes() } }).collect::<Vec<u8>>();   let string = std::str::from_utf8(&s2).unwrap(); let number = string.parse::<usize>().unwrap();   return compute_luhn(number); }  
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
#SAS
SAS
data test; length isin $20 ok $1; input isin; keep isin ok; array s{24}; link isin; return; isin: ok="N"; n=length(isin); if n=12 then do; j=0; do i=1 to n; k=rank(substr(isin,i,1)); if k>=48 & k<=57 then do; if i<3 then return; j+1; s{j}=k-48; end; else if k>=65 & k<=90 then do; if i=12 then return; k+-55; j+1; s{j}=int(k/10); j+1; s{j}=mod(k,10); end; else return; end;   v=sum(of s{*}); do i=j-1 to 1 by -2; v+s{i}-9*(s{i}>4); end;   if mod(v,10)=0 then ok="Y"; end; return; cards; US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 FR0000988040 ; run;
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
#Prolog
Prolog
% vdc( N, Base, Out ) % Out = the Van der Corput representation of N in given Base vdc( 0, _, [] ). vdc( N, Base, Out ) :- Nr is mod(N, Base), Nq is N // Base, vdc( Nq, Base, Tmp ), Out = [Nr|Tmp].   % Writes every element of a list to stdout; no newlines write_list( [] ). write_list( [H|T] ) :- write( H ), write_list( T ).   % Writes the Nth Van der Corput item. print_vdc( N, Base ) :- vdc( N, Base, Lst ), write('0.'), write_list( Lst ). print_vdc( N ) :- print_vdc( N, 2 ).   % Prints the first N+1 elements of the Van der Corput % sequence, each to its own line print_some( 0, _ ) :- write( '0.0' ). print_some( N, Base ) :- M is N - 1, print_some( M, Base ), nl, print_vdc( N, Base ). print_some( N ) :- print_some( N, 2 ).   test :- writeln('First 10 members in base 2:'), print_some( 9 ), nl, write('7th member in base 4 (stretch goal) => '), print_vdc( 7, 4 ).  
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Lambdatalk
Lambdatalk
  1) define a new javascript primitive: {script LAMBDATALK.DICT['decodeURIComponent'] = function() { return decodeURIComponent( arguments[0].trim() ); }; }   2) and use it: {decodeURIComponent http%3A%2F%2Ffoo%20bar%2F} -> http://foo bar/        
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Lasso
Lasso
bytes('http%3A%2F%2Ffoo%20bar%2F') -> decodeurl
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#Kotlin
Kotlin
val LEFT_DIGITS = mapOf( " ## #" to 0, " ## #" to 1, " # ##" to 2, " #### #" to 3, " # ##" to 4, " ## #" to 5, " # ####" to 6, " ### ##" to 7, " ## ###" to 8, " # ##" to 9 ) val RIGHT_DIGITS = LEFT_DIGITS.mapKeys { it.key.replace(' ', 's').replace('#', ' ').replace('s', '#') }   const val END_SENTINEL = "# #" const val MID_SENTINEL = " # # "   fun decodeUPC(input: String) { fun decode(candidate: String): Pair<Boolean, List<Int>> { var pos = 0 var part = candidate.slice(pos until pos + END_SENTINEL.length) if (part == END_SENTINEL) { pos += END_SENTINEL.length } else { return Pair(false, emptyList()) }   val output = mutableListOf<Int>() for (i in 0 until 6) { part = candidate.slice(pos until pos + 7) pos += 7   if (LEFT_DIGITS.containsKey(part)) { output.add(LEFT_DIGITS.getOrDefault(part, -1)) } else { return Pair(false, output.toList()) } }   part = candidate.slice(pos until pos + MID_SENTINEL.length) if (part == MID_SENTINEL) { pos += MID_SENTINEL.length } else { return Pair(false, output.toList()) }   for (i in 0 until 6) { part = candidate.slice(pos until pos + 7) pos += 7   if (RIGHT_DIGITS.containsKey(part)) { output.add(RIGHT_DIGITS.getOrDefault(part, -1)) } else { return Pair(false, output.toList()) } }   part = candidate.slice(pos until pos + END_SENTINEL.length) if (part == END_SENTINEL) { pos += END_SENTINEL.length } else { return Pair(false, output.toList()) }   val sum = output.mapIndexed { i, v -> if (i % 2 == 0) v * 3 else v }.sum() return Pair(sum % 10 == 0, output.toList()) }   val candidate = input.trim()   var out = decode(candidate) if (out.first) { println(out.second) } else { out = decode(candidate.reversed()) if (out.first) { print(out.second) println(" Upside down") } else { if (out.second.size == 12) { println("Invalid checksum") } else { println("Invalid digit(s)") } } }   }   fun main() { val barcodes = listOf( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", )   for (barcode in barcodes) { decodeUPC(barcode) } }
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#PicoLisp
PicoLisp
(let Data # Read all data (in "config" (make (until (eof) (link (trim (split (line) " "))) ) ) ) (setq Data # Fix comments (mapcar '((L) (while (head '(";" ";") (car L)) (pop L) ) (if (= '(";") (car L)) L (cons NIL L) ) ) Data ) ) (let (Need NIL Seed NIL NBan NIL NStr NIL Favo NIL) (map '((L) (let D (mapcar uppc (cadar L)) (cond ((= '`(chop "NEEDSPEELING") D) (if Need (set L) (on Need) (unless (caar L) (set (car L) '(";")) ) ) ) ((= '`(chop "SEEDSREMOVED") D) (if Seed (set L) (on Seed) (when (caar L) (set (car L)) ) ) ) ((= '`(chop "NUMBEROFBANANAS") D) (if NBan (set L) (on NBan) (set (cddar L) 1024) ) ) ((= '`(chop "NUMBEROFSTRAWBERRIES") D) (if NStr (set L) (on NStr) ) ) ((= '`(chop "FAVOURITEFRUIT") D) (if Favo (set L) (on Favo) ) ) ) ) ) Data ) (unless Need (conc Data (cons (list NIL "NEEDSPEELING"))) ) (unless Seed (conc Data (cons (list NIL "SEEDSREMOVED"))) ) (unless NBan (conc Data (cons (list NIL "NUMBEROFBANANAS" 1024))) ) (unless NStr (conc Data (cons (list NIL "NUMBEROFSTRAWBERRIES" 62000))) ) ) (out "config" (for L Data (prinl (glue " " (if (car L) L (cdr L)))) ) ) )
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Frink
Frink
  s = input["Enter a string: "] i = parseInt[input["Enter an integer: "]]  
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Go
Go
package main   import "fmt"   func main() { var s string var i int if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 { fmt.Println("good") } else { fmt.Println("wrong") } }
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Nanoquery
Nanoquery
import Nanoquery.Util.Windows   // a function to handle the main window closing def finish(caller, event) exit end   // create a window w = new(Window, "Input").setTitle("Input") w.setSize(320, 190) w.setHandler(w.closing, finish)   // create two labels to go next to the input boxes stringlabel = new(Label).setParent(w) intlabel = new(Label).setParent(w)   stringlabel.setText("String: "); stringlabel.setPosition(20, 25) intlabel.setText("Integer: "); intlabel.setPosition(20, 75)   // create two textboxes for input stringbox = new(Textbox).setParent(w) intbox = new(Textbox).setParent(w)   stringbox.setPosition(100, 20); stringbox.setWidth(200); stringbox.setHeight(30) intbox.setPosition(100, 70); intbox.setWidth(200); intbox.setHeight(30)   // a function that handles when the 'done' button is clicked def done_clicked(caller, event) global stringbox global intbox global w   s = stringbox.getText() i = intbox.getText()   try if int(i) = 75000 println "String: " + s println "Integer: " + i exit else w.showMessageBox("Please enter 75000 for the integer value") end catch w.showMessageBox("Please enter 75000 for the integer value") end end   // create the 'done' button done = new(Button).setParent(w)   done.setText("Done"); done.setPosition(250,120) done.setHandler(done.clicked, done_clicked)   // display the window w.show()
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary import javax.swing.JOptionPane   unumber = 0 ustring = ''   do unumber = Integer.parseInt(JOptionPane.showInputDialog("Enter an Integer")) ustring = JOptionPane.showInputDialog("Enter a String") catch ex = Exception ex.printStackTrace end   unumber = unumber * 1.0 -- just to prove unumber is really a number say 'Number:' unumber.right(10)', String:' ustring   return  
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Phix
Phix
constant tests = {#0041, #00F6, #0416, #20AC, #1D11E} function hex(sequence s, string fmt) -- output helper return join(apply(true,sprintf,{{fmt},s}),',') end function for i=1 to length(tests) do integer codepoint = tests[i] sequence s = utf32_to_utf8({codepoint}), r = utf8_to_utf32(s) printf(1,"#%04x -> {%s} -> {%s}\n",{codepoint, hex(s,"#%02x"),hex(r,"#%04x")}) end for
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
#Tcl
Tcl
package require uri package require uri::urn   # a little bit of trickery to format results: proc pdict {d} { array set \t $d parray \t }   proc parse_uri {uri} { regexp {^(.*?):(.*)$} $uri -> scheme rest if {$scheme in $::uri::schemes} { # uri already knows how to split it: set parts [uri::split $uri] } else { # parse as though it's http: set parts [uri::SplitHttp $rest] dict set parts scheme $scheme } dict filter $parts value ?* ;# omit empty sections }   set tests { foo://example.com:8042/over/there?name=ferret#nose urn:example:animal:ferret:nose 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 }   foreach uri $tests { puts \n$uri pdict [parse_uri $uri] }
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
#Maple
Maple
URL:-Escape("http://foo bar/");
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
URLEncoding[url_] := StringReplace[url, x : Except[ Join[CharacterRange["0", "9"], CharacterRange["a", "z"], CharacterRange["A", "Z"]]] :> StringJoin[("%" ~~ #) & /@ IntegerString[ToCharacterCode[x, "UTF8"], 16]]]
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
#Java
Java
int a; double b; AClassNameHere c;
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
#JavaScript
JavaScript
[] unstack
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.
#Raku
Raku
sub n-van-ecks ($init) { $init, -> $i, { state %v; state $k; $k++; my $t = %v{$i}.defined ?? $k - %v{$i} !! 0; %v{$i} = $k; $t } ... * }   for < A181391 0 A171911 1 A171912 2 A171913 3 A171914 4 A171915 5 A171916 6 A171917 7 A171918 8 > -> $seq, $start {   my @seq = n-van-ecks($start);   # The task put qq:to/END/   Van Eck sequence OEIS:$seq; with the first term: $start First 10 terms: {@seq[^10]} Terms 991 through 1000: {@seq[990..999]} END }
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
#Racket
Racket
  -> (define (vfun . xs) (for-each displayln xs)) -> (vfun) -> (vfun 1) 1 -> (vfun 1 2 3 4) 1 2 3 4 -> (apply vfun (range 10 15)) 10 11 12 13 14  
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
#Raku
Raku
sub foo { .say for @_; say .key, ': ', .value for %_; }   foo 1, 2, command => 'buckle my shoe', 3, 4, order => 'knock at the door';
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
#Haskell
Haskell
import Data.Monoid ((<>))   type Vector a = [a]   type Scalar a = a   a, b, c, d :: Vector Int a = [3, 4, 5]   b = [4, 3, 5]   c = [-5, -12, -13]   d = [3, 4, 5, 6]   dot :: (Num t) => Vector t -> Vector t -> Scalar t dot u v | length u == length v = sum $ zipWith (*) u v | otherwise = error "Dotted Vectors must be of equal dimension."   cross :: (Num t) => Vector t -> Vector t -> Vector t cross u v | length u == 3 && length v == 3 = [ u !! 1 * v !! 2 - u !! 2 * v !! 1 , u !! 2 * head v - head u * v !! 2 , head u * v !! 1 - u !! 1 * head v ] | otherwise = error "Crossed Vectors must both be three dimensional."   scalarTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Scalar t scalarTriple q r s = dot q $ cross r s   vectorTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Vector t vectorTriple q r s = cross q $ cross r s   main :: IO () main = mapM_ putStrLn [ "a . b = " <> show (dot a b) , "a x b = " <> show (cross a b) , "a . b x c = " <> show (scalarTriple a b c) , "a x b x c = " <> show (vectorTriple a b c) , "a . d = " <> show (dot a d) ]
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
#Scala
Scala
object Isin extends App { val isins = Seq("US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3","AU0000VXGZA3", "FR0000988040")   private def ISINtest(isin: String): Boolean = { val isin0 = isin.trim.toUpperCase   def luhnTestS(number: String): Boolean = {   def luhnTestN(digits: Seq[Int]): Boolean = {   def checksum(digits: Seq[Int]): Int = { digits.reverse.zipWithIndex .foldLeft(0) { case (sum, (digit, i)) => if (i % 2 == 0) sum + digit else sum + (digit * 2) / 10 + (digit * 2) % 10 } % 10 }   checksum(digits) == 0 }   luhnTestN(number.map { c => assert(c.isDigit, s"$number has a non-digit error") c.asDigit }) }   if (!isin0.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$")) false else { val sb = new StringBuilder for (c <- isin0.substring(0, 12)) sb.append(Character.digit(c, 36)) luhnTestS(sb.toString) } }   isins.foreach(isin => println(f"$isin is ${if (ISINtest(isin)) "" else "not"}%s valid"))   }
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
#PureBasic
PureBasic
Procedure.d nBase(n.i,b.i) Define r.d,s.i=1 While n s*b r+(Mod(n,b)/s) n=Int(n/b) Wend ProcedureReturn r EndProcedure   Define.i b,c OpenConsole("van der Corput - Sequence") For b=2 To 5 Print("Base "+Str(b)+": ") For c=0 To 9 Print(StrD(nBase(c,b),5)+~"\t") Next PrintN("") Next Input()
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
#Python
Python
def vdc(n, base=2): vdc, denom = 0,1 while n: denom *= base n, remainder = divmod(n, base) vdc += remainder / denom return vdc
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Liberty_BASIC
Liberty BASIC
  dim lookUp$( 256)   for i =0 to 256 lookUp$( i) ="%" +dechex$( i) next i   url$ ="http%3A%2F%2Ffoo%20bar%2F"   print "Supplied URL '"; url$; "'" print "As string '"; url2string$( url$); "'"   end   function url2string$( i$) for j =1 to len( i$) c$ =mid$( i$, j, 1) if c$ ="%" then nc$ =chr$( hexdec( mid$( i$, j +1, 2))) url2string$ =url2string$ +nc$ j =j +2 else url2string$ =url2string$ +c$ end if next j end function  
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Lingo
Lingo
---------------------------------------- -- URL decodes a string -- @param {string} str -- @return {string} ---------------------------------------- on urldecode (str) res = "" ba = bytearray() len = str.length repeat with i = 1 to len c = str.char[i] if (c = "%") then -- fastest hex-to-dec conversion hack based on Lingo's rgb object ba.writeInt8(rgb(str.char[i+1..i+2]).blue) i = i + 2 else if (c = "+") then ba.writeInt8(32) else ba.writeInt8(chartonum(c)) end if end repeat ba.position = 1 return ba.readRawString(ba.length) end
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#Ksh
Ksh
#!/bin/ksh   # Find the corresponding UPC decimal representation of each, rejecting the error   # # Variables: # UPC_data_file="../upc.data" END_SEQ='# #' # Start and End sequence MID_SEQ=' # # ' # Middle sequence typeset -a CHK_ARR=( 3 1 3 1 3 1 3 1 3 1 3 1 ) integer bpd=7 # Number of bits per digit integer numdig=6 # Number of digits per "side" typeset -a umess=( '' 'Upside down') typeset -a udig=( 0001101 0011001 0010011 0111101 0100011 0110001 0101111 0111011 0110111 0001011 )   # # Functions: #   # # Function _validate(array) - verify result with CHK_ARR # function _validate { typeset _arr ; nameref _arr="$1" typeset _ifs ; _ifs="$2" typeset _dp _singlearr _oldIFS   _oldIFS=$IFS ; IFS=${_ifs} typeset -ia _singlearr=( ${_arr[@]} ) integer _dp=$(_dotproduct _singlearr CHK_ARR) IFS=${_oldIFS}   return $(( _dp % 10 )) }   # # Function _dotproduct(arr1, arr2) - return dot product # function _dotproduct { typeset _arr1 ; nameref _arr1="$1" typeset _arr2 ; nameref _arr2="$2" typeset _i _dp ; integer _i _dp   for (( _i=0; _i<${#_arr1[*]}; _i++ )); do (( _dp += ( _arr1[_i] * _arr2[_i] ) )) done echo ${_dp} }   # # Function _flipit(string) - return flipped string # function _flipit { typeset _buf ; _buf="$1" typeset _tmp ; unset _tmp   for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do _tmp="${_tmp}${_buf:${_i}:1}" done   echo "${_tmp}" }   # # Function _bitget(string, side) - return bitless string & bit # function _bitget { typeset _buff ; _buff="$1" typeset _side ; integer _side=$2 typeset _ubit _bit   _ubit=${_buff:0:1} [[ ${_ubit} == \# ]] && _bit=1 || _bit=0 (( _side )) && (( _bit = ! _bit ))   echo ${_buff#*${_ubit}} return ${_bit} }   # # Function _decode(upc_arr, digit_arr) # function _decode { typeset _uarr ; nameref _uarr="$1" # UPC code array typeset _darr ; nameref _darr="$2" # Decimal array   typeset _s _d _b _bit _digit _uarrcopy ; integer _s _d _b _bit typeset -a _uarrcopy=( ${_uarr[@]} )   for (( _s=0; _s<${#_uarr[*]}; _s++ )); do # each "side" for (( _d=0; _d<numdig; _d++ ))  ; do # each "digit" for (( _b=0; _b<bpd; _b++ )) ; do # each "bit" _uarr[_s]=$(_bitget ${_uarr[_s]} ${_s}) ; _bit=$? _digit="${_digit}${_bit}" done   _darr[_s]="${_darr[_s]} $(_todec ${_digit})" if (( $? )); then # May be upside-down typeset -a _uarr=( ${_uarrcopy[@]} ) # Replace return 1 fi unset _digit done done }   # # Function _todec(digit) - Return numeric digit from upc code # function _todec { typeset _bdig ; _bdig="$1" typeset _i ; integer _i   for (( _i=0; _i<${#udig[*]}; _i++ )); do [[ ${_bdig} == ${udig[_i]} ]] && echo ${_i} && return 0 done return 1 }   # # Function _parseUPC(str, arr) - parse UPS string into 2 ele array # function _parseUPC { typeset _buf ; typeset _buf="$1" typeset _arr ; nameref _arr="$2" typeset _pre _mid   _pre="${_buf%%${END_SEQ}*}" _buf="${_buf#*${_pre}}" # Strip preamble _buf="${_buf#*${END_SEQ}}" # Strip $SEQ   _arr[0]="${_buf:0:$((bpd * numdig))}" # Get the left hand digits _buf="${_buf#*${_arr[0]}}" # Strip left side digits   _mid="${_buf:0:5}" # Check the middle SEQ _buf="${_buf#*${MID_SEQ}}" # Strip $SEQ   _arr[1]="${_buf:0:$((bpd * numdig))}" # Get the right hand digits _buf="${_buf#*${_arr[1]}}" # Strip right side digits   _end="${_buf:0:3}" # Check the end SEQ _buf="${_buf#*${END_SEQ}}" # Strip $SEQ }   ###### # main # ######   oldIFS="$IFS" ; IFS='' while read; do [[ "$REPLY" == \;* ]] && continue   unset side_arr ; typeset -a side_arr # [0]=left [1]=right _parseUPC "$REPLY" side_arr   unset digit_arr ; typeset -a digit_arr # [0]=left [1]=right _decode side_arr digit_arr ; integer uflg=$? if (( uflg )); then # Flip sides and reverse UPC_code unset digit_arr ; typeset -a digit_arr # [0]=left [1]=right buff="$(_flipit "${side_arr[0]}")" side_arr[0]="$(_flipit "${side_arr[1]}")" side_arr[1]="${buff}" _decode side_arr digit_arr ; integer vflg=$? fi   (( ! vflg )) && _validate digit_arr "${oldIFS}" ; integer vflg=$? if (( vflg )); then print "INVALID DIGIT(S)" unset vflg else print "${digit_arr[*]} ${umess[uflg]}" unset uflg fi   done < ${UPC_data_file}
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#PowerShell
PowerShell
  function Update-ConfigurationFile { [CmdletBinding()] Param ( [Parameter(Mandatory=$false, Position=0)] [ValidateScript({Test-Path $_})] [string] $Path = ".\config.txt",   [Parameter(Mandatory=$false)] [string] $FavouriteFruit,   [Parameter(Mandatory=$false)] [int] $NumberOfBananas,   [Parameter(Mandatory=$false)] [int] $NumberOfStrawberries,   [Parameter(Mandatory=$false)] [ValidateSet("On", "Off")] [string] $NeedsPeeling,   [Parameter(Mandatory=$false)] [ValidateSet("On", "Off")] [string] $SeedsRemoved )   [string[]]$lines = Get-Content $Path   Clear-Content $Path   if (-not ($lines | Select-String -Pattern "^\s*NumberOfStrawberries" -Quiet)) { "", "# How many strawberries we have", "NumberOfStrawberries 0" | ForEach-Object {$lines += $_} }   foreach ($line in $lines) { $line = $line -replace "^\s*","" ## Strip leading whitespace   if ($line -match "[;].*\s*") {continue} ## Strip semicolons   switch -Regex ($line) { "(^$)|(^#\s.*)" ## Blank line or comment { $line = $line } "^FavouriteFruit\s*.*" ## Parameter FavouriteFruit { if ($FavouriteFruit) { $line = "FAVOURITEFRUIT $FavouriteFruit" } } "^NumberOfBananas\s*.*" ## Parameter NumberOfBananas { if ($NumberOfBananas) { $line = "NUMBEROFBANANAS $NumberOfBananas" } } "^NumberOfStrawberries\s*.*" ## Parameter NumberOfStrawberries { if ($NumberOfStrawberries) { $line = "NUMBEROFSTRAWBERRIES $NumberOfStrawberries" } } ".*NeedsPeeling\s*.*" ## Parameter NeedsPeeling { if ($NeedsPeeling -eq "On") { $line = "NEEDSPEELING" } elseif ($NeedsPeeling -eq "Off") { $line = "; NEEDSPEELING" } } ".*SeedsRemoved\s*.*" ## Parameter SeedsRemoved { if ($SeedsRemoved -eq "On") { $line = "SEEDSREMOVED" } elseif ($SeedsRemoved -eq "Off") { $line = "; SEEDSREMOVED" } } Default ## Whatever... { $line = $line } }   Add-Content $Path -Value $line -Force } }  
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Groovy
Groovy
word = System.in.readLine() num = System.in.readLine().toInteger()
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Haskell
Haskell
import System.IO (hFlush, stdout) main = do putStr "Enter a string: " hFlush stdout str <- getLine putStr "Enter an integer: " hFlush stdout num <- readLn :: IO Int putStrLn $ str ++ (show num)
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#NewLISP
NewLISP
; file: input-gui.lsp ; url: http://rosettacode.org/wiki/User_input/Graphical ; author: oofoe 2012-02-02   ; Colours (setq ok '(.8 1 .8) fail '(1 .5 .5))   ; Load library and initialize GUI server: (load (append (env "NEWLISPDIR") "/guiserver.lsp")) (gs:init)   ; Validation Callback   ; There is a bug in the "gs:get-text" function that causes it to fail ; silently if the text field is empty. Therfore, I set the field ; background to red first and only clear it if the field returns ; correctly. (define (validate) (gs:set-color 'string fail) (if (not (empty? (gs:get-text 'string))) (gs:set-color 'string ok))   (gs:set-color 'number fail) (if (= 75000 (int (gs:get-text 'number))) (gs:set-color 'number ok)) )   ; Create main window frame and set layout. (gs:frame 'main 100 100 256 128 "User Input/Graphical") (gs:set-flow-layout 'main "left" 4 4)   ; Create and add widgets. (gs:label 'instructions "Please enter a string and the number 75000:") (gs:text-field 'string 'validate 32) (gs:text-field 'number 'validate 8) (gs:button 'check 'validate "validate...") (gs:add-to 'main 'instructions 'string 'number 'check)   ; Show main window. (gs:set-visible 'main true)   ; Start event loop. (gs:listen)   ; No (exit) needed -- guiserver kills program on window close.  
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Processing
Processing
import java.nio.charset.StandardCharsets;   Integer[] code_points = {0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E};   void setup() { size(850, 230); background(255); fill(0); textSize(16); int tel_1 = 80; int tel_2 = 50; text("Char Name Unicode UTF-8 (encoding) Decoded", 40, 40); for (int cp : code_points) { byte[] encoded = new String(new int[]{cp}, 0, 1).getBytes(StandardCharsets.UTF_8); for (byte b : encoded) { text(hex(b), tel_2+530, tel_1); tel_2 += 30; } text(char(cp), 50, tel_1); text(Character.getName(cp), 100, tel_1); String unicode = hex(cp); while (unicode.length() > 4 && unicode.indexOf("0") == 0) unicode = unicode.substring(1); text("U+"+unicode, 450, tel_1); Character decoded = char(new String(encoded, StandardCharsets.UTF_8).codePointAt(0)); text(decoded, 750, tel_1); tel_1 += 30; tel_2 = 50; } }
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
#VBScript
VBScript
  Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then 'parse the scheme scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) 'parse the domain domain = Split(scheme(1),"/") 'check if the domain includes a username, password, and port If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password 'check if the domain have a port If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If 'parse the path if exist If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If   End Function   'test the convoluted function :-( WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:[email protected]") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")  
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
#MATLAB_.2F_Octave
MATLAB / Octave
function u = urlencoding(s) u = ''; for k = 1:length(s), if isalnum(s(k)) u(end+1) = s(k); else u=[u,'%',dec2hex(s(k)+0)]; end; end 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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   /* -------------------------------------------------------------------------- */ testcase() say say 'RFC3986' testcase('RFC3986') say say 'HTML5' testcase('HTML5') say return   /* -------------------------------------------------------------------------- */ method encode(url, varn) public static   variation = varn.upper opts = '' opts['RFC3986'] = '-._~' opts['HTML5'] = '-._*'   rp = '' loop while url.length > 0 parse url tc +1 url select when tc.datatype('A') then do rp = rp || tc end when tc == ' ' then do if variation = 'HTML5' then rp = rp || '+' else rp = rp || '%' || tc.c2x end otherwise do if opts[variation].pos(tc) > 0 then do rp = rp || tc end else do rp = rp || '%' || tc.c2x end end end end   return rp   /* -------------------------------------------------------------------------- */ method testcase(variation = '') public static   url = [ - 'http://foo bar/' - , 'mailto:"Ivan Aim" <[email protected]>' - , 'mailto:"Irma User" <[email protected]>' - , 'http://foo.bar.com/~user-name/_subdir/*~.html' - ]   loop i_ = 0 to url.length - 1 say url[i_] say encode(url[i_], variation) end i_   return  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Joy
Joy
[] unstack
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
#jq
jq
jq -n '1 as $x | (2 as $x | $x) | $x'
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.
#REXX
REXX
/*REXX pgm generates/displays the 'start ──► end' elements of the Van Eck sequence.*/ parse arg LO HI $ . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 10 /* " " " " " " */ if $=='' | $=="," then $= 0 /* " " " " " " */ $$=; z= $ /*$$: old seq: $: initial value of seq*/ do HI-1; z= wordpos( reverse(z), reverse($$) ); $$= $; $= $ z end /*HI-1*/ /*REVERSE allows backwards search in $.*/ /*stick a fork in it, we're all done. */ say 'terms ' LO " through " HI ' of the Van Eck sequence are: ' subword($,LO,HI-LO+1)
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.
#Ruby
Ruby
van_eck = Enumerator.new do |y| ar = [0] loop do y << (term = ar.last) # yield ar << (ar.count(term)==1 ? 0 : ar.size - 1 - ar[0..-2].rindex(term)) end end   ve = van_eck.take(1000) p ve.first(10), ve.last(10)  
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#RapidQ
RapidQ
SUBI printAll (...) FOR i = 1 TO ParamValCount PRINT ParamVal(i) NEXT i FOR i = 1 TO ParamStrCount PRINT ParamStr$(i) NEXT i END SUBI   printAll 4, 3, 5, 6, 4, 3 printAll 4, 3, 5 printAll "Rosetta", "Code", "Is", "Awesome!"
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
#REALbasic
REALbasic
  Sub PrintArgs(ParamArray Args() As String) For i As Integer = 0 To Ubound(Args) Print(Args(i)) Next End Sub  
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
#Icon_and_Unicon
Icon and Unicon
# record type to store a 3D vector record Vector3D(x, y, z)   # procedure to display vector as a string procedure toString (vector) return "(" || vector.x || ", " || vector.y || ", " || vector.z || ")" end   procedure dotProduct (a, b) return a.x * b.x + a.y * b.y + a.z * b.z end   procedure crossProduct (a, b) x := a.y * b.z - a.z * b.y y := a.z * b.x - a.x * b.z z := a.x * b.y - a.y * b.x return Vector3D(x, y, z) end   procedure scalarTriple (a, b, c) return dotProduct (a, crossProduct (b, c)) end   procedure vectorTriple (a, b, c) return crossProduct (a, crossProduct (b, c)) end   # main procedure, to run given test procedure main () a := Vector3D(3, 4, 5) b := Vector3D(4, 3, 5) c := Vector3D(-5, -12, -13)   writes ("A.B : " || toString(a) || "." || toString(b) || " = ") write (dotProduct (a, b)) writes ("AxB : " || toString(a) || "x" || toString(b) || " = ") write (toString(crossProduct (a, b))) writes ("A.(BxC) : " || toString(a) || ".(" || toString(b) || "x" || toString(c) || ") = ") write (scalarTriple (a, b, c)) writes ("Ax(BxC) : " || toString(a) || "x(" || toString(b) || "x" || toString(c) || ") = ") write (toString(vectorTriple (a, b, c))) end
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON @   CREATE OR REPLACE FUNCTION VALIDATE_ISIN ( IN IDENTIFIER VARCHAR(12) ) RETURNS SMALLINT -- ) RETURNS BOOLEAN BEGIN DECLARE CHECKSUM_FUNC CHAR(1); DECLARE CONVERTED VARCHAR(24); DECLARE I SMALLINT; DECLARE LENGTH SMALLINT; DECLARE RET SMALLINT DEFAULT 1; --DECLARE RET BOOLEAN DEFAULT FALSE; DECLARE CHAR_AT CHAR(1); DECLARE INVALID_CHAR CONDITION FOR SQLSTATE 'ISIN1';   SET CHAR_AT = SUBSTR(IDENTIFIER, 1, 1); IF (ASCII(CHAR_AT) < 65 OR 90 < ASCII(CHAR_AT)) THEN SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Country code with invalid characters'; END IF; SET CHAR_AT = SUBSTR(IDENTIFIER, 2, 1); IF (ASCII(CHAR_AT) < 65 OR 90 < ASCII(CHAR_AT)) THEN SIGNAL INVALID_CHAR SET MESSAGE_TEXT = 'Country code with invalid characters'; END IF;   -- Convert letters to numbers. SET I = 1; SET CONVERTED = ''; SET LENGTH = LENGTH(IDENTIFIER); WHILE (I <= LENGTH) DO SET CHAR_AT = SUBSTR(IDENTIFIER, I, 1); IF (48 <= ASCII(CHAR_AT) AND ASCII(CHAR_AT) <= 57) THEN SET CONVERTED = CONVERTED || CHAR_AT; ELSE SET CONVERTED = CONVERTED || (ASCII(CHAR_AT) - 55); END IF; SET I = I + 1; END WHILE;   CALL DBMS_OUTPUT.PUT_LINE(CONVERTED);   -- This function is implemented in Rosetta code. SET CHECKSUM_FUNC = LUHN_TEST(CONVERTED); IF (CHECKSUM_FUNC = 0) THEN SET RET = 0; --SET RET = TRUE; END IF;   RETURN RET; END @  
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
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ [] swap [ dup while base share /mod rot join swap again ] drop ] is digits ( n --> [ )   [ base put digits reverse dup 0 swap witheach [ base share rot * + ] base take rot size ** reduce ] is corput ( n n --> n/d )     5 times [ say "base " i^ 2 + dup echo say ": " 10 times [ i^ over corput vulgar$ echo$ sp sp ] cr drop ]
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
#Racket
Racket
#lang racket (define (van-der-Corput n base) (if (zero? n) 0 (let-values ([(q r) (quotient/remainder n base)]) (/ (+ r (van-der-Corput q base)) base))))
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#LiveCode
LiveCode
put urlDecode("http%3A%2F%2Ffoo%20bar%2F") & cr & \ urlDecode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Lua
Lua
function decodeChar(hex) return string.char(tonumber(hex,16)) end   function decodeString(str) local output, t = string.gsub(str,"%%(%x%x)",decodeChar) return output end   -- will print "http://foo bar/" print(decodeString("http%3A%2F%2Ffoo%20bar%2F"))
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
s=" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "; s//=Characters[StringSplit[#,"\n"]]&; s=%/.{"#"->0," "->1}; Map[BarcodeRecognize@*Image@*List][s]
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#Python
Python
#!/usr/bin/env python   #---------------------------------------------------------------------------- # STANDARD MODULES #---------------------------------------------------------------------------- import re import string     #---------------------------------------------------------------------------- # GLOBAL: VARIABLES #---------------------------------------------------------------------------- DISABLED_PREFIX = ';'     #---------------------------------------------------------------------------- # CLASS Option #---------------------------------------------------------------------------- class Option(object): """An option, characterized by its name and its (optional) value. and by its status, which can be enabled or disabled. If its value is None, it is regarded to as a boolean option with a value of true. """   #------------------------------------------------------------------------ def __init__(self, name, value=None, disabled=False, disabled_prefix=DISABLED_PREFIX): """Create an Option instance, setting its name to 'name' (always converted to a string) and its value to 'value'. If 'disabled' is True, the option is considered disabled, otherwise enabled. The string 'disabled_prefix' is used as a prefix when generating the string representation of the option. """ self.name = str(name) self.value = value self.disabled = bool(disabled) self.disabled_prefix = disabled_prefix   #------------------------------------------------------------------------ def __str__(self): """Return a string representation of the Option instance. This always includes the option name, followed by a space and the option value (if it is not None). If the option is disabled, the whole string is preprendend by the string stored in the instance attribute 'disabled_prefix' and a space. """ disabled = ('', '%s ' % self.disabled_prefix)[self.disabled] value = (' %s' % self.value, '')[self.value is None] return ''.join((disabled, self.name, value))   #------------------------------------------------------------------------ def get(self): """Return the option value. If the stored value is None, the option is regarded to as a boolean one and its enabled status is returned. Othrwise its value is returned. """ enabled = not bool(self.disabled) if self.value is None: value = enabled else: value = enabled and self.value return value     #---------------------------------------------------------------------------- # CLASS Config #---------------------------------------------------------------------------- class Config(object): """A set of configuration options and comment strings. """ # Regular expression matching a valid option line. reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'   #------------------------------------------------------------------------ def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX): """Initialize a Config instance, optionally reading the contents of the configuration file 'fname'. The string 'disabled_prefix' is used as a prefix when generating the string representation of the options. """ self.disabled_prefix = disabled_prefix self.contents = [] # Sequence of strings and Option instances. self.options = {} # Map an option name to an Option instance. self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix) if fname: self.parse_file(fname)   #------------------------------------------------------------------------ def __str__(self): """Return a string representation of the Config instance. This is just the concatenation of all the items stored in the attribute 'contents'. """ return '\n'.join(map(str, self.contents))   #------------------------------------------------------------------------ def parse_file(self, fname): """Parse all the lines of file 'fname' by applying the method 'parser_lines' on the file contents. """ with open(fname) as f: self.parse_lines(f) return self   #------------------------------------------------------------------------ def parse_lines(self, lines): """Parse all the lines of iterable 'lines' by invoking the method 'parse_line' for each line in 'lines'. """ for line in lines: self.parse_line(line) return self   #------------------------------------------------------------------------ def parse_line(self, line): """Parse the line 'line', looking for options. If an option line is found, spaces are stripped from the start and the end of 'line' and any non-printable character is removed as well. Only the first occurrence of an option is processed, all the other occurrences are ignored. A valid option is added to the instance attribute 'contents' (in order to preserve its position among the other lines). It is also added to the mapping stored in the instance attribute 'options'. Any non-option string is added the the instance attribute 'contents', except those lines starting with the string stored into the instance attribute 'disabled_prefix' which are not followed by any option name. """ s = ''.join(c for c in line.strip() if c in string.printable) moOPTION = self.creOPTION.match(s) if moOPTION: name = moOPTION.group('name').upper() if not name in self.options: self.add_option(name, moOPTION.group('value'), moOPTION.group('disabled')) else: if not s.startswith(self.disabled_prefix): self.contents.append(line.rstrip()) return self   #------------------------------------------------------------------------ def add_option(self, name, value=None, disabled=False): """Create a new Option instance, named 'name' (always converted to uppercase) with value 'value' and set its disabled status to 'disabled'. The Option instance is added to the instance attribute 'contents'. It is also added to the mapping stored in the instance attribute 'options'. """ name = name.upper() opt = Option(name, value, disabled) self.options[name] = opt self.contents.append(opt) return opt   #------------------------------------------------------------------------ def set_option(self, name, value=None, disabled=False): """Look for an option named 'name' (always converted to uppercase) among the options stored in the instance attribute 'options'. If it is not found, a new Option instance is created. In any case its value is set to 'value' and its disabled status to 'disabled'. """ name = name.upper() opt = self.options.get(name) if opt: opt.value = value opt.disabled = disabled else: opt = self.add_option(name, value, disabled) return opt   #------------------------------------------------------------------------ def enable_option(self, name, value=None): """Enable the option named 'name' (always converted to uppercase) and set its value to 'value'. If the option is not found, it is created and added to the end of the instance attribute 'contents'. """ return self.set_option(name, value, False)   #------------------------------------------------------------------------ def disable_option(self, name, value=None): """Disable the option named 'name' (always converted to uppercase) and set its value to 'value'. If the option is not found, it is created and added to the end of the instance attribute 'contents'. """ return self.set_option(name, value, True)   #------------------------------------------------------------------------ def get_option(self, name): """Return the value of the option named 'name' (always converted to uppercase). If the option is not found in the instance attribute 'options', None is returned. If the stored value is None, it is regarded to as a boolean option and its enable status is returned. Otherwise its value is returned. """ opt = self.options.get(name.upper()) value = opt.get() if opt else None return value     #---------------------------------------------------------------------------- # MAIN #---------------------------------------------------------------------------- if __name__ == '__main__': import sys cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None) cfg.disable_option('needspeeling') cfg.enable_option('seedsremoved') cfg.enable_option('numberofbananas', 1024) cfg.enable_option('numberofstrawberries', 62000) print cfg  
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#hexiscript
hexiscript
print "Enter a string: " let s scan str print "Enter a number: " let n scan int
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#HolyC
HolyC
U8 *s; s = GetStr("Enter a string: ");   U32 *n; do { n = GetStr("Enter 75000: "); } while(Str2I64(n) != 75000);   Print("Your string: %s\n", s); Print("75000: %d\n", Str2I64(n));
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Nim
Nim
import strutils import gintro/[glib, gobject, gtk, gio]   type MainWindow = ref object of ApplicationWindow strEntry: Entry intEntry: SpinButton   #---------------------------------------------------------------------------------------------------   proc displayValues(strval: string; intval: int) = ## Display a dialog window with the values entered by the user.   let dialog = newDialog() dialog.setModal(true) let label1 = newLabel(" String value is “$1”.".format(strval)) label1.setHalign(Align.start) dialog.contentArea.packStart(label1, true, true, 5) let msg = " Integer value is $1 which is ".format(intval) & (if intval == 75000: "right. " else: "wrong (expected 75000). ") let label2 = newLabel(msg) dialog.contentArea.packStart(label2, true, true, 5) discard dialog.addButton("OK", ord(ResponseType.ok)) dialog.showAll() discard dialog.run() dialog.destroy()   #---------------------------------------------------------------------------------------------------   proc onOk(button: Button; window: MainWindow) = ## Callback executed when the OK button has been clicked. let strval = window.strEntry.text() let intval = window.intEntry.value().toInt displayValues(strval, intval) if intval == 75_000: window.destroy()   #---------------------------------------------------------------------------------------------------   proc activate(app: Application) = ## Activate the application.   let window = newApplicationWindow(MainWindow, app) window.setTitle("User input")   let content = newBox(Orientation.vertical, 10) content.setHomogeneous(true) let grid = newGrid() grid.setColumnSpacing(30) let bbox = newButtonBox(Orientation.horizontal) bbox.setLayout(ButtonBoxStyle.spread)   let strLabel = newLabel("Enter some text") strLabel.setHalign(Align.start) window.strEntry = newEntry() grid.attach(strLabel, 0, 0, 1, 1) grid.attach(window.strEntry, 1, 0, 1, 1)   let intLabel = newLabel("Enter 75000") intLabel.setHalign(Align.start) window.intEntry = newSpinButtonWithRange(0, 80_000, 1) grid.attach(intLabel, 0, 1, 1, 1) grid.attach(window.intEntry, 1, 1, 1, 1)   let btnOk = newButton("OK")   bbox.add(btnOk)   content.packStart(grid, true, true, 0) content.packEnd(bbox, true, true, 0)   window.setBorderWidth(5) window.add(content)   discard btnOk.connect("clicked", onOk, window)   window.showAll()   #———————————————————————————————————————————————————————————————————————————————————————————————————   let app = newApplication(Application, "Rosetta.UserInput") discard app.connect("activate", activate) discard app.run()
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' System define Number NumberWidget Text StatusLabel WindowClosed GUI = td(action:OnClose return:WindowClosed lr(label(text:"Enter some text:" width:20) entry(return:Text glue:ew) glue:ew) lr(label(text:"Enter a number:" width:20) numberentry(max:100000 return:Number handle:NumberWidget) label(handle:StatusLabel width:20) glue:ew ) button(text:"Ok" glue:ew action:OnClose ) ) proc {OnClose} if {NumberWidget get($)} \= 75000 then {StatusLabel set(text:"Invalid value")} else {Window close} end end Window = {QTk.build GUI} {Window show} {Wait WindowClosed} {System.showInfo "You entered; "#Text#", "#Number} {Application.exit 0} end
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#PureBasic
PureBasic
#UTF8_codePointMaxByteCount = 4 ;UTF-8 encoding uses only a maximum of 4 bytes to encode a codepoint   Procedure UTF8_encode(x, Array encoded_codepoint.a(1)) ;x is codepoint to encode, the array will contain output ;Array encoded_codepoint() is used for output. ;After encode element zero holds the count of significant bytes in elements 1 to 4 If ArraySize(encoded_codepoint()) < #UTF8_codePointMaxByteCount ReDim encoded_codepoint.a(#UTF8_codePointMaxByteCount) EndIf   Select x Case 0 To $7F encoded_codepoint(0) = 1 encoded_codepoint(1) = x ;all 7 bits Case $80 To $7FF encoded_codepoint(0) = 2 encoded_codepoint(2) = (x & %00111111) | %10000000 ;lowest 6 bits encoded_codepoint(1) = (x >> 6) | %11000000 ;highest bits 7 -> 11 Case $800 To $FFFF encoded_codepoint(0) = 3 encoded_codepoint(3) = (x & %00111111) | %10000000 ;lowest 6 bits encoded_codepoint(2) = ((x >> 6) & %00111111) | %10000000 ;bits 7 -> 12 encoded_codepoint(1) = (x >> 12) | %11100000 ;highest bits 13 -> 16   Case $10000 To $10FFFF encoded_codepoint(0) = 4 encoded_codepoint(4) = (x & %00111111) | %10000000 ;lowest 6 bits encoded_codepoint(3) = ((x >> 6) & %00111111) | %10000000 ;bits 7 -> 12 encoded_codepoint(2) = ((x >> 12) & %00111111) | %10000000 ;bits 13 -> 18 encoded_codepoint(1) = (x >> 18) | %11110000 ;highest bits 19 -> 21 Default encoded_codepoint(0) = 0 ;error, codepoint is not valid and can't be encoded EndSelect EndProcedure   Procedure UTF8_decode(Array encoded_codepoint.a(1)) ;Array encoded_codepoint() holds the UTF-8 encoding in elements 1 to 4, element zero isn't used for decoding. Protected x = -1 ;initialzie with error value for possible improper encoding   If ArraySize(encoded_codepoint()) < #UTF8_codePointMaxByteCount ProcedureReturn x ;Input array was not dimensioned properly. EndIf   ;Determine the number of bytes in the UTF8 encoding by looking at first byte ;and then proceeding accordingly. Select encoded_codepoint(1) Case %00000000 To %01111111 ;1 byte encoding x = encoded_codepoint(1) Case %11000000 To %11011111 ;2 byte encoding x = (encoded_codepoint(1) & %00011111) << 6 ;last 5 bits only x | (encoded_codepoint(2) & %00111111) Case %11100000 To %11101111 ;3 byte encoding x = (encoded_codepoint(1) & %00001111) << 6 ;last 4 bits only x << 6 + (encoded_codepoint(2) & %00111111) x << 6 + (encoded_codepoint(3) & %00111111) Case %11110000 To %11110111 ;4 byte encoding x = (encoded_codepoint(1) & %00000111) << 6 ;last 3 bits only x << 6 + (encoded_codepoint(2) & %00111111) x << 6 + (encoded_codepoint(3) & %00111111) x << 6 + (encoded_codepoint(4) & %00111111) EndSelect   ProcedureReturn x EndProcedure   ;helper procedure to format output for this example Procedure.s formatOutput(c$, c, Array encoded_utf.a(1), dcp) ;character, codepooint, UTf8 encoding, decoded codepoint Protected o$, i, encoding$   o$ = " " + LSet(c$, 8) + LSet("U+" + RSet(Hex(c), 5, "0"), 10) For i = 1 To encoded_utf(0) encoding$ + RSet(Hex(encoded_utf(i)), 2, "0") + " " Next o$ + " " + LSet(encoding$, 11, " ") + " " + RSet(Hex(dcp), 5, "0")   ProcedureReturn o$ EndProcedure   DataSection ;unicode code points in hex unicode_codepoints: Data.i 5, $41, $F6, $416, $20AC, $1D11E ;The names for these codepoints are: latin capital letter a; latin small letter o With diaeresis ;cyrillic capital letter zhe; euro sign; musical symbol g clef. EndDataSection   ;read initial unicode codepoint values Restore unicode_codepoints Read num_codepoints num_codepoints - 1   Dim codepoint(num_codepoints) For i = 0 To num_codepoints Read codepoint(i) Next   ;This array is used for input and output from the UTF8 encode and decode procedures. After encoding its elements ;hold the byte count of the encoding followed by the respective bytes. For decoding element zero is not used and ;elements 1 To 4 holds the bytes to be decoded. Dim encoded_codepoint.a(#UTF8_codePointMaxByteCount) If OpenConsole("", #PB_UTF8) PrintN(LSet("", 11) + LSet("Unicode", 12) + LSet("UTF-8",14) + LSet("Decoded",12)) PrintN(LSet("Character", 11) + LSet("Code Point", 12) + LSet("Encoding",14) + LSet("Code Point",12)) PrintN(LSet("---------", 11) + LSet("----------", 12) + LSet("-----------",14) + LSet("-----------",12))   For i = 0 To num_codepoints UTF8_encode(codepoint(i), encoded_codepoint()) dcp = UTF8_decode(encoded_codepoint()) ;Decoded UTF-8 encoding should match original codepoint that was encoded. PrintN(formatOutput(Chr(codepoint(i)), codepoint(i), encoded_codepoint(), dcp)) Next Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#Vlang
Vlang
import net.urllib   const urls = ['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', 'foo://example.com:8042/over/there?name=ferret#nose' ]   fn main() { for url in urls { u := urllib.parse(url)? println(u) print_url(u) } }   fn print_url(u urllib.URL) { println(" Scheme: $u.scheme") if u.opaque != "" { println(" Opaque: $u.opaque") } if u.str() == '' { println(" Username: $u.user.username") if u.user.password != '' { println(" Password: $u.user.password") } } if u.host != "" { if u.port() != '' { println(" Host: ${u.hostname()}") println(" Port: ${u.port()}") } else { println(" Host: $u.host") } } if u.path != "" { println(" Path: $u.path") } if u.raw_query != "" { println(" RawQuery: $u.raw_query") m := u.query().data for q in m { println(" Key: $q.key Values: $q.value") } } if u.fragment != "" { println(" Fragment: $u.fragment") } }
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
#Wren
Wren
var urlParse = Fn.new { |url| var parseUrl = "URL = " + url var index if ((index = url.indexOf("//")) && index >= 0 && url[0...index].count { |c| c == ":" } == 1) { // parse the scheme var scheme = url.split("//") parseUrl = parseUrl + "\n" + "Scheme = " + scheme[0][0..-2] // parse the domain var domain = scheme[1].split("/") // check if the domain includes a username, password and port if (domain[0].contains("@")) { var cred = domain[0].split("@") var split = [cred[0], ""] if (cred[0].contains(".")) { split = cred[0].split(".") } else if (cred[0].contains(":")) { split = cred[0].split(":") } var username = split[0] var password = split[1] parseUrl = parseUrl + "\n" + "Username = " + username if (password != "") parseUrl = parseUrl + "\n" + "Password = " + password // check if the domain has a port if (cred[1].contains(":")) { split = cred[1].split(":") var host = split[0] var port = ":" + split[1] parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port } else { parseUrl = parseUrl + "\n" + "Domain = " + cred[1] } } else if (domain[0].contains(":") && !domain[0].contains("[") && !domain[0].contains("]")) { var split = domain[0].split(":") var host = split[0] var port = ":" + split[1] parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port } else if (domain[0].contains("[") && domain[0].contains("]:")) { var split = domain[0].split("]") var host = split[0] + "]" var port = ":" + split[1][1..-1] parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port } else { parseUrl = parseUrl + "\n" + "Domain = " + domain[0] } // parse the path if it exists if (domain.count > 1) { var path = "/" for (i in 1...domain.count) { if (i < domain.count - 1) { path = path + domain[i] + "/" } else if (domain[i].contains("?")) { var split = domain[i].split("?") path = path + split[0] if (domain[i].contains("#")) { var split2 = split[1].split("#") var query = split2[0] var fragment = split2[1] path = path + "\n" + "Query = " + query + "\n" + "Fragment = " + fragment } else { var query = split[1] path = path + "\n" + "Query = " + query } } else if (domain[i].contains("#")) { var split = domain[i].split("#") var fragment = split[1] path = path + split[0] + "\n" + "Fragment = " + fragment } else { path = path + domain[i] } } parseUrl = parseUrl + "\n" + "Path = " + path } } else if (url.contains(":")) { var index = url.indexOf(":") var scheme = url[0...index] parseUrl = parseUrl + "\n" + "Scheme = " + scheme + "\n" var path = url[index+1..-1] if (!path.contains("?")) { parseUrl = parseUrl + "Path = " + path } else { var split = path.split("?") var query = split[1] parseUrl = parseUrl + "Path = " + split[0] + "\n" if (!query.contains("#")) { parseUrl = parseUrl + "Query = " + query } else { split = query.split("#") var fragment = split[1] parseUrl = parseUrl + "Query = " + split[0] + "Fragment = " + fragment } } } else { parseUrl = parseUrl + "\n" + "Invalid!!!" } System.print(parseUrl) System.print() }   var urls = [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "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", "ssh://[email protected]", "https://bob:[email protected]/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=\%65\%6e\%63\%6F\%64\%65\%64" ] for (url in urls) urlParse.call(url)
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
#NewLISP
NewLISP
;; simple encoder ;; (source http://www.newlisp.org/index.cgi?page=Code_Snippets) (define (url-encode str) (replace {([^a-zA-Z0-9])} str (format "%%%2X" (char $1)) 0))   (url-encode "http://foo bar/")
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
#Nim
Nim
import cgi   echo encodeUrl("http://foo/bar/")
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
#Julia
Julia
#declaration/assignment, declaration is optional x::Int32 = 1 #datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals x = 1 #x is inferred as Int, which is Int32 for 32-bit machines, Int64 for 64-bit machines #variable reference julia>x 1   x = int8(1) #x is of type Int8 x = 1.0 #x is Float64 x = y = 1 #assign both x and y to 1 global x = 1 #assigns 1 to global variable x (used inside scope blocks) local x = 1 #assigns 1 to local variable x (used inside scope blocks) x = 'a' #x is a 'Char' type, designated by single quotes x = "a" #x is a 1-element string, designated by double quotes
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
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { /* read-only variables */ val i = 3 // type inferred to be Int val d = 2.4 // type inferred to be double val sh: Short = 2 // type specified as Short val ch = 'A' // type inferred to be Char val bt: Byte = 1 // type specified as Byte   /* mutable variables */ var s = "Hey" // type inferred to be String var l = 4L // type inferred to be Long var b: Boolean // type specified as Boolean, not initialized immediately var f = 4.4f // type inferred to be Float   b = true // now initialized println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f")   s = "Bye" // OK as mutable l = 5L // OK as mutable b = false // OK as mutable f = 5.6f // OK as mutable   println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f") }
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.
#Rust
Rust
fn van_eck_sequence() -> impl std::iter::Iterator<Item = i32> { let mut index = 0; let mut last_term = 0; let mut last_pos = std::collections::HashMap::new(); std::iter::from_fn(move || { let result = last_term; let mut next_term = 0; if let Some(v) = last_pos.get_mut(&last_term) { next_term = index - *v; *v = index; } else { last_pos.insert(last_term, index); } last_term = next_term; index += 1; Some(result) }) }   fn main() { let mut v = van_eck_sequence().take(1000); println!("First 10 terms of the Van Eck sequence:"); for n in v.by_ref().take(10) { print!("{} ", n); } println!("\nTerms 991 to 1000 of the Van Eck sequence:"); for n in v.skip(980) { print!("{} ", n); } println!(); }
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.
#Scala
Scala
  object VanEck extends App {   def vanEck(n: Int): List[Int] = {   def vanEck(values: List[Int]): List[Int] = if (values.size < n) vanEck(math.max(0, values.indexOf(values.head, 1)) :: values) else values   vanEck(List(0)).reverse }   val vanEck1000 = vanEck(1000) println(s"The first 10 terms are ${vanEck1000.take(10)}.") println(s"Terms 991 to 1000 are ${vanEck1000.drop(990)}.") }  
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
#REBOL
REBOL
rebol [ Title: "Variadic Arguments" ]   print-all: func [ args [block!] {the arguments to print} ] [ foreach arg args [print arg] ]   print-all [rebol works this way]
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
#REXX
REXX
print_all: procedure /* [↓] is the # of args passed.*/ do j=1 for arg() say arg(j) end /*j*/ return
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
#J
J
cross=: (1&|.@[ * 2&|.@]) - 2&|.@[ * 1&|.@]
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
#Tcl
Tcl
package require Tcl 8.6 ;# mostly needed for [assert]. Substitute a simpler one or a NOP if required.
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
#Transact-SQL
Transact-SQL
  CREATE FUNCTION dbo._ISINCheck( @strISIN VarChar(40) ) RETURNS bit AS BEGIN --*** Test an ISIN code and return 1 if it is valid, 0 if invalid. DECLARE @bValid bit;   SET @bValid = CASE WHEN @strISIN LIKE '[A-Z][A-Z][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9]' THEN 1 ELSE 0 END IF @bValid = 1 BEGIN DECLARE @strTest VarChar(40) = ''; DECLARE @strAdd VarChar(2); DECLARE @p INT = 0; WHILE @p < LEN(@strISIN) BEGIN SET @p = @p+1; SET @strAdd = SUBSTRING(@strISIN,@p,1); IF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55); SET @strTest = @strTest + @strAdd; END;   -- Proceed with Luhn test DECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values SET @p = 0; -- reset loop counter DECLARE @intValue INT; DECLARE @intSum INT = 0; -- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum WHILE @p < LEN(@strLuhn) BEGIN SET @p = @p+1; SET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string IF @p % 2 = 0 SET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1)) SET @intSum = @intSum + @intValue END -- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds SET @bValid = CASE WHEN @intSum % 10 = 0 THEN 1 ELSE 0 END END;   RETURN @bValid END  
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
#Raku
Raku
constant VdC = map { :2("0." ~ .base(2).flip) }, ^Inf; .say for VdC[^16];