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/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
#REXX
REXX
/*REXX program converts an integer (or a range) ──► a Van der Corput number in base 2.*/ numeric digits 1000 /*handle almost anything the user wants*/ parse arg a b . /*obtain the optional arguments from CL*/ if a=='' then parse value 0 10 with a b /*Not specified? Then use the defaults*/ if b=='' then b= a /*assume a range for a single number.*/   do j=a to b /*traipse through the range of numbers.*/ _= VdC( abs(j) ) /*convert absolute value of an integer.*/ leading= substr('-', 2 + sign(j) ) /*if needed, elide the leading sign. */ say leading || _ /*show number, with leading minus sign?*/ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ VdC: procedure; y= x2b( d2x( arg(1) ) ) + 0 /*convert to hexadecimal, then binary.*/ if y==0 then return 0 /*handle the special case of zero. */ return '.'reverse(y) /*heavy lifting is performed by REXX. */
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á".
#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) \\ convert to one byte per character using str$(string) acc$=str$(a$(0)) While k { \\ chr$() convert to UTF16LE \\ str$() convert to ANSI using locale (can be 1033 we can set it before as Locale 1033) \\ so chr$(0x93) give 0x201C \\ str$(chr$(0x93)) return one byte 93 in ANSI as string of one byte length \\ numbers are for UTF-8 so we have to preserve them acc$+=str$(Chr$(Eval("0x"+left$(a$(k^),2)))+Mid$(a$(k^),3)) } =acc$ } \\ decode from utf8 final$=DecodeUrl$("google.com/search?q=%60Abdu%27l-Bah%C3%A1") Print string$(final$ as utf8dec)="google.com/search?q=`Abdu'l-Bahá" final$=DecodeUrl$("http%3A%2F%2Ffoo%20bar%2F") Print string$(final$ as utf8dec)="http://foo bar/" } CheckIt  
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á".
#Maple
Maple
StringTools:-Decode("http%3A%2F%2Ffoo%20bar%2F", encoding=percent);
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.
#Nim
Nim
import algorithm, sequtils, strutils   const   LeftDigits = [" ## #", " ## #", " # ##", " #### #", " # ##", " ## #", " # ####", " ### ##", " ## ###", " # ##"]   RightDigits = LeftDigits.mapIt(it.multiReplace(("#", " "), (" ", "#")))   EndSentinel = "# #" MidSentinel = " # # "     template isEven(n: int): bool = (n and 1) == 0     proc decodeUPC(input: string) =   #.................................................................................................   proc decode(candidate: string): tuple[valid: bool, list: seq[int]] =   const Invalid = (false, @[])   var pos = 0 var next = pos + EndSentinel.len if candidate[pos..<next] == EndSentinel: pos = next else: return Invalid   for _ in 1..6: next = pos + 7 let i = LeftDigits.find(candidate[pos..<next]) if i >= 0: result.list.add i pos = next else: return Invalid   next = pos + MidSentinel.len if candidate[pos..<next] == MidSentinel: pos = next else: return Invalid   for _ in 1..6: next = pos + 7 let i = RightDigits.find(candidate[pos..<next]) if i >= 0: result.list.add i pos = next else: return Invalid   next = pos + EndSentinel.len if candidate[pos..<next] == EndSentinel: pos = next else: return Invalid   var sum = 0 for i, v in result.list: sum += (if i.isEven: 3 * v else: v) result.valid = sum mod 10 == 0   #.................................................................................................   var candidate = input.strip() let output = candidate.decode() if output.valid: echo output.list.join(", ") else: candidate.reverse() let output = candidate.decode() if output.valid: echo output.list.join(", "), " Upside down" elif output.list.len == 0: echo "Invalid digit(s)" else: echo "Invalid checksum: ", output.list.join(", ")     #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   const BarCodes = [ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", ]   for barcode in BarCodes: barcode.decodeUPC()
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
#Racket
Racket
  #lang racket   (require "options.rkt")     (read-options "options-file") (define-options needspeeling seedsremoved numberofbananas numberofstrawberries)   ;; Disable the needspeeling option (using a semicolon prefix) (set! needspeeling #f) ;; Enable the seedsremoved option by removing the semicolon and any ;; leading whitespace (set! seedsremoved ENABLE) ;; Change the numberofbananas parameter to 1024 (set! numberofbananas 1024) ;; Enable (or create if it does not exist in the file) a parameter for ;; numberofstrawberries with a value of 62000 (set! numberofstrawberries 62000)  
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
#Raku
Raku
conf-update --/needspeeling --seedsremoved --numberofbananas=1024 --numberofstrawberries=62000 test.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
#Icon_and_Unicon
Icon and Unicon
  procedure main () writes ("Enter something: ") s := read () write ("You entered: " || s)   writes ("Enter 75000: ") if (i := integer (read ())) then write (if (i = 75000) then "correct" else "incorrect") else write ("you must enter a number") end  
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
#Io
Io
string := File clone standardInput readLine("Enter a string: ") integer := File clone standardInput readLine("Enter 75000: ") asNumber
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
#Perl
Perl
use Wx;   package MyApp; use base 'Wx::App'; use Wx qw(wxHORIZONTAL wxVERTICAL wxALL wxALIGN_CENTER); use Wx::Event 'EVT_BUTTON';   our ($frame, $text_input, $integer_input);   sub OnInit {$frame = new Wx::Frame (undef, -1, 'Input window', [-1, -1], [250, 150]);   my $panel = new Wx::Panel($frame, -1); $text_input = new Wx::TextCtrl($panel, -1, ''); $integer_input = new Wx::SpinCtrl ($panel, -1, '', [-1, -1], [-1, -1], 0, 0, 100_000);   my $okay_button = new Wx::Button($panel, -1, 'OK'); EVT_BUTTON($frame, $okay_button, \&OnQuit);   my $sizer = new Wx::BoxSizer(wxVERTICAL); $sizer->Add($_, 0, wxALL | wxALIGN_CENTER, 5) foreach $text_input, $integer_input, $okay_button; $panel->SetSizer($sizer);   $frame->Show(1);}   sub OnQuit {print 'String: ', $text_input->GetValue, "\n"; print 'Integer: ', $integer_input->GetValue, "\n"; $frame->Close;}   # ---------------------------------------------------------------   package main;   MyApp->new->MainLoop;
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.
#Python
Python
  #!/usr/bin/env python3 from unicodedata import name     def unicode_code(ch): return 'U+{:04x}'.format(ord(ch))     def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()     if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
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.
#Racket
Racket
#lang racket   (define char-map '((LATIN-CAPITAL-LETTER-A . #\U0041) (LATIN-SMALL-LETTER-O-WITH-DIAERESIS . #\U00F6) (CYRILLIC-CAPITAL-LETTER-ZHE . #\U0416) (EURO-SIGN . #\U20AC) (MUSICAL-SYMBOL-G-CLEF . #\U1D11E)))   (for ((name.char (in-list char-map))) (define name (car name.char)) (define chr (cdr name.char)) (let ((bites (bytes->list (string->bytes/utf-8 (list->string (list chr)))))) (printf "~s\t~a\t~a\t~a\t~a~%" chr chr (map (curryr number->string 16) bites) (bytes->string/utf-8 (list->bytes bites)) name)))
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
#Oberon-2
Oberon-2
  MODULE URLEncoding; IMPORT Out := NPCT:Console, ADT:StringBuffer, URI := URI:String; VAR encodedUrl: StringBuffer.StringBuffer; BEGIN encodedUrl := NEW(StringBuffer.StringBuffer,512); URI.AppendEscaped("http://foo bar/","",encodedUrl); Out.String(encodedUrl.ToString());Out.Ln END URLEncoding.  
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
#Objeck
Objeck
  use FastCgi;   bundle Default { class UrlEncode { function : Main(args : String[]) ~ Nil { url := "http://foo bar/"; UrlUtility->Encode(url)->PrintLine(); } } }  
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
#Lambdatalk
Lambdatalk
  1) working in a global scope   {def A 3} -> A // A is in the global scope {def B 4} -> B // B is in the global scopel {def MUL {lambda {:x :y} {* :x :y}}} -> MUL // MUL is a global function {MUL {A} {B}} // using global variables -> 12   2) working in a local scope   {let // open local scope { // begin defining and assigning local variables {:a 3} // :a is local {:b 4} // :b is local {:mul {lambda {:x :y} {* :x :y}}} // :mul is a local function } // end defining and assigning local variables {:mul :a :b} // computing with local variables } // closing local scope -> 12  
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.
#SNOBOL4
SNOBOL4
define('eck(n)i,j')  :(eck_end) eck eck = array(n,0) i = 0 eouter i = lt(i,n - 1) i + 1  :f(return) j = i einner j = gt(j,0) j - 1  :f(eouter) eck<i + 1> = eq(eck<i>,eck<j>) i - j  :s(eouter)f(einner) eck_end   define('list(arr,start,stop)')  :(list_end) list list = list arr<start> ' ' start = lt(start,stop) start + 1  :s(list)f(return) list_end   ecks = eck(1000) output = list(ecks, 1, 10) output = list(ecks, 991, 1000) 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.
#Sidef
Sidef
func van_eck(n) {   var seen = Hash() var seq = [0] var prev = seq[-1]   for k in (1 ..^ n) { seq << (seen.has(prev) ? (k - seen{prev}) : 0) seen{prev} = k prev = seq[-1] }   seq }   say van_eck(10) say van_eck(1000).slice(991-1, 1000-1)
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
#Ring
Ring
  # Project : Variadic function   sum([1,2]) sum([1,2,3]) nums = [1,2,3,4] sum(nums)   func sum(nums) total = 0 for num = 1 to len(nums) total = total + num next showarray(nums) see " " + total + nl   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + " " next svect = left(svect, len(svect) - 1) see "" + svect + "]"  
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
#Ruby
Ruby
def print_all(*things) puts things 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
#Rust
Rust
// 20220106 Rust programming solution   macro_rules! print_all { ($($args:expr),*) => { $( println!("{}", $args); )* } }   fn main() { print_all!("Rosetta", "Code", "Is", "Awesome!"); }
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
#Java
Java
public class VectorProds{ public static class Vector3D<T extends Number>{ private T a, b, c;   public Vector3D(T a, T b, T c){ this.a = a; this.b = b; this.c = c; }   public double dot(Vector3D<?> vec){ return (a.doubleValue() * vec.a.doubleValue() + b.doubleValue() * vec.b.doubleValue() + c.doubleValue() * vec.c.doubleValue()); }   public Vector3D<Double> cross(Vector3D<?> vec){ Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue(); Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue(); Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue(); return new Vector3D<Double>(newA, newB, newC); }   public double scalTrip(Vector3D<?> vecB, Vector3D<?> vecC){ return this.dot(vecB.cross(vecC)); }   public Vector3D<Double> vecTrip(Vector3D<?> vecB, Vector3D<?> vecC){ return this.cross(vecB.cross(vecC)); }   @Override public String toString(){ return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">"; } }   public static void main(String[] args){ Vector3D<Integer> a = new Vector3D<Integer>(3, 4, 5); Vector3D<Integer> b = new Vector3D<Integer>(4, 3, 5); Vector3D<Integer> c = new Vector3D<Integer>(-5, -12, -13);   System.out.println(a.dot(b)); System.out.println(a.cross(b)); System.out.println(a.scalTrip(b, c)); System.out.println(a.vecTrip(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
#VBScript
VBScript
' Validate International Securities Identification Number - 03/03/2019 buf=buf&test("US0378331005")&vbCrLf buf=buf&test("US0373831005")&vbCrLf buf=buf&test("U50378331005")&vbCrLf buf=buf&test("US03378331005")&vbCrLf buf=buf&test("AU0000XVGZA3")&vbCrLf buf=buf&test("AU0000VXGZA3")&vbCrLf buf=buf&test("FR0000988040")&vbCrLf msgbox buf,,"Validate International Securities Identification Number"   function test(cc) dim err,c,r,s,i1,i2 if len(cc)=12 then for i=1 to len(cc) p=instr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1)) if p<>0 then c=c&(p-1) else err=1 next 'i for i=1 to 2 if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1))=0 then err=1 next 'i if err=0 then for i=len(c) to 1 step -1 r=r&mid(c,i,1) next 'i for i=1 to len(r) step 2 i1=i1+cint(mid(r,i,1)) next 'i for i=2 to len(r) step 2 ii=cint(mid(r,i,1))*2 if ii>=10 then ii=ii-9 i2=i2+ii next 'i s=cstr(i1+i2) if mid(s,len(s),1)="0" then msg="valid" else msg="invalid ??1" end if else msg="invalid ??2" end if else msg="invalid ??3" end if test=cc&" "&msg end function 'test
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
#Visual_Basic
Visual Basic
Function IsValidISIN(ByVal ISIN As String) As Boolean Dim s As String, c As String Dim i As Long If Len(ISIN) = 12 Then For i = 1 To Len(ISIN) c = UCase$(Mid(ISIN, i, 1)) Select Case c Case "A" To "Z" If i = 12 Then Exit Function s = s & CStr(Asc(c) - 55) Case "0" To "9" If i < 3 Then Exit Function s = s & c Case Else Exit Function End Select Next i IsValidISIN = LuhnCheckPassed(s) End If End Function
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
#Ring
Ring
  decimals(4) for base = 2 to 5 see "base " + string(base) + " : " for number = 0 to 9 see "" + corput(number, base) + " " next see nl next   func corput n, b vdc = 0 denom = 1 while n denom *= b rem = n % b n = floor(n/b) vdc += rem / denom end return vdc  
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
#Ruby
Ruby
def vdc(n, base=2) str = n.to_s(base).reverse str.to_i(base).quo(base ** str.length) end   (2..5).each do |base| puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ") 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á".
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
URLDecoding[url_] := StringReplace[url, "%" ~~ x_ ~~ y_ :> FromDigits[x ~~ y, 16]] //. StringExpression[x___, Longest[n__Integer], y___] :> StringExpression[x, FromCharacterCode[{n}, "UTF8"], y]
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á".
#MATLAB_.2F_Octave
MATLAB / Octave
function u = urldecoding(s) u = ''; k = 1; while k<=length(s) if s(k) == '%' && k+2 <= length(s) u = sprintf('%s%c', u, char(hex2dec(s((k+1):(k+2))))); k = k + 3; else u = sprintf('%s%c', u, s(k)); k = k + 1; end end 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.
#Perl
Perl
use strict; use warnings; use feature 'say';   sub decode_UPC { my($line) = @_; my(%pattern_to_digit_1,%pattern_to_digit_2,@patterns1,@patterns2,@digits,$sum);   for my $p (' ## #', ' ## #', ' # ##', ' #### #', ' # ##', ' ## #', ' # ####', ' ### ##', ' ## ###', ' # ##') { push @patterns1, $p; push @patterns2, $p =~ tr/# / #/r; }   $pattern_to_digit_1{$patterns1[$_]} = $_ for 0..$#patterns1; $pattern_to_digit_2{$patterns2[$_]} = $_ for 0..$#patterns2;   my $re = '\s*# #\s*' . "(?<match1>(?:@{[join '|', @patterns1]}){6})" . '\s*# #\s*' . "(?<match2>(?:@{[join '|', @patterns2]}){6})" . '\s*# #\s*'; $line =~ /^$re$/g || return;   my($match1,$match2) = ($+{match1}, $+{match2}); push @digits, $pattern_to_digit_1{$_} for $match1 =~ /(.{7})/g; push @digits, $pattern_to_digit_2{$_} for $match2 =~ /(.{7})/g; $sum += (3,1)[$_%2] * $digits[$_] for 0..11; $sum % 10 ? '' : join '', @digits; }   my @lines = ( ' # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ', ' # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ', ' # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ', ' # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ', ' # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ', ' # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ', ' # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ', ' # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ', ' # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ', ' # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ', );   for my $line (@lines) { say decode_UPC($line) // decode_UPC(join '', reverse split '', $line) // 'Invalid'; }  
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
#REXX
REXX
/*REXX program demonstrates how to update a configuration file (four specific tasks).*/ parse arg iFID oFID . /*obtain optional arguments from the CL*/ if iFID=='' | iFID=="," then iFID= 'UPDATECF.TXT' /*Not given? Then use default.*/ if oFID=='' | oFID=="," then oFID='\TEMP\UPDATECF.$$$' /* " " " " " */ call lineout iFID; call lineout oFID /*close the input and the output files.*/ $.=0 /*placeholder of the options detected. */ call dos 'ERASE' oFID /*erase a file (with no error message).*/ changed=0 /*nothing changed in the file (so far).*/ /* [↓] read the entire config file. */ do rec=0 while lines(iFID)\==0 /*read a record; bump the record count.*/ z=linein(iFID); zz=space(z) /*get record; elide extraneous blanks.*/ say '───────── record:' z /*echo the record just read ──► console*/ a=left(zz,1); _=space( translate(zz, ,';') ) /*_: is used to elide multiple ";" */ if zz=='' | a=='#' then do; call cpy z; iterate; end /*blank or a comment.*/ if _=='' then do; changed=1; iterate; end /*elide any semicolons; empty records.*/ parse upper var z op . /*obtain the option from the record. */ /* [↓] option may have leading or ···*/ if a==';' then do; parse upper var z 2 op . /*trailing blanks.*/ if op='SEEDSREMOVED' then call new space( substr(z, 2) ) call cpy z; $.op=1 /*write the Z record to the output file*/ iterate /*rec*/ /* ··· and then go read the next record*/ end if $.op then do; changed=1; iterate; end /*is the option already defined? */ $.op=1 /* [↑] Yes? Then delete it. */ if op=='NEEDSPEELING' then call new ";" z if op=='NUMBEROFBANANAS' then call new op 1024 if op=='NUMBEROFSTRAWBERRIES' then call new op 62000 call cpy z /*write the Z record to the output file*/ end /*rec*/   nos='NUMBEROFSTRAWBERRIES' /* [↓] Does NOS option need updating? */ if \$.nos then do; call new nos 62000; call cpy z; end /*update option.*/ call lineout iFID; call lineout oFID /*close the input and the output files.*/ if rec==0 then do; say "ERROR: input file wasn't found:" iFID; exit; end if changed then do /*possibly overwrite the input file. */ call dos 'XCOPY' oFID iFID '/y /q',">nul" /*quietly*/ say; say center('output file', 79, "▒") /*title. */ call dos 'TYPE' oFID /*display content of the output file. */ end call dos 'ERASE' oFID /*erase a file (with no error message).*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cpy: call lineout oFID, arg(1); return /*write one line of text ───► oFID. */ dos: ''arg(1) word(arg(2) "2>nul",1); return /*execute a DOS command (quietly). */ new: z=arg(1); changed=1; return /*use new Z, indicate changed record. */
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
#J
J
require 'misc' NB. load system script prompt 'Enter string: ' 0".prompt '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
#Java
Java
  import java.util.Scanner;   public class GetInput { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Enter a string: "); String str = s.nextLine(); System.out.print("Enter an integer: "); int i = Integer.parseInt(s.next()); } }
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
#Phix
Phix
-- demo\rosetta\User_Input_Graphical.exw include pGUI.e Ihandle dlg, label1, input1, label2, input2, OK, Cancel function ok_cb(Ihandle self) if self=OK then string in1 = IupGetAttribute(input1,"VALUE") integer in2 = IupGetInt(input2,"VALUE") string msg = sprintf(`"%s" and %d`,{in1,in2}) IupMessage("You entered",msg) -- (return IUP_CONTINUE if unhappy with input) end if return IUP_CLOSE end function IupOpen() label1 = IupLabel("Please enter a string") input1 = IupText(`VALUE="a string", EXPAND=HORIZONTAL`) label2 = IupLabel("and the number 75000") input2 = IupText("VALUE=75000, EXPAND=HORIZONTAL, MASK="&IUP_MASK_INT) OK = IupButton("OK", "ACTION", Icallback("ok_cb")) Cancel = IupButton("Cancel", "ACTION", Icallback("ok_cb")) sequence buttons = {IupFill(),OK,Cancel,IupFill()} Ihandle strbox = IupHbox({label1,input1},"ALIGNMENT=ACENTER, PADDING=5"), numbox = IupHbox({label2,input2},"ALIGNMENT=ACENTER, PADDING=5"), btnbox = IupHbox(buttons,"PADDING=40"), vbox = IupVbox({strbox, numbox, btnbox}, "MARGIN=5x5") if platform()!=JS then IupSetAttribute(btnbox,"NORMALIZESIZE","BOTH") IupSetAttribute(vbox,"GAP","5") end if dlg = IupDialog(vbox, `TITLE="User Input/Graphical"`) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if
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.
#Raku
Raku
say sprintf("%-18s %-36s|%8s| %7s |%14s | %s\n", 'Character|', 'Name', 'Ordinal', 'Unicode', 'UTF-8 encoded', 'decoded'), '-' x 100;   for < A ö Ж € 𝄞 😜 👨‍👩‍👧‍👦> -> $char { printf "  %-5s | %-43s | %6s | %-7s | %12s |%4s\n", $char, $char.uninames.join(','), $char.ords.join(' '), ('U+' X~ $char.ords».base(16)).join(' '), $char.encode('UTF8').list».base(16).Str, $char.encode('UTF8').decode; }
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
#Objective-C
Objective-C
NSString *normal = @"http://foo bar/"; NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@", encoded);
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
#OCaml
OCaml
$ ocaml # #use "topfind";; # #require "netstring";;   # Netencoding.Url.encode "http://foo bar/" ;; - : string = "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
#Lasso
Lasso
// declare thread variable, default type null var(x) $x->type // null   // declare local variable, default type null local(x) #x->type // null   // declare thread variable, initialize with a type, in this case integer var(x = integer)   // declare local variable, initialize with a type, in this case integer local(x = integer)   // assign a value to the thread var x $x = 12   // assign a value to the local var x $x = 177   // a var always has a data type, even if not declared - then it's null // a var can either be assigned a type using the name of the type, or a value that is by itself the type local(y = string) local(y = 'hello')   '\r' // demonstrating asCopyDeep and relationship between variables: local(original) = array('radish', 'carrot', 'cucumber', 'olive') local(originalaswell) = #original local(copy) = #original->asCopyDeep iterate(#original) => { loop_value->uppercase } #original // modified //array(RADISH, CARROT, CUCUMBER, OLIVE) '\r' #originalaswell // modified as well as it was not a deep copy //array(RADISH, CARROT, CUCUMBER, OLIVE) '\r' #copy // unmodified as it used ascopydeep //array(RADISH, CARROT, CUCUMBER, OLIVE)
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
#Liberty_BASIC
Liberty BASIC
  'In Liberty BASIC variables are either string or numeric. 'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname). 'There is no practical limit to the length of a variable name... up to ~2M characters. 'The variable names are case sensitive.   'assignments: -numeric variables. LB assumes integers unless assigned or calculated otherwise. 'Because of its Smalltalk heritage, LB integers are of arbitrarily long precision. 'They lose this if a calculation yields a non-integer, switching to floating point. i = 1 r = 3.14   'assignments -string variables. Any string-length, from zero to ~2M. t$ ="21:12:45" flag$ ="TRUE"   'assignments -1D or 2D arrays 'A default array size of 10 is available. Larger arrays need pre-'DIM'ming. height( 3) =1.87 dim height( 50) height( 23) =123.5 potential( 3, 5) =4.5 name$( 4) ="John"   'There are no Boolean /bit variables as such.   'Arrays in a main program are global. 'However variables used in the main program code are not visible inside functions and subroutines. 'They can be declared 'global' if such visibility is desired. 'Functions can receive variables by name or by reference.  
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.
#Swift
Swift
struct VanEckSequence: Sequence, IteratorProtocol { private var index = 0 private var lastTerm = 0 private var lastPos = Dictionary<Int, Int>()   mutating func next() -> Int? { let result = lastTerm var nextTerm = 0 if let v = lastPos[lastTerm] { nextTerm = index - v } lastPos[lastTerm] = index lastTerm = nextTerm index += 1 return result } }   let seq = VanEckSequence().prefix(1000)   print("First 10 terms of the Van Eck sequence:") for n in seq.prefix(10) { print(n, terminator: " ") } print("\nTerms 991 to 1000 of the Van Eck sequence:") for n in seq.dropFirst(990) { print(n, terminator: " ") } print()
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.
#Tcl
Tcl
## Mathematically, the first term has index "0", not "1". We do that, also.   set ::vE 0   proc vanEck {n} { global vE vEocc while {$n >= [set k [expr {[llength $vE] - 1}]]} { set kv [lindex $vE $k] ## value $kv @ $k is not yet stuffed into vEocc() lappend vE [expr {[info exists vEocc($kv)] ? $k - $vEocc($kv) : 0}] set vEocc($kv) $k } return [lindex $vE $n] }   proc show {func from to} { for {set n $from} {$n <= $to} {incr n} { append r " " [$func $n] } puts "${func}($from..$to) =$r" }   show vanEck 0 9 show vanEck 990 999
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
#Scala
Scala
def printAll(args: Any*) = args foreach println
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
#Scheme
Scheme
(define (print-all . things) (for-each (lambda (x) (display x) (newline)) things))
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
#Sidef
Sidef
func print_all(*things) { things.each { |x| say x }; }
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
#JavaScript
JavaScript
function dotProduct() { var len = arguments[0] && arguments[0].length; var argsLen = arguments.length; var i, j = len; var prod, sum = 0;   // If no arguments supplied, return undefined if (!len) { return; }   // If all vectors not same length, return undefined i = argsLen; while (i--) {   if (arguments[i].length != len) { return; // return undefined } }   // Sum terms while (j--) { i = argsLen; prod = 1;   while (i--) { prod *= arguments[i][j]; } sum += prod; } return sum; }   function crossProduct(a, b) {   // Check lengths if (a.length != 3 || b.length != 3) { return; }   return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]];   }   function scalarTripleProduct(a, b, c) { return dotProduct(a, crossProduct(b, c)); }   function vectorTripleProduct(a, b, c) { return crossProduct(a, crossProduct(b, c)); }   // Run tests (function () { var a = [3, 4, 5]; var b = [4, 3, 5]; var c = [-5, -12, -13];   alert( 'A . B: ' + dotProduct(a, b) + '\n' + 'A x B: ' + crossProduct(a, b) + '\n' + 'A . (B x C): ' + scalarTripleProduct(a, b, c) + '\n' + 'A x (B x C): ' + vectorTripleProduct(a, b, c) ); }());
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Imports System.Text.RegularExpressions   Module Module1 ReadOnly IsinRegex As New Regex("^[A-Z]{2}[A-Z0-9]{9}\d$", RegexOptions.Compiled)   Function DigitValue(c As Char) As Integer Dim temp As Integer If Asc(c) >= Asc("0"c) AndAlso Asc(c) <= Asc("9"c) Then temp = Asc(c) - Asc("0"c) Else temp = Asc(c) - Asc("A"c) + 10 End If Return temp End Function   Function LuhnTest(number As String) As Boolean Return number.Select(Function(c, i) (AscW(c) - 48) << ((number.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0 End Function   Function Digitize(isin As String) As String Return String.Join("", isin.Select(Function(c) $"{DigitValue(c)}")) End Function   Function IsValidIsin(isin As String) As Boolean Return IsinRegex.IsMatch(isin) AndAlso LuhnTest(Digitize(isin)) End Function   Sub Main() Dim isins() = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" }   For Each isin In isins If IsValidIsin(isin) Then Console.WriteLine("{0} is valid", isin) Else Console.WriteLine("{0} is not valid", isin) End If Next End Sub   End Module
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Rust
Rust
  /// Van der Corput sequence for any base, based on C languange example from Wikipedia. pub fn corput(nth: usize, base: usize) -> f64 { let mut n = nth; let mut q: f64 = 0.0; let mut bk: f64 = 1.0 / (base as f64);   while n > 0_usize { q += ((n % base) as f64)*bk; n /= base; bk /= base as f64; } q }   fn main() { for base in 2_usize..=5_usize { print!("Base {}:", base); for i in 1_usize..=10_usize { let c = corput(i, base); print!(" {:.6}", c) } println!(""); } }    
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
#Scala
Scala
object VanDerCorput extends App { def compute(n: Int, base: Int = 2) = Iterator.from(0). scanLeft(1)((a, _) => a * base). map(b => (n - 1) / b -> b). takeWhile(_._1 != 0). foldLeft(0d)((a, b) => a + (b._1 % base).toDouble / b._2 / base)   val n = scala.io.StdIn.readInt val b = scala.io.StdIn.readInt (1 to n).foreach(x => println(compute(x, b))) }
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á".
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   url = [ - 'http%3A%2F%2Ffoo%20bar%2F', - 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E', - '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' - ]   loop u_ = 0 to url.length - 1 say url[u_] say DecodeURL(url[u_]) say end u_   return   method DecodeURL(arg) public static   Parse arg encoded decoded = '' PCT = '%'   loop label e_ while encoded.length() > 0 parse encoded head (PCT) +1 code +2 tail decoded = decoded || head select when code.strip('T').length() = 2 & code.datatype('X') then do code = code.x2c() decoded = decoded || code end when code.strip('T').length() \= 0 then do decoded = decoded || PCT tail = code || tail end otherwise do nop end end encoded = tail end e_   return decoded  
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.
#Phix
Phix
with javascript_semantics constant numbers = {" ## #", -- 0 " ## #", -- 1 " # ##", -- 2 " #### #", -- 3 " # ##", -- 4 " ## #", -- 5 " # ####", -- 6 " ### ##", -- 7 " ## ###", -- 8 " # ##"} -- 9 procedure decode(string bar_code) bar_code = trim(bar_code) if length(bar_code)=95 and bar_code[1..3]="# #" and bar_code[46..50]=" # # " and bar_code[93..95]="# #" then for reversed=false to true do sequence r = {} for i=1 to 12 do integer st = iff(i<=6?i*7-3:i*7+2) string number = bar_code[st..st+6] if i>6 then number = substitute_all(number," #X","X #") end if r &= find(number,numbers)-1 end for if not find(-1,r) then if remainder(sum(sq_mul(r,{3,1,3,1,3,1,3,1,3,1,3,1})),10) then printf(1,"invalid checksum\n") else printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")}) end if return end if bar_code = reverse(bar_code) end for end if printf(1,"invalid\n") end procedure constant bar_codes = split(""" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ""","\n",true) for i=1 to length(bar_codes) do decode(bar_codes[i]) end for
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
#Ruby
Ruby
require 'stringio'   class ConfigFile   # create a ConfigFile object from a file def self.file(filename) fh = File.open(filename) obj = self.new(fh) obj.filename = filename fh.close obj end   # create a ConfigFile object from a string def self.data(string) fh = StringIO.new(string) obj = self.new(fh) fh.close obj end   def initialize(filehandle) @lines = filehandle.readlines @filename = nil tidy_file end attr :filename   def save() if @filename File.open(@filename, "w") {|f| f.write(self)} end end   def tidy_file() @lines.map! do |line| # remove leading whitespace line.lstrip!   if line.match(/^#/) # Lines beginning with hash symbols should not be manipulated and left # unchanged in the revised file. line else # replace double semicolon prefixes with just a single semicolon line.sub!(/^;+\s+/, "; ")   if line.match(/^; \s*$/) # Any lines beginning with a semicolon or groups of semicolons, but no # following option should be removed line = "" else # remove ... any trailing whitespace on the lines line = line.rstrip + "\n"   # Whitespace between the option and paramters should consist only of a # single space if m = line.match(/^(; )?([[:upper:]]+)\s+(.*)/) line = (m[1].nil? ? "" : m[1]) + format_line(m[2], m[3]) end end   line end end end   def format_line(option, value) "%s%s\n" % [option.upcase.strip, value.nil? ? "" : " " + value.to_s.strip] end   # returns the index of the option, or nil if not found def find_option(option) @lines.find_index {|line| line.match(/^#{option.upcase.strip}\b/)} end   # uncomments a disabled option def enable_option(option) if idx = find_option("; " + option) @lines[idx][/^; /] = "" end end   # comment a line with a semi-colon def disable_option(option) if idx = find_option(option) @lines[idx][/^/] = "; " end end   # add an option, or change the value of an existing option. # use nil for the value to set a boolean option def set_value(option, value) if idx = find_option(option) @lines[idx] = format_line(option, value) else @lines << format_line(option, value) end end   def to_s @lines.join('') end end     config = ConfigFile.data(DATA.read) config.disable_option('needspeeling') config.enable_option('seedsremoved') config.set_value('numberofbananas', 1024) config.set_value('numberofstrawberries', 62000) puts config     __END__ # 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
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
#JavaScript
JavaScript
WScript.Echo("Enter a string"); var str = WScript.StdIn.ReadLine();   var val = 0; while (val != 75000) { WScript.Echo("Enter the integer 75000"); val = parseInt( WScript.StdIn.ReadLine() ); }
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
#Joy
Joy
  "Enter a string: " putchars stdin fgets "Enter a number: " putchars stdin fgets 10 strtol.  
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
#PicoLisp
PicoLisp
(and (call 'sh "-c" (pack "dialog \ --inputbox 'Input a string' 8 60 \ --inputbox 'Input a number' 8 20 \ 2>" (tmp "dlg") ) ) (split (in (tmp "dlg") (line)) "^I") (cons (pack (car @)) (format (cadr @))) )
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
#PowerBASIC
PowerBASIC
FUNCTION PBMAIN () AS LONG result$ = INPUTBOX$("Enter a string.") MSGBOX result$ DO 'This assumes that 75000 is the ONLY valid input. result$ = INPUTBOX$("Enter the number 75000.") IF VAL(result$) <> 75000 THEN MSGBOX "You need to enter 75000!" ELSE MSGBOX "You entered the right number." EXIT DO END IF LOOP END FUNCTION
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.
#Ruby
Ruby
  character_arr = ["A","ö","Ж","€","𝄞"] for c in character_arr do puts "Character: " + c.encode("utf-8") puts "Code-Point: #{c.encode("utf-8").ord.to_s(16).upcase}" puts "Code-Units: " + c.each_byte.map { |n| '%02X ' % (n & 0xFF) }.join puts "" 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.
#Rust
Rust
fn main() { let chars = vec!('A', 'ö', 'Ж', '€', '𝄞'); chars.iter().for_each(|c| { let mut encoded = vec![0; c.len_utf8()]; c.encode_utf8(&mut encoded); let decoded = String::from_utf8(encoded.to_vec()).unwrap(); let encoded_string = encoded.iter().fold(String::new(), |acc, val| format!("{}{:X}", acc, val)); println!("Character: {}, Unicode:{}, UTF-8 encoded:{}, Decoded: {}", c, c.escape_unicode(), encoded_string , decoded); }); }  
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
#ooRexx
ooRexx
sub urlencode { my $s = shift; $s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg; $s =~ tr/ /+/; return $s; }   print urlencode('http://foo bar/')."\n";  
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
#Perl
Perl
sub urlencode { my $s = shift; $s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg; $s =~ tr/ /+/; return $s; }   print urlencode('http://foo bar/')."\n";  
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
#Lingo
Lingo
x = 23 y = "Hello world!" z = TRUE -- same effect as z = 1
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Logo
Logo
make "g1 0 name 2 "g2  ; same as make with parameters reversed global "g3  ; no initial value to func :x make "g4 4  ; still global localmake "L1 6 local ["L2 "L3]  ; local variables, collection syntax func2 :g4 print :L2  ; 9, modified by func2 print :L3  ; L3 has no value, was not modified by func2 end to func2 :y make "g3 :y make "L2 :L1 + 3  ; dynamic scope: can see variables of callers localmake "L3 5  ; locally override L3 from caller (print :y :L1 :L2 :L3)  ; 4 6 9 5 end print :g4  ; 4 print :L1  ; L1 has no value print name? "L1  ; false, L1 is not bound in the current scope
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
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.
#Vlang
Vlang
fn main() { max := 1000 mut a := []int{len: max} // all zero by default for n in 0..max-1 { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } println("The first ten terms of the Van Eck sequence are:") println(a[..10]) println("\nTerms 991 to 1000 of the sequence are:") println(a[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
#Slate
Slate
define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].   printAll applyTo: #(4 3 5 6 4 3). printAll applyTo: #('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
#Swift
Swift
func printAll<T>(things: T...) { // "things" is a [T] for i in things { print(i) } }
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
#Tcl
Tcl
proc print_all {args} {puts [join $args \n]}   print_all 4 3 5 6 4 3 print_all 4 3 5 print_all Rosetta Code Is Awesome!   set things {Rosetta Code Is Awesome!}   print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all print_all {*}$things ;# ==> correct: passes each element of the list to the procedure
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
#jq
jq
def dot_product(a; b): reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );   # for 3d vectors def cross_product(a;b): [ a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0] ];   def scalar_triple_product(a;b;c): dot_product(a; cross_product(b; c));   def vector_triple_product(a;b;c): cross_product(a; cross_product(b; c));   def main: [3, 4, 5] as $a | [4, 3, 5] as $b | [-5, -12, -13] as $c | "a . b = \(dot_product($a; $b))", "a x b = [\( cross_product($a; $b) | map(tostring) | join (", ") )]" , "a . (b x c) = \( scalar_triple_product ($a; $b; $c)) )", "a x (b x c) = [\( vector_triple_product($a; $b; $c)|map(tostring)|join (", ") )]" ;
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
#Vlang
Vlang
import regex   const ( inc = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], ] )   fn valid_isin(n string) bool { mut r,_,_ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\d$') if !r.matches_string(n) { return false } mut sum := 0 mut p := 0 for i := 10; i >= 0; i-- { p = 1 - p mut d := n[i..i+1].int() if d < 'A'.int() { sum += inc[p][d-'0'.int()] } else { d -= 'A'.int() sum += inc[p][d%10] p = 1 - p sum += inc[p][d/10+1] } } sum += n[11..12].int() - '0'.int() return sum%10 == 0 }   struct Testcases { isin string valid bool }   fn main(){ testcases := [ Testcases{"US0378331005", true}, Testcases{"US0373831005", false}, Testcases{"U50378331005", false}, Testcases{"US03378331005", false}, Testcases{"AU0000XVGZA3", true}, Testcases{"AU0000VXGZA3", true}, Testcases{"FR0000988040", true}, ]   for testcase in testcases { actual := valid_isin(testcase.isin) if actual != testcase.valid { println("expected ${testcase.valid} for ${testcase.isin}, got $actual") } } }
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
#Wren
Wren
import "/str" for Char import "/trait" for Stepped import "/fmt" for Conv, Fmt   var luhn = Fn.new { |s| s = s[-1..0] var s1 = Stepped.new(s, 2).reduce(0) { |sum, d| sum + d.bytes[0] - 48 } var s2 = Stepped.new(s[1..-1], 2).reduce(0) { |sum, d| var d2 = (d.bytes[0] - 48) * 2 return sum + ((d2 > 9) ? d2%10 + 1 : d2) } return (s1 + s2)%10 == 0 }   var isin = Fn.new { |s| if (!(s is String && s.count == 12)) return false for (i in 0..11) { var c = s[i] if (i <= 1) { if (!Char.isUpper(c)) return false } else if (i >= 2 && i <= 10) { if (!Char.isUpper(c) && !Char.isDigit(c)) return false } else { if (!Char.isDigit(c)) return false } } var dec = "" for (i in 0...s.count) dec = dec + "%(Conv.atoi(s[i], 36))" return luhn.call(dec) }   var tests = [ "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" ]   for (test in tests) { var ans = (isin.call(test)) ? "valid" : "not valid" System.print("%(Fmt.s(-13, test)) -> %(ans)") }
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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const func float: vdc (in var integer: number, in integer: base) is func result var float: vdc is 0.0; local var integer: denom is 1; var integer: remainder is 0; begin while number <> 0 do denom *:= base; remainder := number rem base; number := number div base; vdc +:= flt(remainder) / flt(denom); end while; end func;   const proc: main is func local var integer: base is 0; var integer: number is 0; begin for base range 2 to 5 do writeln; writeln("Base " <& base); for number range 0 to 9 do write(vdc(number, base) digits 6 <& " "); end for; writeln; end for; end func;
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
#Sidef
Sidef
func vdc(value, base=2) { while (value[-1] > 0) { value.append(value[-1] / base -> int) } var (x, sum) = (1, 0) value.each { |i| sum += ((i % base) / (x *= base)) } return sum }   for base in (2..5) { var seq = 10.of {|i| vdc([i], base) } "base %d: %s\n".printf(base, seq.map{|n| "%.4f" % n}.join(', ')) }
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á".
#NewLISP
NewLISP
;; universal decoder, works for ASCII and UTF-8 ;; (source http://www.newlisp.org/index.cgi?page=Code_Snippets) (define (url-decode url (opt nil)) (if opt (replace "+" url " ")) (replace "%([0-9a-f][0-9a-f])" url (pack "b" (int $1 0 16)) 1))   (url-decode "http%3A%2F%2Ffoo%20bar%2F")
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á".
#Nim
Nim
import cgi   echo decodeUrl("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.
#PicoLisp
PicoLisp
(de l2n (Lst) (case Lst ((0 0 0 1 1 0 1) 0) ((0 0 1 1 0 0 1) 1) ((0 0 1 0 0 1 1) 2) ((0 1 1 1 1 0 1) 3) ((0 1 0 0 0 1 1) 4) ((0 1 1 0 0 0 1) 5) ((0 1 0 1 1 1 1) 6) ((0 1 1 1 0 1 1) 7) ((0 1 1 0 1 1 1) 8) ((0 0 0 1 0 1 1) 9) ) ) (de convs (Lst Flg) (make (for L Lst (link (if2 (= "#" L) Flg 0 1 1 0) ) ) ) ) (de getL (Lst) (make (cut 3 'Lst) (do 6 (link (convs (cut 7 'Lst))) ) (cut 5 'Lst) (do 6 (link (convs (cut 7 'Lst) T)) ) ) ) (de parse (Str) (let Lst (make (link (clip (chop Str))) (link (reverse (car (made)))) ) (find '((N) (fully num? N)) (mapcar '((L) (mapcar l2n (getL L))) Lst) ) ) ) (de upc (Str) (let Lst (parse Str) (cons Lst (% (apply + (mapcar * Lst (circ 3 1))) 10 ) ) ) ) (setq *U (quote " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ) ) (for L (mapcar upc *U) (println (if (car L) @ 'invalid)) )
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
#Tcl
Tcl
package require Tcl 8.6 oo::class create Config { variable filename contents constructor fileName { set filename $fileName set contents {} try { set f [open $filename] ### Sanitize during input foreach line [split [read $f] \n] { if {[string match "#*" $line]} { lappend contents $line continue } if {[regexp {^;\W*$} $line]} continue set line [string trim [regsub -all {[^\u0020-\u007e]} $line {}]] if {[regexp {^(\W*)(\w+)(.*)$} $line -> a b c]} { set line "[regsub -all {^;+} $a {;}][string toupper $b]$c" } lappend contents $line } } finally { if {[info exists f]} { close $f } } } method save {} { set f [open $filename w] puts $f [join $contents \n] close $f }   # Utility methods (not exposed API) method Transform {pattern vars replacement} { set matched 0 set line -1 set RE "(?i)^$pattern$" foreach l $contents { incr line if {[uplevel 1 [list regexp $RE $l -> {*}$vars]]} { if {$matched} { set contents [lreplace $contents $line $line] incr line -1 } else { lset contents $line [uplevel 1 [list subst $replacement]] } set matched 1 } } return $matched } method Format {k v} { set v " [string trimleft $v]" return "[string toupper $k][string trimright $v]" }   # Public API for modifying options method enable {option} { if {![my Transform ";?\\s*($option)\\M\s*(.*)" {k v} \ {[my Format $k $v]}]} { lappend contents [my Format $option ""] } } method disable {option} { if {![my Transform ";?\\s*($option)\\M\s*(.*)" {k v} \ {; [my Format $k $v]}]} { lappend contents "; [my Format $option ""]" } } method set {option {value ""}} { if {![my Transform ";?\\s*($option)\\M.*" k {[my Format $k $value]}]} { lappend contents [my Format $option $value] } } }
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
#jq
jq
def read(int): null | until( . == int; "Expecting \(int)" | stderr | input);   def read_string: null | until( type == "string"; "Please enter a string" | stderr | input);   (read_string | "I see the string: \(.)"), (read(75000) | "I see the expected 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
#Julia
Julia
  print("String? ") y = readline() println("Your input was \"", y, "\".\n") print("Integer? ") y = readline() try y = parse(Int, y) println("Your input was \"", y, "\".\n") catch println("Sorry, but \"", y, "\" does not compute as an integer.") end  
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
#PowerShell
PowerShell
#region Define the Windows Form [Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")   $Form1 = New-Object System.Windows.Forms.Form $label1 = New-Object System.Windows.Forms.Label $label2 = New-Object System.Windows.Forms.Label $txtInputText = New-Object System.Windows.Forms.TextBox $txtInputNumber = New-Object System.Windows.Forms.TextBox $btnAccept = New-Object System.Windows.Forms.Button $label3 = New-Object System.Windows.Forms.Label $btnCancel = New-Object System.Windows.Forms.Button $SuspendLayout # # label1 # $label1.AutoSize = $true $label1.Location = New-Object System.Drawing.Point(23, 36) $label1.Name = "label1" $label1.Size = New-Object System.Drawing.Size(34, 13) $label1.TabIndex = 0 $label1.Text = "String" # # label2 # $label2.AutoSize = $true $label2.Location = New-Object System.Drawing.Point(13, 62) $label2.Name = "label2" $label2.Size = New-Object System.Drawing.Size(44, 13) $label2.TabIndex = 1 $label2.Text = "Number" # # txtInputText # $txtInputText.Location = New-Object System.Drawing.Point(63, 33) $txtInputText.Name = "txtInputText" $txtInputText.Size = New-Object System.Drawing.Size(100, 20) $txtInputText.TabIndex = 0 # # txtInputNumber # $txtInputNumber.Location = New-Object System.Drawing.Point(63, 59) $txtInputNumber.Name = "txtInputNumber" $txtInputNumber.Size = New-Object System.Drawing.Size(100, 20) $txtInputNumber.TabIndex = 1 $txtInputNumber.Text = "75000" # # btnAccept # $btnAccept.DialogResult = [System.Windows.Forms.DialogResult]::OK $btnAccept.Location = New-Object System.Drawing.Point(16, 94) $btnAccept.Name = "btnAccept" $btnAccept.Size = New-Object System.Drawing.Size(75, 23) $btnAccept.TabIndex = 2 $btnAccept.Text = "Accept" $btnAccept.UseVisualStyleBackColor = $true $btnAccept.add_Click({$rc="Accept"; $Form1.Close()}) # # label3 # $label3.AutoSize = $true $label3.Location = New-Object System.Drawing.Point(13, 9) $label3.Name = "label3" $label3.Size = New-Object System.Drawing.Size(173, 13) $label3.TabIndex = 5 $label3.Text = "Please input a string and a number:" # # btnCancel # $btnCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $btnCancel.Location = New-Object System.Drawing.Point(97, 94) $btnCancel.Name = "btnCancel" $btnCancel.Size = New-Object System.Drawing.Size(75, 23) $btnCancel.TabIndex = 3 $btnCancel.Text = "Cancel" $btnCancel.UseVisualStyleBackColor = $true # # Form1 # $Form1.AcceptButton = $btnAccept $Form1.CancelButton = $btnCancel $Form1.ClientSize = New-Object System.Drawing.Size(196, 129) $Form1.ControlBox = $false $Form1.Controls.Add($btnCancel) $Form1.Controls.Add($label3) $Form1.Controls.Add($btnAccept) $Form1.Controls.Add($txtInputNumber) $Form1.Controls.Add($txtInputText) $Form1.Controls.Add($label2) $Form1.Controls.Add($label1) $Form1.Name = "Form1" $Form1.Text = "RosettaCode"   #endregion Define the Windows Form   ### Show the input form $f = $Form1.ShowDialog() if ( $f -eq [System.Windows.Forms.DialogResult]::Cancel ) { "User selected Cancel" } else { "User entered `"{0}`" for the text and {1} for the number" -f $txtInputText.Text, $txtInputNumber.Text }
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.
#Scala
Scala
object UTF8EncodeAndDecode extends App {   val codePoints = Seq(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E)   def utf8Encode(codepoint: Int): Array[Byte] = new String(Array[Int](codepoint), 0, 1).getBytes(StandardCharsets.UTF_8)   def utf8Decode(bytes: Array[Byte]): Int = new String(bytes, StandardCharsets.UTF_8).codePointAt(0)   println("Char Name Unicode UTF-8 Decoded") for (codePoint <- codePoints) { val w = if (Character.isBmpCodePoint(codePoint)) 4 else 5 // Compute spacing val bytes = utf8Encode(codePoint)   def leftAlignedHex = f"U+${codePoint}%04X"   val s = new StringBuilder() bytes.foreach(byte => s ++= "%02X ".format(byte))   printf(s"%-${w}c %-36s %-7s  %-${16 - w}s%c%n", codePoint, Character.getName(codePoint), leftAlignedHex, s, utf8Decode(bytes)) }
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
#Phix
Phix
-- -- demo\rosetta\encode_url.exw -- =========================== -- with javascript_semantics function nib(integer b) return b+iff(b<=9?'0':'A'-10) end function function encode_url(string s, string exclusions="", integer spaceplus=0) string res = "" for i=1 to length(s) do integer ch = s[i] if ch=' ' and spaceplus then ch = '+' elsif not find(ch,exclusions) and (ch<'0' or (ch>'9' and ch<'A') or (ch>'Z' and ch<'a') or ch>'z') then res &= '%' res &= nib(floor(ch/#10)) ch = nib(and_bits(ch,#0F)) end if res &= ch end for return res end function printf(1,"%s\n",{encode_url("http://foo bar/")}) {} = wait_key()
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
#LotusScript
LotusScript
Sub Click() 'a few declarations as example Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession Dim i as Integer ' i = 0 Dim s as String ' s= "" Dim v as Variant ' v is nothing Dim l as Long ' l = 0 Dim doc as NotesDocument 'doc is EMTPY   '...   End Sub  
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
#Lua
Lua
a = 1 -- Here we declare a numeric variable fruit = "banana" -- Here we declare a string datatype needspeeling = True -- This is a boolean local b = 2 -- This variable declaration is prefixed with a scope modifier
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.
#Wren
Wren
var max = 1000 var a = List.filled(max, 0) var seen = {} for (n in 0...max-1) { var m = seen[a[n]] if (m != null) a[n+1] = n - m seen[a[n]] = n } System.print("The first ten terms of the Van Eck sequence are:") System.print(a[0...10]) System.print("\nTerms 991 to 1000 of the sequence are:") System.print(a[990..-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.
#XPL0
XPL0
int Seq(1001), Back, N, M, Term;   func New; \Return 'true' if last term is new to sequence [for Back:= N-2 downto 1 do if Seq(Back) = Seq(N-1) then return false; return true; ];   func VanEck; \Return term of Van Eck sequence [Seq(N):= if New then 0 else N-Back-1; N:= N+1; return Seq(N-1); ];   [N:= 1; for M:= 1 to 1000 do [Term:= VanEck; if M<=10 or M>=991 then [IntOut(0, Term); if M=10 or M=1000 then Crlf(0) else Text(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
#TIScript
TIScript
  function printAll(separator,argv..) { if(argv.length) stdout.print(argv[0]); for (var i=1; i < argv.length; i++) stdout.print(separator, argv[i]); } 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
#uBasic.2F4tH
uBasic/4tH
Push _Mary, _had, _a, _little, _lamb ' Push the hashes Proc _PrintStrings (5) ' Print the string   Push 1, 4, 5, 19, 12, 3 ' Push the numbers Print "Maximum is: ";FUNC(_Max(6)) ' Call the function   End     _PrintStrings Param(1) ' Print a variadic number of strings Local(1)   For b@ = a@-1 To 0 Step -1 ' Reverse the hashes, load in array @(b@) = Pop() Next   For b@ = 0 To a@-1 ' Now call the appropriate subroutines Proc @(b@) Until b@ = a@-1 Print " "; ' Print a space Next ' unless it is the last word   Print ' Terminate the string Return     _Max Param(1) ' Calculate the maximum value Local(3)   d@ = -(2^31) ' Set maximum to a tiny value   For b@ = 1 To a@ ' Get all values from the stack c@ = Pop() If c@ > d@ THEN d@ = c@ ' Change maximum if required Next Return (d@) ' Return the maximum   ' Hashed labels _Mary Print "Mary"; : Return _had Print "had"; : Return _a Print "a"; : Return _little Print "little"; : Return _lamb Print "lamb"; : 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
#Julia
Julia
using LinearAlgebra   const a = [3, 4, 5] const b = [4, 3, 5] const c = [-5, -12, -13]   println("Test Vectors:") @show a b c   println("\nVector Products:") @show a ⋅ b @show a × b @show a ⋅ (b × c) @show 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
#XPL0
XPL0
string 0; \use zero-terminated strings   func Luhn(Str); \Return 'true' if digits in Str pass Luhn test char Str; int Len, Sum, I, Dig; [Len:= 0; \find length of Str while Str(Len) do Len:= Len+1; Sum:= 0; \sum even and odd digits for I:= 0 to Len-1 do \(no need to reverse) [if (I xor Len) & 1 then Sum:= Sum + Str(I) - ^0 else [Dig:= Str(I) - ^0; Dig:= Dig*2; Sum:= Sum + Dig/10 + rem(0); ]; ]; return rem(Sum/10) = 0; ]; \Luhn   func Valid(Str); \Return 'true' if valid ISIN code char Str, Str2(100); int Sum, I, J, C, V; [J:= 0; for I:= 0 to 12-1 do \convert letters in Str to digits in Str2 [C:= Str(I); case of C>=^0 & C<=^9: [Str2(J):= C; J:= J+1]; C>=^A & C<=^Z: [Str2(J):= (C-^A+10)/10 + ^0; J:= J+1; Str2(J):= rem(0) + ^0; J:= J+1] other return false; if I=1 & J#4 then return false; \first two chars not letters ]; if Str(I) # 0 then return false; \too long Str2(J):= 0; \terminate string return Luhn(Str2); ]; \Valid   int ISIN, N; [ISIN:= ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]; for N:= 0 to 7-1 do [Text(0, ISIN(N)); Text(0, if Valid(ISIN(N)) then " is valid" else " is not valid"); CrLf(0); ]; ]
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Yabasic
Yabasic
sub luhntest(cardnr$) local i, j, s1, s2, l   cardnr$ = Trim$(cardnr$) // remove spaces   l = Len(cardnr$)   // sum odd numbers For i = l To 1 Step -2 s1 = s1 + (asc(mid$(cardnr$, i, 1)) - Asc("0")) Next // sum even numbers For i = l-1 To 1 Step -2 j = asc(mid$(cardnr$, i, 1)) - Asc("0") j = j * 2 If j > 9 j = mod(j, 10) + 1 s2 = s2 + j Next   return mod(s1 + s2, 10) = 0 End sub   // ------=< MAIN >=-----   data "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040", ""   do read test_item$ if test_item$ = "" break   l = Len(test_item$) If l <> 12 Then Print test_item$, " Invalid, length <> 12 char." Continue End If c1$ = mid$(test_item$, 1, 1) : c2$ = mid$(test_item$, 2, 1) If c1$ < "A" Or c1$ > "Z" or c2$ < "A" or c2$ > "Z" Then Print test_item$, " Invalid, number needs to start with 2 characters" Continue End If test_str$ = "" For n = 1 To l x = asc(mid$(test_item$, n, 1)) - Asc("0") // if is a letter we to correct for that If x > 9 x = x - 7 If x < 10 Then test_str$ = test_str$ + Str$(x) Else // two digest number test_str$ = test_str$ + Str$(int(x / 10)) + Str$(mod(x, 10)) End If Next Print test_item$; if luhntest(test_str$) then print " Valid" else print " Invalid, checksum error" end if loop  
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
#Stata
Stata
mata // 5th term of Van der Corput sequence halton(1,1,5) .625   // the first 10 terms of Van der Corput sequence halton(10,1) 1 +---------+ 1 | .5 | 2 | .25 | 3 | .75 | 4 | .125 | 5 | .625 | 6 | .375 | 7 | .875 | 8 | .0625 | 9 | .5625 | 10 | .3125 | +---------+   // the first 10 terms of Van der Corput sequence in base 3 ghalton(10,3,0) 1 +---------------+ 1 | .3333333333 | 2 | .6666666667 | 3 | .1111111111 | 4 | .4444444444 | 5 | .7777777778 | 6 | .2222222222 | 7 | .5555555556 | 8 | .8888888889 | 9 | .037037037 | 10 | .3703703704 | +---------------+   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
#Swift
Swift
func vanDerCorput(n: Int, base: Int, num: inout Int, denom: inout Int) { var n = n, p = 0, q = 1   while n != 0 { p = p * base + (n % base) q *= base n /= base }   num = p denom = q   while p != 0 { n = p p = q % p q = n }   num /= q denom /= q }   var num = 0 var denom = 0   for base in 2...5 { print("base \(base): 0 ", terminator: "")   for n in 1..<10 { vanDerCorput(n: n, base: base, num: &num, denom: &denom)   print("\(num)/\(denom) ", terminator: "") }   print() }
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á".
#Oberon-2
Oberon-2
  MODULE URLDecoding; IMPORT URI := URI:String, Out := NPCT:Console; BEGIN Out.String(URI.Unescape("http%3A%2F%2Ffoo%20bar%2F"));Out.Ln; Out.String(URI.Unescape("google.com/search?q=%60Abdu%27l-Bah%C3%A1"));Out.Ln; END URLDecoding.  
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á".
#Objeck
Objeck
  class UrlDecode { function : Main(args : String[]) ~ Nil { Net.UrlUtility->Decode("http%3A%2F%2Ffoo%20bar%2F")->PrintLine(); } }  
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.
#Python
Python
"""UPC-A barcode reader. Requires Python =>3.6""" import itertools import re   RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" # quiet zone r"(?P<s_guard># #)" # start guard r"(?P<left>[ #]{42})" # left digits r"(?P<m_guard> # # )" # middle guard r"(?P<right>[ #]{42})" # right digits r"(?P<e_guard># #)" # end guard r"(?P<e_quiet> +)$" # quiet zone )   LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, }   RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, }     MODULES = { " ": 0, "#": 1, }   DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7     class ParityError(Exception): """Exception raised when a parity error is found."""     class ChecksumError(Exception): """Exception raised when check digit does not match."""     def group(iterable, n): """Chunk the iterable into groups of size ``n``.""" args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args))     def parse(barcode): """Return the 12 digits represented by the given barcode. Raises a ParityError if any digit fails the parity check.""" match = RE_BARCODE.match(barcode)   # Translate bars and spaces to 1s and 0s so we can do arithmetic # with them. Group "modules" into chunks of 7 as we go. left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT)   # Parity check left, right = check_parity(left, right)   # Lookup digits return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) )     def check_parity(left, right): """Check left and right parity. Flip left and right if the barcode was scanned upside down.""" # When reading from left to right, each digit on the left should # have odd parity, and each digit on the right should have even # parity. left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right)   # Use left and right parity to check if the barcode was scanned # upside down. Flip it if it was. if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: # Error condition. Mixed parity. error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error))   return left, right     def checksum(digits): """Return the check digit for the given digits. Raises a ChecksumError if the check digit does not match.""" odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2))   check_digit = (sum(odds) * 3 + sum(evens)) % 10   if check_digit != 0: check_digit = 10 - check_digit   if digits[-1] != check_digit: raise ChecksumError(str(check_digit))   return check_digit     def main(): barcodes = [ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### ## ## # ### # # ", ]   for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue   try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue   print(f"{' '.join(str(d) for d in digits)}")     if __name__ == "__main__": main()  
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
#TXR
TXR
VAR # define or update VAR as a true-valued boolean VAR= # ensure "; VAR" in the config file. VAR=VAL # ensure "VAR VAL" in the config 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
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject")   'Paramater lookups Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With   'Open the config file for reading. Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) 'Initialize output. Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With   'Create a new config file. Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With   Set objFSO = Nothing Set objParamLookup = Nothing  
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
#Kite
Kite
  System.file.stdout|write("Enter a String "); string = System.file.stdin|readline();  
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
#Kotlin
Kotlin
// version 1.1   fun main(args: Array<String>) { print("Enter a string : ") val s = readLine()!! println(s) do { print("Enter 75000 : ") val number = readLine()!!.toInt() } while (number != 75000) }
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
#Processing
Processing
import javax.swing.JOptionPane;   int number = int(JOptionPane.showInputDialog ("Enter an Integer")); println(number);   String string = JOptionPane.showInputDialog ("Enter a String"); println(string);
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
#PureBasic
PureBasic
string$=InputRequester("Some Title","Enter a string","") variable=Val(InputRequester("Some other Title","Enter a Number","75000"))
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "unicode.s7i"; include "console.s7i"; include "bytedata.s7i";   const proc: main is func local var char: ch is ' '; var string: utf8 is ""; begin OUT := STD_CONSOLE; writeln("Character Unicode UTF-8 encoding (hex) Decoded"); writeln("-------------------------------------------------"); for ch range "AöЖ€𝄞" do utf8 := striToUtf8(str(ch)); writeln(ch rpad 11 <& "U+" <& ord(ch) radix 16 lpad0 4 rpad 7 <& hex(utf8) rpad 22 <& utf8ToStri(utf8)); end for; end func;
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.
#Sidef
Sidef
func utf8_encoder(Number code) { code.chr.encode('UTF-8').bytes.map{.chr} }   func utf8_decoder(Array bytes) { bytes.map{.ord}.decode('UTF-8') }   for n in ([0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E]) { var encoded = utf8_encoder(n) var decoded = utf8_decoder(encoded) assert_eq(n, decoded.ord) say "#{decoded} -> #{encoded}" }
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
#PHP
PHP
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>