task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Elixir
Elixir
iex(1)> URI.encode("http://foo bar/", &URI.char_unreserved?/1) "http%3A%2F%2Ffoo%20bar%2F"
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Erlang
Erlang
1> http_uri:encode("http://foo bar/"). "http%3A%2F%2Ffoo%20bar%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
#DM
DM
// Both of the following declarations can be seen as a tree, // var -> <varname> var/x var y   // They can also be defined like this. // This is once again a tree structure, but this time the "var" only appears once, and the x and y are children. var x y // And like this, still a tree structure. var/x, y  
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
#Diego
Diego
add_var(v1); dim(v1); add_var(v1, v2, v3, v4); dim(v1, v2, v3, v4); add_var(isRaining)_datatype(boolean); dim(isRaining)_datatype(boolean); add_var(greeting)_dt(string); dim(greeting)_dt(string); add_var({date}, birthdate); dim({date}, birthdate);
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.
#Go
Go
package main   import "fmt"   func main() { const max = 1000 a := make([]int, max) // all zero by default for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
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.
#Haskell
Haskell
import Data.List (elemIndex) import Data.Maybe (maybe)   vanEck :: Int -> [Int] vanEck n = reverse $ iterate go [] !! n where go [] = [0] go xxs@(x:xs) = maybe 0 succ (elemIndex x xs) : xxs   main :: IO () main = do print $ vanEck 10 print $ drop 990 (vanEck 1000)
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw(say);   sub fangs { my $vampire = shift; my $length = length 0 + $vampire; return if $length % 2; my $fang_length = $length / 2; my $from = '1' . '0' x ($fang_length - 1); my $to = '9' x $fang_length; my $sorted = join q(), sort split //, $vampire; my @fangs; for my $f1 ($from .. 1 + sqrt $vampire) { next if $vampire % $f1; my $f2 = $vampire / $f1; next if $sorted ne join q(), sort split //, $f1 . $f2; next if 2 == grep '0' eq substr($_, -1 , 1), $f1, $f2; # Needed for the 26th number. push @fangs, [$f1, $f2]; } return @fangs; }   my $count = 0; my $i = 9; while ($count < 25) { $i++; my @f = fangs($i); $count++, say join ' ', "$count. $i:", map "[@$_]", @f if @f; }   say join ' ', $_, map "[@$_]", fangs($_) for 16758243290880, 24959017348650, 14593825548650;
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
#Lua
Lua
function varar(...) for i, v in ipairs{...} do print(v) end 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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ Works for numbers and strings (letters in M2000) Function Variadic { \\ print a letter for each type in function stack Print Envelope$() \\Check types using Match Print Match("NNSNNS") =stack.size While not Empty { if islet then {print letter$} else print number } } M=Variadic(1,2,"Hello",3,4,"Bye") Print M \\ K is a poiner to Array K=(1,2,"Hello 2",3,4,"Bye 2") \\ !K pass all items to function's stack M=Variadic(!K) } Checkit     Module CheckIt2 { Function Variadic { \\ [] return a pointer to stack, and leave a new stack as function's stack a=[] \\ a is a pointer to stack \\ objects just leave a space, and cursor move to next column (spread on lines) Print a } M=Variadic(1,2,"Hello",3,4,"Bye") Print M \\ K is a poiner to Array K=(1,2,"Hello 2",3,4,"Bye 2") \\ !K pass all items to function stack M=Variadic(!K) } Checkit2  
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Rust
Rust
use std::fmt; use std::ops::{Add, Div, Mul, Sub};   #[derive(Copy, Clone, Debug)] pub struct Vector<T> { pub x: T, pub y: T, }   impl<T> fmt::Display for Vector<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(prec) = f.precision() { write!(f, "[{:.*}, {:.*}]", prec, self.x, prec, self.y) } else { write!(f, "[{}, {}]", self.x, self.y) } } }   impl<T> Vector<T> { pub fn new(x: T, y: T) -> Self { Vector { x, y } } }   impl Vector<f64> { pub fn from_polar(r: f64, theta: f64) -> Self { Vector { x: r * theta.cos(), y: r * theta.sin(), } } }   impl<T> Add for Vector<T> where T: Add<Output = T>, { type Output = Self;   fn add(self, other: Self) -> Self::Output { Vector { x: self.x + other.x, y: self.y + other.y, } } }   impl<T> Sub for Vector<T> where T: Sub<Output = T>, { type Output = Self;   fn sub(self, other: Self) -> Self::Output { Vector { x: self.x - other.x, y: self.y - other.y, } } }   impl<T> Mul<T> for Vector<T> where T: Mul<Output = T> + Copy, { type Output = Self;   fn mul(self, scalar: T) -> Self::Output { Vector { x: self.x * scalar, y: self.y * scalar, } } }   impl<T> Div<T> for Vector<T> where T: Div<Output = T> + Copy, { type Output = Self;   fn div(self, scalar: T) -> Self::Output { Vector { x: self.x / scalar, y: self.y / scalar, } } }   fn main() { use std::f64::consts::FRAC_PI_3;   println!("{:?}", Vector::new(4, 5)); println!("{:.4}", Vector::from_polar(3.0, FRAC_PI_3)); println!("{}", Vector::new(2, 3) + Vector::new(4, 6)); println!("{:.4}", Vector::new(5.6, 1.3) - Vector::new(4.2, 6.1)); println!("{:.4}", Vector::new(3.0, 4.2) * 2.3); println!("{:.4}", Vector::new(3.0, 4.2) / 2.3); println!("{}", Vector::new(3, 4) / 2); }
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Scala
Scala
object Vector extends App {   case class Vector2D(x: Double, y: Double) { def +(v: Vector2D) = Vector2D(x + v.x, y + v.y)   def -(v: Vector2D) = Vector2D(x - v.x, y - v.y)   def *(s: Double) = Vector2D(s * x, s * y)   def /(s: Double) = Vector2D(x / s, y / s)   override def toString() = s"Vector($x, $y)" }   val v1 = Vector2D(5.0, 7.0) val v2 = Vector2D(2.0, 3.0) println(s"v1 = $v1") println(s"v2 = $v2\n")   println(s"v1 + v2 = ${v1 + v2}") println(s"v1 - v2 = ${v1 - v2}") println(s"v1 * 11 = ${v1 * 11.0}") println(s"11 * v2 = ${v2 * 11.0}") println(s"v1 / 2 = ${v1 / 2.0}")   println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Rust
Rust
use std::ascii::AsciiExt;   static A: u8 = 'A' as u8;   fn uppercase_and_filter(input: &str) -> Vec<u8> { let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; let mut result = Vec::new();   for c in input.chars() { // Ignore anything that is not in our short list of chars. We can then safely cast to u8. if alphabet.iter().any(|&x| x as char == c) { result.push(c.to_ascii_uppercase() as u8); } }   return result; }   fn vigenere(key: &str, text: &str, is_encoding: bool) -> String {   let key_bytes = uppercase_and_filter(key); let text_bytes = uppercase_and_filter(text);   let mut result_bytes = Vec::new();   for (i, c) in text_bytes.iter().enumerate() { let c2 = if is_encoding { (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A } else { (c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A }; result_bytes.push(c2); }   String::from_utf8(result_bytes).unwrap() }   fn main() { let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER";   println!("Text: {}", text); println!("Key: {}", key);   let encoded = vigenere(key, text, true); println!("Code: {}", encoded); let decoded = vigenere(key, &encoded, false); println!("Back: {}", decoded); }
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Scala
Scala
  object Vigenere { def encrypt(msg: String, key: String) : String = { var result: String = "" var j = 0   for (i <- 0 to msg.length - 1) { val c = msg.charAt(i) if (c >= 'A' && c <= 'Z') { result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar j = (j + 1) % key.length } }   return result }   def decrypt(msg: String, key: String) : String = { var result: String = "" var j = 0   for (i <- 0 to msg.length - 1) { val c = msg.charAt(i) if (c >= 'A' && c <= 'Z') { result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar j = (j + 1) % key.length } }   return result } }   println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY")) println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))  
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
#ERRE
ERRE
  PROGRAM VECTORPRODUCT   !$DOUBLE   TYPE TVECTOR=(X,Y,Z)   DIM A:TVECTOR,B:TVECTOR,C:TVECTOR   DIM AA:TVECTOR,BB:TVECTOR,CC:TVECTOR DIM DD:TVECTOR,EE:TVECTOR,FF:TVECTOR   PROCEDURE DOTPRODUCT(DD.,EE.->DOTP) DOTP=DD.X*EE.X+DD.Y*EE.Y+DD.Z*EE.Z END PROCEDURE   PROCEDURE CROSSPRODUCT(DD.,EE.->FF.) FF.X=DD.Y*EE.Z-DD.Z*EE.Y FF.Y=DD.Z*EE.X-DD.X*EE.Z FF.Z=DD.X*EE.Y-DD.Y*EE.X END PROCEDURE   PROCEDURE SCALARTRIPLEPRODUCT(AA.,BB.,CC.->SCALARTP) CROSSPRODUCT(BB.,CC.->FF.) DOTPRODUCT(AA.,FF.->SCALARTP) END PROCEDURE   PROCEDURE VECTORTRIPLEPRODUCT(AA.,BB.,CC.->FF.) CROSSPRODUCT(BB.,CC.->FF.) CROSSPRODUCT(AA.,FF.->FF.) END PROCEDURE   PROCEDURE PRINTVECTOR(AA.) PRINT("(";AA.X;",";AA.Y;",";AA.Z;")") END PROCEDURE   BEGIN A.X=3 A.Y=4 A.Z=5 B.X=4 B.Y=3 B.Z=5 C.X=-5 C.Y=-12 C.Z=-13   PRINT("A: ";) PRINTVECTOR(A.) PRINT("B: ";) PRINTVECTOR(B.) PRINT("C: ";) PRINTVECTOR(C.)   PRINT DOTPRODUCT(A.,B.->DOTP) PRINT("A.B =";DOTP)   CROSSPRODUCT(A.,B.->FF.) PRINT("AxB =";) PRINTVECTOR(FF.)   SCALARTRIPLEPRODUCT(A.,B.,C.->SCALARTP) PRINT("A.(BxC)=";SCALARTP)   VECTORTRIPLEPRODUCT(A.,B.,C.->FF.) PRINT("Ax(BxC)=";) PRINTVECTOR(FF.) END PROGRAM  
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
#Kotlin
Kotlin
// version 1.1   object Isin { val r = Regex("^[A-Z]{2}[A-Z0-9]{9}[0-9]$")   fun isValid(s: String): Boolean { // check format if (!s.matches(r)) return false // validate checksum val sb = StringBuilder() for (c in s) { when (c) { in '0'..'9' -> sb.append(c) in 'A'..'Z' -> sb.append((c.toInt() - 55).toString().padStart(2, '0')) } } return luhn(sb.toString()) }   private fun luhn(s: String): Boolean { fun sumDigits(n: Int) = n / 10 + n % 10 val t = s.reversed() val s1 = t.filterIndexed { i, _ -> i % 2 == 0 }.sumBy { it - '0' } val s2 = t.filterIndexed { i, _ -> i % 2 == 1 }.map { sumDigits((it - '0') * 2) }.sum() return (s1 + s2) % 10 == 0 } }   fun main(args: Array<String>) { val isins = arrayOf( "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" ) for (isin in isins) { println("$isin\t -> ${if (Isin.isValid(isin)) "valid" else "not valid"}") } }
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Haskell
Haskell
import Data.Ratio (Rational(..), (%), numerator, denominator) import Data.List (unfoldr) import Text.Printf (printf)   -- A wrapper type for Rationals to make them look nicer when we print them. newtype Rat = Rat Rational   instance Show Rat where show (Rat n) = show (numerator n) <> ('/' : show (denominator n))   -- Convert a list of base b digits to its corresponding number. -- We assume the digits are valid base b numbers and that -- their order is from least to most significant. digitsToNum :: Integer -> [Integer] -> Integer digitsToNum b = foldr1 (\d acc -> b * acc + d)   -- Convert a number to the list of its base b digits. -- The order will be from least to most significant. numToDigits :: Integer -> Integer -> [Integer] numToDigits _ 0 = [0] numToDigits b n = unfoldr step n where step 0 = Nothing step m = let (q, r) = m `quotRem` b in Just (r, q)   -- Return the n'th element in the base b van der Corput sequence. -- The base must be ≥ 2. vdc :: Integer -> Integer -> Rat vdc b n | b < 2 = error "vdc: base must be ≥ 2" | otherwise = let ds = reverse $ numToDigits b n in Rat (digitsToNum b ds % b ^ length ds)   -- Each base followed by a specified range of van der Corput numbers. printVdcRanges :: ([Integer], [Integer]) -> IO () printVdcRanges (bases, nums) = mapM_ putStrLn [ printf "Base %d:" b <> concatMap (printf " %5s" . show) rs | b <- bases , let rs = map (vdc b) nums ]   main :: IO () main = do -- Small bases: printVdcRanges ([2, 3, 4, 5], [0 .. 9]) putStrLn []   -- Base 123: printVdcRanges ([123], [50,100 .. 300])
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á".
#CoffeeScript
CoffeeScript
  console.log decodeURIComponent "http%3A%2F%2Ffoo%20bar%2F?name=Foo%20Barson"  
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á".
#Common_Lisp
Common Lisp
(defun decode (string &key start) (assert (char= (char string start) #\%)) (if (>= (length string) (+ start 3)) (multiple-value-bind (code pos) (parse-integer string :start (1+ start) :end (+ start 3) :radix 16 :junk-allowed t) (if (= pos (+ start 3)) (values (code-char code) pos) (values #\% (1+ start)))) (values #\% (1+ start))))   (defun url-decode (url) (loop with start = 0 for pos = (position #\% url :start start) collect (subseq url start pos) into chunks when pos collect (multiple-value-bind (decoded next) (decode url :start pos) (setf start next) (string decoded)) into chunks while pos finally (return (apply #'concatenate 'string chunks))))   (url-decode "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.
#Action.21
Action!
DEFINE PTR="CARD" DEFINE RESOK="255" DEFINE RESUPSIDEDOWN="254" DEFINE RESINVALID="253" DEFINE DIGITCOUNT="12" DEFINE DIGITLEN="7"   PTR ARRAY ldigits(10),rdigits(10) CHAR ARRAY marker="# #",midmarker=" # # "   PROC Init() ldigits(0)=" ## #" ldigits(1)=" ## #" ldigits(2)=" # ##" ldigits(3)=" #### #" ldigits(4)=" # ##" ldigits(5)=" ## #" ldigits(6)=" # ####" ldigits(7)=" ### ##" ldigits(8)=" ## ###" ldigits(9)=" # ##" rdigits(0)="### # " rdigits(1)="## ## " rdigits(2)="## ## " rdigits(3)="# # " rdigits(4)="# ### " rdigits(5)="# ### " rdigits(6)="# # " rdigits(7)="# # " rdigits(8)="# # " rdigits(9)="### # " RETURN   BYTE FUNC DecodeMarker(CHAR ARRAY s BYTE POINTER pos CHAR ARRAY marker) CHAR ARRAY tmp(6) BYTE x   x=pos^+marker(0) IF x>s(0) THEN RETURN (RESINVALID) ELSE SCopyS(tmp,s,pos^,pos^+marker(0)-1) pos^==+marker(0) IF SCompare(tmp,marker)#0 THEN RETURN (RESINVALID) FI FI RETURN (RESOK)   BYTE FUNC DecodeDigit(CHAR ARRAY s BYTE POINTER pos PTR ARRAY digits) CHAR ARRAY tmp(DIGITLEN+1) BYTE i,x   x=pos^+DIGITLEN IF x>s(0) THEN RETURN (RESINVALID) ELSE SCopyS(tmp,s,pos^,pos^+DIGITLEN-1) pos^==+DIGITLEN FOR i=0 TO 9 DO IF SCompare(tmp,digits(i))=0 THEN RETURN (i) FI OD FI RETURN (RESINVALID)   BYTE FUNC Validation(BYTE ARRAY code) BYTE ARRAY mult=[3 1 3 1 3 1 3 1 3 1 3 1] BYTE i INT sum   sum=0 FOR i=0 TO DIGITCOUNT-1 DO sum==+code(i)*mult(i) OD IF sum MOD 10=0 THEN RETURN (RESOK) FI RETURN (RESINVALID)   BYTE FUNC DecodeInternal(CHAR ARRAY s BYTE ARRAY code) BYTE res,pos,i   pos=1 WHILE pos<=s(0) AND s(pos)=32 DO pos==+1 OD   res=DecodeMarker(s,@pos,marker) IF res=RESINVALID THEN RETURN (res) FI   FOR i=0 TO 5 DO res=DecodeDigit(s,@pos,ldigits) IF res=RESINVALID THEN RETURN (res) FI code(i)=res OD   res=DecodeMarker(s,@pos,midmarker) IF res=RESINVALID THEN RETURN (res) FI   FOR i=6 TO 11 DO res=DecodeDigit(s,@pos,rdigits) IF res=RESINVALID THEN RETURN (res) FI code(i)=res OD   res=DecodeMarker(s,@pos,marker) IF res=RESINVALID THEN RETURN (res) FI res=Validation(code) RETURN (res)   PROC Reverse(CHAR ARRAY src,dst) BYTE i,j   i=1 j=src(0) dst(0)=j WHILE j>0 DO dst(j)=src(i) i==+1 j==-1 OD RETURN   BYTE FUNC Decode(CHAR ARRAY s BYTE ARRAY code) CHAR ARRAY tmp(256) BYTE res   res=DecodeInternal(s,code) IF res=RESOK THEN RETURN (res) FI Reverse(s,tmp) res=DecodeInternal(tmp,code) IF res=RESINVALID THEN RETURN (res) FI RETURN (RESUPSIDEDOWN)   PROC Test(BYTE id CHAR ARRAY s) BYTE ARRAY code(DIGITCOUNT) BYTE res,i   res=Decode(s,code) IF id<10 THEN Put(32) FI PrintF("%B: ",id) IF res=RESINVALID THEN PrintE("invalid") ELSE FOR i=0 TO DIGITCOUNT-1 DO PrintB(code(i)) OD IF res=RESUPSIDEDOWN THEN PrintE(" valid (upside down)") ELSE PrintE(" valid") FI FI RETURN   PROC Main() PTR ARRAY codes(10) BYTE i   Init() codes(0)=" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " codes(1)=" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " codes(2)=" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " codes(3)=" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " codes(4)=" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " codes(5)=" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " codes(6)=" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " codes(7)=" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " codes(8)=" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " codes(9)=" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "   FOR i=0 TO 9 DO Test(i+1,codes(i)) OD RETURN
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
#Erlang
Erlang
  -module( update_configuration_file ).   -export( [add/3, change/3, disable/2, enable/2, read/1, task/0, write/2] ).   add( Option, Value, Lines ) -> Upper = string:to_upper( Option ), [string:join( [Upper, Value], " " ) | Lines].   change( Option, Value, Lines ) -> Upper = string:to_upper( Option ), change_done( Option, Value, Lines, [change_option(Upper, Value, X) || X <- Lines] ).   disable( Option, Lines ) -> Upper = string:to_upper( Option ), [disable_option(Upper, X) || X <- Lines].   enable( Option, Lines ) -> Upper = string:to_upper( Option ), [enable_option(Upper, X) || X <- Lines].   read( Name ) -> {ok, Binary} = file:read_file( Name ), Lines = [binary:bin_to_list(X) || X <- binary:split( Binary, <<"\n">>, [global] )], Lines_no_white = [string:strip(X) || X <- Lines], Lines_no_control = [strip_control(X) || X <- Lines_no_white], Lines_no_consecutive_space = [string:join(string:tokens(X, " "), " ") || X <- Lines_no_control], Lines_no_consecutive_semicolon = [strip_semicolon(X) || X <- Lines_no_consecutive_space], Lines_no_empty = lists:filter( fun strip_empty/1, Lines_no_consecutive_semicolon ), Lines_upper = [to_upper(X) || X <- Lines_no_empty], lists:reverse( lists:foldl(fun remove_duplicates/2, [], Lines_upper) ).   task() -> Lines = read( "priv/configuration_file2" ), Disabled_lines = disable( "needspeeling", Lines ), Enabled_lines = enable( "SEEDSREMOVED", Disabled_lines ), Changed_lines1 = change( "NUMBEROFBANANAS", "1024", Enabled_lines ), Changed_lines2 = change( "numberofstrawberries", "62000", Changed_lines1 ), write( "configuration_file", Changed_lines2 ), [io:fwrite( "Wrote this line: ~s~n", [X]) || X <- Changed_lines2].   write( Name, Lines ) -> file:write_file( Name, binary:list_to_bin(string:join(Lines, "\n")) ).       change_done( Option, Value, Lines, Lines ) -> add( Option, Value, Lines ); change_done( _Option, _Value, _Lines, New_lines ) -> New_lines.   change_option( Option, Value, String ) -> change_option_same( string:str(String, Option), Value, String ).   change_option_same( 1, Value, String ) -> [Option | _T] = string:tokens( String, " " ), string:join( [Option, Value], " " ); change_option_same( _N, _Value, String ) -> String.   disable_option( Option, String ) -> disable_option_same( string:str(String, Option), String ).   disable_option_same( 1, String ) -> "; " ++ String; disable_option_same( _N, String ) -> String.   enable_option( Option, String ) -> enable_option_same( string:str(String, "; " ++ Option), String ).   enable_option_same( 1, "; " ++ String ) -> String; enable_option_same( _N, String ) -> String.   is_semicolon( $; ) -> true; is_semicolon( _C ) -> false.   remove_duplicates( "#" ++_T=Line, Lines ) -> [Line | Lines]; remove_duplicates( Line, Lines ) -> Duplicates = [X || X <-Lines, 1 =:= string:str(Line, X)], remove_duplicates( Duplicates, Line, Lines ).   remove_duplicates( [], Line, Lines ) -> [Line | Lines]; remove_duplicates( _Duplicates, _Line, Lines ) -> Lines.   strip_control( "" ) -> ""; strip_control( ";" ++ _T=String ) -> lists:filter( fun strip_control_codes:is_not_control_code_nor_extended_character/1, String ); strip_control( String ) -> String.   strip_empty( ";" ) -> false; strip_empty( _String ) -> true.     strip_semicolon( ";" ++ _T=String ) -> ";" ++ lists:dropwhile( fun is_semicolon/1, String ); strip_semicolon( String ) -> String.   to_upper( "" ) -> ""; to_upper( "#" ++ _T=String ) -> String; to_upper( "; " ++ _T=String ) -> [";", Option | T] = string:tokens( String, " " ), string:join( [";", string:to_upper(Option) | T], " " ); to_upper( String ) -> [Option | T] = string:tokens( String, " " ), string:join( [string:to_upper(Option) | T], " " ).  
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
#C.23
C#
using System;   namespace C_Sharp_Console {   class example {   static void Main() { string word; int num;   Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.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
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   int main() { // while probably all current implementations have int wide enough for 75000, the C++ standard // only guarantees this for long int. long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
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
#Delphi
Delphi
program UserInputGraphical;   {$APPTYPE CONSOLE}   uses SysUtils, Dialogs;   var s: string; lStringValue: string; lIntegerValue: Integer; begin lStringValue := InputBox('User input/Graphical', 'Enter a string', '');   repeat s := InputBox('User input/Graphical', 'Enter the number 75000', '75000'); lIntegerValue := StrToIntDef(s, 0); if lIntegerValue <> 75000 then ShowMessage('Invalid entry: ' + s); until lIntegerValue = 75000; 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.
#F.23
F#
  // Unicode character point to UTF8. Nigel Galloway: March 19th., 2018 let fN g = match List.findIndex (fun n->n>g) [0x80;0x800;0x10000;0x110000] with |0->[g] |1->[0xc0+(g&&&0x7c0>>>6);0x80+(g&&&0x3f)] |2->[0xe0+(g&&&0xf000>>>12);0x80+(g&&&0xfc0>>>6);0x80+(g&&&0x3f)] |_->[0xf0+(g&&&0x1c0000>>>18);0x80+(g&&&0x3f000>>>12);0x80+(g&&&0xfc0>>>6);0x80+(g&&&0x3f)]  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Ol
Ol
  #include <extensions/embed.h>   #define min(x,y) (x < y ? x : y)   extern unsigned char repl[]; int Query(char *Data, size_t *Length) { ol_t ol; embed_new(&ol, repl, 0);   word s = embed_eval(&ol, new_string(&ol, "(define sample \"Here am I\")" "sample" ), 0); if (!is_string(s)) goto fail;   int i = *Length = min(string_length(s), *Length);   memcpy(Data, string_value(s), i); *Length = i;   OL_free(ol.vm); return 1; fail: OL_free(ol.vm); return 0; }  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#PARI.2FGP
PARI/GP
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k-84)%26+97,if(k>64&&k<91,(k-52)%26+65,k)),Vec(Vecsmall(s)))))
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Lua
Lua
local url = require('socket.url')   local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:[email protected]', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' }   for _, test in ipairs(tests) do local parsed = url.parse(test)   io.write('URI: ' .. test .. '\n')   for k, v in pairs(parsed) do io.write(string.format('  %s: %s\n', k, v)) end   io.write('\n') end  
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#F.23
F#
open System   [<EntryPoint>] let main args = printfn "%s" (Uri.EscapeDataString(args.[0])) 0
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
#Factor
Factor
USING: combinators.short-circuit unicode urls.encoding.private ;   : my-url-encode ( str -- encoded ) [ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;   "http://foo bar/" my-url-encode print
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
#DWScript
DWScript
  var i := 123; // inferred type of i is Integer var s := 'abc'; // inferred type of s is String var o := TObject.Create; // inferred type of o is TObject var s2 := o.ClassName; // inferred type of s2 is String as that's the type returned by ClassName  
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
#Dyalect
Dyalect
//A constant declaration let pi = 3.14   private { //private constant, not visible outside of a module let privateConst = 3.3 }   //Variable declaration var x = 42   //Assignment x = 42.42   //Dyalect is a dynamic language, so types are attached //to values, not to the names var foo = (x: 2, y: 4) //foo is of type Tuple var bar = "Hello!" //bar is of type String   //Global variable var g = 1.1   { //local variable (not visible outside of { } brackets) var loc = 2.2 }   func fun() { //Local variables, not visible outside of function var x = 1 var y = 2 }   func parent() { //A local variable inside a parent function var x = 1 func child() { //A local variable inside a nested function //It shadows a parent's variable var x = 2   //But this is how we can reference a variable from //a parent function base.x } }
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#J
J
VanEck=. (, (<:@:# - }: i: {:))^:(]`0:)
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Java
Java
  import java.util.HashMap; import java.util.Map;   public class VanEckSequence {   public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); }   private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } }   }   }  
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Phix
Phix
with javascript_semantics requires("1.0.2") -- (for in) function vampire(atom v) sequence res = {} if v>=0 then string vs = sprintf("%d",v) if mod(length(vs),2)=0 then -- even length vs = sort(vs) for i=power(10,length(vs)/2-1) to floor(sqrt(v)) do if remainder(v,i)=0 then integer i2 = v/i string si = sprintf("%d",i), s2 = sprintf("%d",i2) if (si[$]!='0' or s2[$]!='0') and sort(si&s2)=vs then res = append(res,{i,i2}) end if end if end for end if end if return res end function integer found = 0 atom i = 0 sequence res puts(1,"The first 26 vampire numbers and their fangs:\n") while found<26 do res = vampire(i) if length(res) then found += 1 printf(1,"%d: %d: %v\n",{found,i,res}) end if i += 1 end while puts(1,"\n") for i in {16758243290880,24959017348650,14593825548650} do res = vampire(i) printf(1,"%d: %s\n",{i,iff(res={}?"not a vampire number":sprint(res))}) end for
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
#M4
M4
define(`showN', `ifelse($1,0,`',`$2 $0(decr($1),shift(shift($@)))')')dnl define(`showargs',`showN($#,$@)')dnl dnl showargs(a,b,c) dnl define(`x',`1,2') define(`y',`,3,4,5') showargs(x`'y)
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ShowMultiArg[x___] := Do[Print[i], {i, {x}}]
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#MATLAB
MATLAB
function variadicFunction(varargin)   for i = (1:numel(varargin)) disp(varargin{i}); end   end
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Sidef
Sidef
class MyVector(:args) {   has Number x has Number y   method init { if ([:x, :y] ~~ args) { x = args{:x} y = args{:y} } elsif ([:length, :angle] ~~ args) { x = args{:length}*args{:angle}.cos y = args{:length}*args{:angle}.sin } elsif ([:from, :to] ~~ args) { x = args{:to}[0]-args{:from}[0] y = args{:to}[1]-args{:from}[1] } else { die "Invalid arguments: #{args}" } }   method length { hypot(x, y) } method angle { atan2(y, x) }   method +(MyVector v) { MyVector(x => x + v.x, y => y + v.y) } method -(MyVector v) { MyVector(x => x - v.x, y => y - v.y) } method *(Number n) { MyVector(x => x * n, y => y * n) } method /(Number n) { MyVector(x => x / n, y => y / n) }   method neg { self * -1 } method to_s { "vec[#{x}, #{y}]" } }   var u = MyVector(x => 3, y => 4) var v = MyVector(from => [1, 0], to => [2, 3]) var w = MyVector(length => 1, angle => 45.deg2rad)   say u #: vec[3, 4] say v #: vec[1, 3] say w #: vec[0.70710678118654752440084436210485, 0.70710678118654752440084436210485]   say u.length #: 5 say u.angle.rad2deg #: 53.13010235415597870314438744090659   say u+v #: vec[4, 7] say u-v #: vec[2, 1] say -u #: vec[-3, -4] say u*10 #: vec[30, 40] say u/2 #: vec[1.5, 2]
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: vigenereCipher (in string: source, in var string: keyword) is func result var string: dest is ""; local var char: ch is ' '; var integer: index is 1; var integer: shift is 0; begin keyword := upper(keyword); for ch range source do if ch in {'A' .. 'Z'} | {'a' .. 'z'} then shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A'); dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') + shift) rem 26); incr(index); end if; end for; end func;   const func string: vigenereDecipher (in string: source, in var string: keyword) is func result var string: dest is ""; local var char: ch is ' '; var integer: index is 0; var integer: shift is 0; begin keyword := upper(keyword); for ch key index range source do if ch in {'A' .. 'Z'} | {'a' .. 'z'} then shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A'); dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') - shift) mod 26); end if; end for; end func;   const proc: main is func local const string: input is "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; const string: keyword is "VIGENERECIPHER"; var string: encrypted is ""; var string: decrypted is ""; begin writeln("Input: " <& input); writeln("key: " <& keyword); encrypted := vigenereCipher(input, keyword); writeln("Encrypted: " <& encrypted); decrypted := vigenereDecipher(encrypted, keyword); writeln("Decrypted: " <& decrypted); end func;
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Sidef
Sidef
func s2v(s) { s.uc.scan(/[A-Z]/).map{.ord} »-» 65 } func v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join }   func blacken (red, key) { v2s(s2v(red) »+« s2v(key)) } func redden (blk, key) { v2s(s2v(blk) »-« s2v(key)) }   var red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" var key = "Vigenere Cipher!!!"   say red say (var black = blacken(red, key)) say redden(black, key)
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
#Euphoria
Euphoria
constant X = 1, Y = 2, Z = 3   function dot_product(sequence a, sequence b) return a[X]*b[X] + a[Y]*b[Y] + a[Z]*b[Z] end function   function cross_product(sequence a, sequence b) return { a[Y]*b[Z] - a[Z]*b[Y], a[Z]*b[X] - a[X]*b[Z], a[X]*b[Y] - a[Y]*b[X] } end function   function scalar_triple(sequence a, sequence b, sequence c) return dot_product( a, cross_product( b, c ) ) end function   function vector_triple( sequence a, sequence b, sequence c) return cross_product( a, cross_product( b, c ) ) end function   constant a = { 3, 4, 5 }, b = { 4, 3, 5 }, c = { -5, -12, -13 }   puts(1,"a = ") ? a puts(1,"b = ") ? b puts(1,"c = ") ? c puts(1,"a dot b = ") ? dot_product( a, b ) puts(1,"a x b = ") ? cross_product( a, b ) puts(1,"a dot (b x c) = ") ? scalar_triple( a, b, c ) puts(1,"a x (b x c) = ") ? vector_triple( 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
#langur
langur
val .luhntest = f(.s) { val .t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] val .numbers = s2n .s val .oddeven = len(.numbers) rem 2   for[=0] .i of .numbers { _for += if(.i rem 2 == .oddeven: .numbers[.i]; .t[.numbers[.i]+1]) } div 10 }   val .isintest = f(.s) { matching(re/^[A-Z][A-Z][0-9A-Z]{9}[0-9]$/, .s) and .luhntest(join s2n .s) }   val .tests = h{ "US0378331005": true, "US0373831005": false, "U50378331005": false, "AU0000XVGZA3": true, "AU0000VXGZA3": true, "FR0000988040": true, "US03378331005": false, }   for .key in sort(keys .tests) { val .pass = .isintest(.key) write .key, ": ", .pass writeln if(.pass == .tests[.key]: ""; " (ISIN TEST FAILED)") }
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
#Lua
Lua
function luhn (n) local revStr, s1, s2, digit, mod = n:reverse(), 0, 0 for pos = 1, #revStr do digit = tonumber(revStr:sub(pos, pos)) if pos % 2 == 1 then s1 = s1 + digit else digit = digit * 2 if digit > 9 then mod = digit % 10 digit = mod + ((digit - mod) / 10) end s2 = s2 + digit end end return (s1 + s2) % 10 == 0 end   function checkISIN (inStr) if #inStr ~= 12 then return false end local numStr = "" for pos = 1, #inStr do numStr = numStr .. tonumber(inStr:sub(pos, pos), 36) end return luhn(numStr) end   local testCases = { "US0378331005", "US0373831005", "US0373831005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" } for _, ISIN in pairs(testCases) do print(ISIN, checkISIN(ISIN)) 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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) base := integer(get(A)) | 2 every writes(round(vdc(0 to 9,base),10)," ") write() end   procedure vdc(n, base) e := 1.0 x := 0.0 while x +:= 1(((0 < n) % base) / (e *:= base), n /:= base) return x end   procedure round(n,d) places := 10 ^ d return real(integer(n*places + 0.5)) / places 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
#J
J
vdc=: ([ %~ %@[ #. #.inv)"0 _
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á".
#Crystal
Crystal
require "uri"   puts URI.decode "http%3A%2F%2Ffoo%20bar%2F" puts URI.decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1"
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#D
D
import std.stdio, std.uri;   void main() { writeln(decodeComponent("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.
#ALGOL_68
ALGOL 68
BEGIN # number of digits encoded by UPC # INT upc digits = 12; # MODE to hold UPC bar code parse results # MODE UPC = STRUCT( BOOL valid # TRUE if the UPC was valid, # # FASLE otherwise # , [ 1 : upc digits ]INT digits # the digits encoded by the # # UPC if it was valid # , BOOL inverted # TRUE if the code was scanned # # upside down, FALSE if it was # # right-side up # , STRING error message # erro rmessage if the string # # was invalid # ); # parses the UPC string s and returns a UPC containing the results # PROC parse upc = ( STRING s )UPC: BEGIN # returns TRUE if we are at the end of s, FALSE otherwise # PROC at end = BOOL: s pos > UPB s; # counts and skips spaces in s # PROC skip spaces = INT: BEGIN INT spaces := 0; WHILE IF at end THEN FALSE ELSE s[ s pos ] = " " FI DO spaces +:= 1; s pos +:= 1 OD; spaces END; # skip spaces # # skips over the next number of bits characters of s and returns # # a bit representation ( space = 0, anything else = 1 ) # PROC get value = ( INT number of bits )BITS: BEGIN BITS value := 2r0; FOR b TO number of bits WHILE NOT at end DO value := ( value SHL 1 ) OR IF s[ s pos ] = " " THEN 2r0 ELSE 2r1 FI; s pos +:= 1 OD; value END; # get value # # the representations of the digits # []BITS representations = ( 2r 0 0 0 1 1 0 1 # 0 # , 2r 0 0 1 1 0 0 1 # 1 # , 2r 0 0 1 0 0 1 1 # 2 # , 2r 0 1 1 1 1 0 1 # 3 # , 2r 0 1 0 0 0 1 1 # 4 # , 2r 0 1 1 0 0 0 1 # 5 # , 2r 0 1 0 1 1 1 1 # 6 # , 2r 0 1 1 1 0 1 1 # 7 # , 2r 0 1 1 0 1 1 1 # 8 # , 2r 0 0 0 1 0 1 1 # 9 # ); []BITS reversed digits = ( 2r 0 1 0 0 1 1 1 # 0 # , 2r 0 1 1 0 0 1 1 # 1 # , 2r 0 0 1 1 0 1 1 # 2 # , 2r 0 1 0 0 0 0 1 # 3 # , 2r 0 0 1 1 1 0 1 # 4 # , 2r 0 1 1 1 0 0 1 # 5 # , 2r 0 0 0 0 1 0 1 # 6 # , 2r 0 0 1 0 0 0 1 # 7 # , 2r 0 0 0 1 0 0 1 # 8 # , 2r 0 0 1 0 1 1 1 # 9 # ); # number of digits in the left and right sides of the UPC # INT digits per side = upc digits OVER 2; UPC result; FOR d TO upc digits DO ( digits OF result )[ d ] := 0 OD; inverted OF result := FALSE; error message OF result := "unknown error"; valid OF result := FALSE; INT s pos := LWB s; IF skip spaces < 6 # should be 9 but we are being tolerant # THEN # insufficient leading spaces # error message OF result := "missing leading spaces" ELIF get value( 3 ) /= 2r101 THEN # no start # error message OF result := "missing start sequence" ELSE # ok so far - should now have six digits, each encoded in # # seven bits # # note we store the digits as 1..10 if the are right-sid up # # and -1..-10 if they are inverted, so we can distinguish # # right-side up 0 and inverted 0 # # the digits are corrected to be 0..9 later # BOOL valid digits := TRUE; FOR d TO digits per side WHILE valid digits DO BITS code = get value( 7 ); BOOL found digit := FALSE; FOR d pos TO UPB representations WHILE NOT found digit DO IF code = representations[ d pos ] THEN # found a "normal" digit # found digit := TRUE; ( digits OF result )[ d ] := d pos ELIF code = reversed digits[ d pos ] THEN # found a reversed digit # found digit := TRUE; inverted OF result := TRUE; ( digits OF result )[ d ] := - d pos FI OD; IF NOT found digit THEN # have an invalid digit # error message OF result := "invalid digit " + whole( d, 0 ); valid digits := FALSE FI OD; IF NOT valid digits THEN # had an error # SKIP ELIF get value( 5 ) /= 2r01010 THEN # no middle separator # error message OF result := "missing middle sequence" ELSE # should now have 6 negated digits # FOR d FROM digits per side + 1 TO upc digits WHILE valid digits DO BITS code = NOT get value( 7 ) AND 16r7f; BOOL found digit := FALSE; FOR d pos TO UPB representations WHILE NOT found digit DO IF code = representations[ d pos ] THEN # found a normal negated digit # found digit := TRUE; ( digits OF result )[ d ] := d pos ELIF code = reversed digits[ d pos ] THEN # found reversed negated digit # found digit := TRUE; inverted OF result := TRUE; ( digits OF result )[ d ] := - d pos FI OD; IF NOT found digit THEN # have an invalid digit # error message OF result := "invalid digit " + whole( d, 0 ); valid digits := FALSE FI OD; IF NOT valid digits THEN # had an error # SKIP ELIF get value( 3 ) /= 2r101 THEN # no end sequence # error message OF result := "missing end sequence" ELIF skip spaces < 6 # should be 9 but we are being # # tolerant # THEN # insufficient trailing spaces # error message OF result := "insufficient trailing spaces" ELIF NOT at end THEN # extraneous stuff after the trailing spaces # error message OF result := "unexpected trailing bits" ELSE # valid so far - if there were reversed digits, # # check they were all reversed # # and correct the digits to be in 0..9 # BOOL all reversed := TRUE; FOR d TO upc digits DO IF ( digits OF result )[ d ] < 0 THEN # reversd digit # ( digits OF result )[ d ] := ABS ( digits OF result )[ d ] - 1 ELSE # normal digit # ( digits OF result )[ d ] -:= 1; all reversed := FALSE FI OD; IF inverted OF result AND NOT all reversed THEN # had a mixture of inverted and non-inverted # # digits # error message OF result := "some reversed digits found" ELSE # the code appears valid - check the check sum # IF inverted OF result THEN # the code was reversed - reverse the digits # FOR d TO digits per side DO INT right digit = ( digits OF result )[ ( upc digits + 1 ) - d ]; ( digits OF result )[ ( upc digits + 1 ) - d ] := ( digits OF result )[ d ]; ( digits OF result )[ d ] := right digit OD FI; INT check sum := 0; FOR d FROM 1 BY 2 TO upc digits DO check sum +:= 3 * ( digits OF result )[ d ] OD; FOR d FROM 2 BY 2 TO upc digits DO check sum +:= ( digits OF result )[ d ] OD; IF check sum MOD 10 /= 0 THEN # invalid check digit # error message OF result := "incorrect check digit" ELSE # the UPC code appears valid # valid OF result := TRUE FI FI FI FI FI; result END; # parse upc # # task test cases # []STRING tests = ( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " , " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " , " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " , " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " , " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " , " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " , " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " , " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " , " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " , " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ); FOR t pos FROM LWB tests TO UPB tests DO UPC code = parse upc( tests[ t pos ] ); print( ( whole( t pos, -2 ), ":" ) ); IF NOT valid OF code THEN # invalid UPC code # print( ( " error: ", error message OF code, newline ) ) ELSE # valid code # FOR d TO upc digits - 1 DO print( ( whole( ( digits OF code )[ d ], -2 ) ) ) OD; print( ( " valid" ) ); IF inverted OF code THEN print( ( " (inverted)" ) ) FI; print( ( newline ) ) FI OD END
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#Fortran
Fortran
PROGRAM TEST !Define some data aggregates, then write and read them. CHARACTER*28 FAVOURITEFRUIT LOGICAL NEEDSPEELING LOGICAL SEEDSREMOVED INTEGER NUMBEROFBANANAS NAMELIST /FRUIT/ FAVOURITEFRUIT,NEEDSPEELING,SEEDSREMOVED, 1 NUMBEROFBANANAS INTEGER F !An I/O unit number. F = 10 !This will do.   Create an example file to show its format. OPEN(F,FILE="Basket.txt",STATUS="REPLACE",ACTION="WRITE", !First, prepare a recipient file. 1 DELIM="QUOTE") !CHARACTER variables will be enquoted. FAVOURITEFRUIT = "Banana" NEEDSPEELING = .TRUE. SEEDSREMOVED = .FALSE. NUMBEROFBANANAS = 48 WRITE (F,FRUIT) !Write the lot in one go. CLOSE (F) !Finished with output. Can now read from the file. OPEN(F,FILE="Basket.txt",STATUS="OLD",ACTION="READ", !Get it back. 1 DELIM="QUOTE") READ (F,FRUIT) !Read who knows what. WRITE (6,FRUIT) 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
#Ceylon
Ceylon
shared void run() { print("enter any text here"); value text = process.readLine(); print(text); print("enter the number 75000 here"); if (is Integer number = Integer.parse(process.readLine() else "")) { print("``number == 75k then number else "close enough"``"); } else { print("That was not a number per se."); } }
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
#Clojure
Clojure
(import '(java.util Scanner)) (def scan (Scanner. *in*)) (def s (.nextLine scan)) (def n (.nextInt scan))
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
#Frink
Frink
  s = input["Enter a string: "] i = parseInt[input["Enter an integer: "]]  
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
#Gambas
Gambas
hTextBox As TextBox hValueBox As ValueBox hLabel As Label   Public Sub Form_Open()   With Me .Height = 100 .Width = 300 .padding = 5 .Arrangement = Arrange.Vertical .Title = "User input/Graphical" End With   hTextBox = New TextBox(Me) As "TextBox1" hTextBox.Expand = True   hValueBox = New ValueBox(Me) As "ValueBox1" hValueBox.Expand = True   hLabel = New Label(Me) hLabel.expand = True   End   Public Sub TextBox1_Change()   hLabel.text = hTextBox.Text & " - " & Str(hValueBox.value)   End   Public Sub valueBox1_Change()   TextBox1_Change   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.
#Forth
Forth
: showbytes ( c-addr u -- ) over + swap ?do i c@ 3 .r loop ;   : test {: xc -- :} xc xemit xc 6 .r xc pad xc!+ pad tuck - ( c-addr u ) 2dup showbytes drop xc@+ xc <> abort" test failed" drop cr ;   hex $41 test $f6 test $416 test $20ac test $1d11e test \ can also be written as \ 'A' test 'ö' test 'Ж' test '€' test '𝄞' test  
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.
#Go
Go
package main   import ( "bytes" "encoding/hex" "fmt" "log" "strings" )   var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, }   func main() { for _, tc := range testCases { // derive some things from test data u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } // exercise encoder and decoder on test data e := encodeUTF8(tc.rune) d := decodeUTF8(b) // show function return values fmt.Printf("%c  %-7s  %X\n", d, u, e) // validate return values against test data if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } }   const ( // first byte of a 2-byte encoding starts 110 and carries 5 bits of data b2Lead = 0xC0 // 1100 0000 b2Mask = 0x1F // 0001 1111   // first byte of a 3-byte encoding starts 1110 and carries 4 bits of data b3Lead = 0xE0 // 1110 0000 b3Mask = 0x0F // 0000 1111   // first byte of a 4-byte encoding starts 11110 and carries 3 bits of data b4Lead = 0xF0 // 1111 0000 b4Mask = 0x07 // 0000 0111   // non-first bytes start 10 and carry 6 bits of data mbLead = 0x80 // 1000 0000 mbMask = 0x3F // 0011 1111 )   func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: // max code point that encodes into a single byte return []byte{byte(r)} case i <= 1<<11-1: // into two bytes return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: // three return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } }   func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Pascal
Pascal
without js -- (peek/poke, call_back) constant Here_am_I = "Here am I" function Query(atom pData, pLength) integer len = peekNS(pLength,machine_word(),0) if poke_string(pData,len,Here_am_I) then return 0 end if pokeN(pLength,length(Here_am_I)+1,machine_word()) return 1 end function constant Query_cb = call_back(Query)
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Phix
Phix
without js -- (peek/poke, call_back) constant Here_am_I = "Here am I" function Query(atom pData, pLength) integer len = peekNS(pLength,machine_word(),0) if poke_string(pData,len,Here_am_I) then return 0 end if pokeN(pLength,length(Here_am_I)+1,machine_word()) return 1 end function constant Query_cb = call_back(Query)
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#M2000_Interpreter
M2000 Interpreter
  Module checkit { any=lambda (z$)->{=lambda z$ (a$)->instr(z$,a$)>0} one=lambda (z$)->{=lambda z$ (a$)->z$=a$} number$="0123456789"   series=Lambda -> { func=Array([]) =lambda func (&line$, &res$)->{ if line$="" then exit k=each(func) def p=0,ok as boolean while k { ok=false : p++ : f=array(k) if not f(mid$(line$,p,1)) then exit ok=true } if ok then res$=left$(line$, p) : line$=mid$(line$, p+1) =ok } }   is_any=lambda series, any (c$) ->series(any(c$)) is_one=lambda series, one (c$) ->series(one(c$)) Is_Alpha=series(lambda (a$)-> a$ ~ "[a-zA-Z]") Is_digit=series(any(number$)) Is_hex=any(number$+"abcdefABCDEF")   optionals=Lambda -> { func=Array([]) =lambda func (&line$, &res$)->{ k=each(func) def ok as boolean while k { f=array(k) if f(&line$,&res$) then ok=true : exit } =ok } } repeated=Lambda (func)-> { =lambda func (&line$, &res$)->{ def ok as boolean, a$ res$="" do { sec=len(line$) if not func(&line$,&a$) then exit res$+=a$ ok=true } until line$="" or sec=len(line$) =ok } }   oneAndoptional=lambda (func1, func2) -> { =lambda func1, func2 (&line$, &res$)->{ def ok as boolean, a$ res$="" if not func1(&line$,&res$) then exit if func2(&line$,&a$) then res$+=a$ =True } } many=Lambda -> { func=Array([]) =lambda func (&line$, &res$)->{ k=each(func) def p=0,ok as boolean, acc$ oldline$=line$ while k { ok=false res$="" if line$="" then exit f=array(k) if not f(&line$,&res$) then exit acc$+=res$ ok=true } if not ok then {line$=oldline$} else res$=acc$ =ok } } is_safe=series(any("$-_@.&")) Is_extra=series(any("!*'(),"+chr$(34))) Is_Escape=series(any("%"), is_hex, is_hex) \\Is_reserved=series(any("=;/#?: ")) is_xalpha=optionals(Is_Alpha, is_digit, is_safe, is_extra, is_escape) is_xalphas=oneAndoptional(is_xalpha,repeated(is_xalpha)) is_xpalpha=optionals(is_xalpha, is_one("+")) is_xpalphas=oneAndoptional(is_xpalpha,repeated(is_xpalpha)) Is_ialpha=oneAndoptional(Is_Alpha,repeated(is_xpalphas)) is_fragmentid=lambda is_xalphas (&lines$, &res$) -> { =is_xalphas(&lines$, &res$) } is_search=oneAndoptional(is_xalphas, repeated(many(series(one("+")), is_xalphas))) is_void=lambda (f)-> { =lambda f (&oldline$, &res$)-> { line$=oldline$ if f(&line$, &res$) then {oldline$=line$ } else res$="" =true } } is_scheme=is_ialpha is_path=repeated(oneAndoptional(is_void(is_xpalphas), series(one("/")))) is_uri=oneAndoptional(many(is_scheme, series(one(":")), is_path), many(series(one("?")),is_search)) is_fragmentaddress=oneAndoptional(is_uri, many(series(one("#")),is_fragmentid ))   data "foo://example.com:8042/over/there?name=ferret#nose" data "urn:example:animal:ferret:nose" data "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true " data "ftp://ftp.is.co.za/rfc/rfc1808.txt" data "http://www.ietf.org/rfc/rfc2396.txt#header1" data "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" data "mailto:[email protected]" data "tel:+1-816-555-1212" data "telnet://192.0.2.16:80/" data "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"   while not empty { read What$ pen 15 { Print What$ } a$="" If is_scheme(&What$, &a$) Then Print "Scheme=";a$ : What$=mid$(What$,2) If is_path(&What$, &a$) Then { count=0 while left$(a$, 1)="/" { a$=mid$(a$,2): count++} if count>1 then { domain$=leftpart$(a$+"/", "/") a$=rightpart$(a$,"/") if domain$<>"" Then Print "Domain:";Domain$ if a$<>"" Then Print "Path:";a$ } else.if left$(What$,1) =":" then { Print "path:";a$+What$: What$="" } Else Print "Data:"; a$   }   if left$(What$,1) =":" then { is_number=repeated(is_digit) What$=mid$(What$,2): If is_number(&What$, &a$) Then Print "Port:";a$ if not left$(What$,1)="/" then exit If is_path(&What$, &a$) Then { while left$(a$, 1)="/" { a$=mid$(a$,2)} if a$<>"" Then Print "Path:";a$ } } if left$(What$, 1)="?" then { What$=mid$(What$,2) If is_search(&What$, &a$) Then { v$="" if left$(What$, 1)="=" then { What$=mid$(What$,2) If is_search(&What$, &v$) Then Print "Query:";a$;"=";v$ } else Print "Query:";a$ } } While left$(What$, 1)="#" { What$=mid$(What$,2) if not is_xalphas(&What$, &a$) Then exit Print "fragment:";a$ } if What$<>"" Then Print "Data:"; What$ } } Checkit  
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
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
#Free_Pascal
Free Pascal
function urlEncode(data: string): AnsiString; var ch: AnsiChar; begin Result := ''; for ch in data do begin if ((Ord(ch) < 65) or (Ord(ch) > 90)) and ((Ord(ch) < 97) or (Ord(ch) > 122)) then begin Result := Result + '%' + IntToHex(Ord(ch), 2); end else Result := Result + ch; end; end;
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#FreeBASIC
FreeBASIC
  Dim Shared As String lookUp(256) For cadena As Integer = 0 To 256 lookUp(cadena) = "%" + Hex(cadena) Next cadena   Function string2url(cadena As String) As String Dim As String cadTemp, cadDevu For j As Integer = 1 To Len(cadena) cadTemp = Mid(cadena, j, 1) If Instr( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", cadTemp) Then cadDevu &= cadTemp Else cadDevu &= lookUp(Asc(cadTemp)) End If Next j Return cadDevu End Function   Dim As String URL = "http://foo bar/"   Print "Supplied URL '"; URL; "'" Print "URL encoding '"; string2url(URL); "'" Sleep  
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
#E
E
def x := 1 x + x # returns 2
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
#EasyLang
EasyLang
# it is statically typed # # global number variable n = 99 print n # global array of numbers a[] = [ 2.1 3.14 3 ] # func f . . # i is local, because it is first used in the function for i range len a[] print a[i] . . call f # # string domain$ = "easylang.online" print domain$ # # array of strings fruits$[] = [ "apple" "banana" "orange" ] print fruits$[]
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.
#JavaScript
JavaScript
(() => { 'use strict';   // vanEck :: Int -> [Int] const vanEck = n => reverse( churchNumeral(n)( xs => 0 < xs.length ? cons( maybe( 0, succ, elemIndex(xs[0], xs.slice(1)) ), xs ) : [0] )([]) );   // TEST ----------------------------------------------- const main = () => { console.log('VanEck series:\n') showLog('First 10 terms', vanEck(10)) showLog('Terms 991-1000', vanEck(1000).slice(990)) };   // GENERIC FUNCTIONS ----------------------------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // churchNumeral :: Int -> (a -> a) -> a -> a const churchNumeral = n => f => x => Array.from({ length: n }, () => f) .reduce((a, g) => g(a), x)   // cons :: a -> [a] -> [a] const cons = (x, xs) => [x].concat(xs)   // elemIndex :: Eq a => a -> [a] -> Maybe Int const elemIndex = (x, xs) => { const i = xs.indexOf(x); return -1 === i ? ( Nothing() ) : Just(i); };   // maybe :: b -> (a -> b) -> Maybe a -> b const maybe = (v, f, m) => m.Nothing ? v : f(m.Just);   // reverse :: [a] -> [a] const reverse = xs => 'string' !== typeof xs ? ( xs.slice(0).reverse() ) : xs.split('').reverse().join('');   // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') );   // succ :: Int -> Int const succ = x => 1 + x;   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#PureBasic
PureBasic
EnableExplicit DisableDebugger   Macro CheckVamp(CheckNum) c=0 : i=CheckNum : Print(~"\nCheck number: "+Str(i)+~"\n") Gosub VampireLoop : If c=0 : Print(Str(i)+" is not vampiric.") : EndIf : PrintN("") EndMacro   Procedure.i Factor(number.i,counter.i) If number>0 And number>=counter*counter And number%counter=0 ProcedureReturn counter EndIf ProcedureReturn 0 EndProcedure   Procedure.b IsVampire(f1.i,f2.i) Define a.s=Str(f1*f2), b.s=Str(f1), c.s=Str(f2), d.s=b+c, i.i If Len(a)=Len(d) And Len(b)=Len(c) While Len(a) i=FindString(d,Left(a,1)) If i a=Mid(a,2) d=RemoveString(d,Mid(d,i,1),#PB_String_NoCase,i,1) Else ProcedureReturn #False EndIf Wend ProcedureReturn Bool(Len(d)=0) EndIf ProcedureReturn #False EndProcedure   OpenConsole("Vampire number") Define i.i, j.i, m.i, c.i=0   PrintN("The first 25 Vampire numbers...") While c<25 : i+1 : Gosub VampireLoop : Wend PrintN("") CheckVamp(16758243290880) : CheckVamp(24959017348650) : CheckVamp(14593825548650) Input() End   VampireLoop: For j=1 To Int(Sqr(i)) If Factor(i,j)>0 m=i/j Else Continue EndIf If IsVampire(m,j) c+1 PrintN(RSet(Str(c),3," ")+". "+RSet(Str(i),10," ")+": ["+Str(j)+", "+Str(m)+"]") EndIf Next Return
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
#Maxima
Maxima
show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$   show(1, 2, 3, 4);   apply(show, [1, 2, 3, 4]);   /* Actually, the built-in function "disp" is already what we want */ disp(1, 2, 3, 4);   apply(disp, [1, 2, 3, 4]);
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
#Metafont
Metafont
def print_arg(text t) = for x = t: if unknown x: message "unknown value" elseif numeric x: message decimal x elseif string x: message x elseif path x: message "a path" elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x)) elseif boolean x: if x: message "true!" else: message "false!" fi elseif pen x: message "a pen" elseif picture x: message "a picture" elseif transform x: message "a transform" fi; endfor enddef;   print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle); end
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Swift
Swift
import Foundation #if canImport(Numerics) import Numerics #endif   struct Vector<T: Numeric> { var x: T var y: T   func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint { return String(format: "[%.\(precision)f, %.\(precision)f]", x, y) }   static func +(lhs: Vector, rhs: Vector) -> Vector { return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y) }   static func -(lhs: Vector, rhs: Vector) -> Vector { return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y) }   static func *(lhs: Vector, scalar: T) -> Vector { return Vector(x: lhs.x * scalar, y: lhs.y * scalar) }   static func /(lhs: Vector, scalar: T) -> Vector where T: FloatingPoint { return Vector(x: lhs.x / scalar, y: lhs.y / scalar) }   static func /(lhs: Vector, scalar: T) -> Vector where T: BinaryInteger { return Vector(x: lhs.x / scalar, y: lhs.y / scalar) } }   #if canImport(Numerics) extension Vector where T: ElementaryFunctions { static func fromPolar(radians: T, theta: T) -> Vector { return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta)) } } #else extension Vector where T == Double { static func fromPolar(radians: Double, theta: Double) -> Vector { return Vector(x: radians * cos(theta), y: radians * sin(theta)) } } #endif   print(Vector(x: 4, y: 5)) print(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted()) print((Vector(x: 2, y: 3) + Vector(x: 4, y: 6))) print((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted()) print((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted()) print((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted()) print(Vector(x: 3, y: 4) / 2)
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Tcl
Tcl
namespace path ::tcl::mathop proc vec {op a b} { if {[llength $a] == 1 && [llength $b] == 1} { $op $a $b } elseif {[llength $a]==1} { lmap i $b {vec $op $a $i} } elseif {[llength $b]==1} { lmap i $a {vec $op $i $b} } elseif {[llength $a] == [llength $b]} { lmap i $a j $b {vec $op $i $j} } else {error "length mismatch [llength $a] != [llength $b]"} }   proc polar {r t} { list [expr {$r * cos($t)}] [expr {$r * sin($t)}] }   proc check {cmd res} { set r [uplevel 1 $cmd] if {$r eq $res} { puts "Ok! $cmd \t = $res" } else { puts "ERROR: $cmd = $r \t expected $res" } }   check {vec + {5 7} {2 3}} {7 10} check {vec - {5 7} {2 3}} {3 4} check {vec * {5 7} 11} {55 77} check {vec / {5 7} 2.0} {2.5 3.5} check {polar 2 0.785398} {1.41421 1.41421}
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Smalltalk
Smalltalk
  prep := [:s | s select:[:ch | ch isLetter] thenCollect:[:ch | ch asUppercase]]. encrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:((cypher at:((i-1)\\key size+1))-$A) ]]. decrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:26-((cypher at:((i-1)\\key size+1))-$A) ]].  
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
#F.23
F#
let dot (ax, ay, az) (bx, by, bz) = ax * bx + ay * by + az * bz   let cross (ax, ay, az) (bx, by, bz) = (ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx)   let scalTrip a b c = dot a (cross b c)   let vecTrip a b c = cross a (cross b c)   [<EntryPoint>] let main _ = let a = (3.0, 4.0, 5.0) let b = (4.0, 3.0, 5.0) let c = (-5.0, -12.0, -13.0) printfn "%A" (dot a b) printfn "%A" (cross a b) printfn "%A" (scalTrip a b c) printfn "%A" (vecTrip a b c) 0 // return an integer exit code
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[LuhnQ, VakudISINQ] LuhnQ[n_Integer] := Block[{digits = Reverse@IntegerDigits@n}, Mod[Total[{digits[[;; ;; 2]], IntegerDigits[2 #] & /@ digits[[2 ;; ;; 2]]}, -1], 10] == 0] VakudISINQ[sin_String] := Module[{s = ToUpperCase[sin]}, If[StringMatchQ[s, LetterCharacter ~~ LetterCharacter ~~ Repeated[DigitCharacter | LetterCharacter, {9}] ~~ DigitCharacter], s = StringJoin[ Characters[s] /. Thread[CharacterRange["A", "Z"] -> ToString /@ Range[10, 35]]]; LuhnQ[ToExpression[s]] , False ] ] VakudISINQ /@ {"US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"}
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
#Nim
Nim
import strformat   const DigitRange = '0'..'9' UpperCaseRange = 'A'..'Z'   type ISINError = object of ValueError     proc luhn(s: string): bool = const m = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] var sum = 0 var odd = true for i in countdown(s.high, 0): let digit = ord(s[i]) - ord('0') sum += (if odd: digit else: m[digit]) odd = not odd result = sum mod 10 == 0     proc validateISIN(s: string) = if s.len != 12: raise newException(ISINError, "wrong length") if s[0] notin UpperCaseRange or s[1] notin UpperCaseRange: raise newException(ISINError, "wrong country code") if s[11] notin DigitRange: raise newException(ISINError, "wrong checksum character") var t: string for ch in s: case ch of '0'..'9': t.add ch of 'A'..'Z': t.addInt ord(ch) - ord('A') + 10 else: raise newException(ISINError, "invalid characters in code") if not t.luhn(): raise newException(ISINError, "checksum error")     when isMainModule:   for isin in ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]: try: isin.validateISIN() echo &"{isin} is valid." except ISINError: echo &"{isin} is not valid: {getCurrentExceptionMsg()}."
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
#Java
Java
public class VanDerCorput{ public static double vdc(int n){ double vdc = 0; int denom = 1; while(n != 0){ vdc += n % 2.0 / (denom *= 2); n /= 2; } return vdc; }   public static void main(String[] args){ for(int i = 0; i <= 10; i++){ System.out.println(vdc(i)); } } }
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
#jq
jq
# vdc(base) converts an input decimal integer to a decimal number based on the van der # Corput sequence using base 'base', e.g. (4 | vdc(2)) is 0.125. # def vdc(base):   # The helper function converts a stream of residuals to a decimal, # e.g. if base is 2, then decimalize( (0,0,1) ) yields 0.125 def decimalize(stream): reduce stream as $d # state: [accumulator, power] ( [0, 1/base]; .[1] as $power | [ .[0] + ($d * $power), $power / base] ) | .[0];   if . == 0 then 0 else decimalize(recurse( if . == 0 then empty else ./base | floor end ) % base) 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á".
#Delphi
Delphi
program URLEncoding;   {$APPTYPE CONSOLE}   uses IdURI;   begin Writeln(TIdURI.URLDecode('http%3A%2F%2Ffoo%20bar%2F')); 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á".
#Elixir
Elixir
IO.inspect URI.decode("http%3A%2F%2Ffoo%20bar%2F") IO.inspect URI.decode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#AutoHotkey
AutoHotkey
UPC2Dec(code){ lBits :={" ## #":0," ## #":1," # ##":2," #### #":3," # ##":4," ## #":5," # ####":6," ### ##":7," ## ###":8," # ##":9} xlBits:={"# ## ":0,"# ## ":1,"## # ":2,"# #### ":3,"## # ":4,"# ## ":5,"#### # ":6,"## ### ":7,"### ## ":8,"## # ":9} rBits :={"### # ":0,"## ## ":1,"## ## ":2,"# # ":3,"# ### ":4,"# ### ":5,"# # ":6,"# # ":7,"# # ":8,"### # ":9} xrBits:={" # ###":0," ## ##":1," ## ##":2," # #":3," ### #":4," ### #":5," # #":6," # #":7," # #":8," # ###":9} UPC := "", CD := 0, code := Trim(code, " ") S := SubStr(code, 1, 3), code := SubStr(code, 4) ; start or "upside down" end sequence loop 6 C := SubStr(code, 1, 7), code := SubStr(code, 8) ; six left hand or "upside down" right hand digits , UPC := lBits[C] <> "" ? UPC . lBits[C] : xrBits[C] . UPC M := SubStr(code, 1, 5), code := SubStr(code, 6) ; middle sequence loop 6 C := SubStr(code, 1, 7), code := SubStr(code, 8) ; six right hand or "upside down" left hand digits , UPC := rBits[C] <> "" ? UPC . rBits[C] : xlBits[C] . UPC E := SubStr(code, 1, 3), code := SubStr(code, 4) ; end or "upside down" start sequence for k, v in StrSplit(UPC) CD += Mod(A_Index, 2) ? v*3 : v ; Check Digit if (S <> "# #") || (M <> " # # ") || (E <> "# #") || Mod(CD, 10) return "Invalid!" return UPC }  
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type ConfigData favouriteFruit As String needsPeeling As Boolean seedsRemoved As Boolean numberOfBananas As UInteger numberOfStrawberries As UInteger End Type   Sub updateConfigData(fileName As String, cData As ConfigData) Dim fileNum As Integer = FreeFile Open fileName For Input As #fileNum If err > 0 Then Print "File could not be opened" Sleep End End If Dim tempFileName As String = "temp_" + fileName Dim fileNum2 As Integer = FreeFile Open tempFileName For Output As #fileNum2 Dim As Boolean hadFruit, hadPeeling, hadSeeds, hadBananas, hadStrawberries '' all false by default Dim As String ln While Not Eof(fileNum) Line Input #fileNum, ln If ln = "" OrElse Left(ln, 1) = "#" Then Print #fileNum2, ln Continue While End If ln = Trim(LTrim(ln, ";"), Any !" \t") If ln = "" Then Continue While If UCase(Left(ln, 14)) = "FAVOURITEFRUIT" Then If hadFruit Then Continue While hadFruit = True Print #fileNum2, "FAVOURITEFRUIT " + cData.favouriteFruit ElseIf UCase(Left(ln, 12)) = "NEEDSPEELING" Then If hadPeeling Then Continue While hadPeeling = True If cData.needsPeeling Then Print #fileNum2, "NEEDSPEELING" Else Print #fileNum2, "; NEEDSPEELING" End If ElseIf UCase(Left(ln, 12)) = "SEEDSREMOVED" Then If hadSeeds Then Continue While hadSeeds = True If cData.seedsRemoved Then Print #fileNum2, "SEEDSREMOVED" Else Print #fileNum2, "; SEEDSREMOVED" End If ElseIf UCase(Left(ln, 15)) = "NUMBEROFBANANAS" Then If hadBananas Then Continue While hadBananas = True Print #fileNum2, "NUMBEROFBANANAS " + Str(cData.numberOfBananas) ElseIf UCase(Left(ln, 20)) = "NUMBEROFSTRAWBERRIES" Then If hadStrawberries Then Continue While hadStrawberries = True Print #fileNum2, "NUMBEROFSTRAWBERRIES " + Str(cData.numberOfStrawBerries) End If Wend   If Not hadFruit Then Print #fileNum2, "FAVOURITEFRUIT " + cData.favouriteFruit End If If Not hadPeeling Then If cData.needsPeeling Then Print #fileNum2, "NEEDSPEELING" Else Print #fileNum2, "; NEEDSPEELING" End If End If If Not hadSeeds Then If cData.seedsRemoved Then Print #fileNum2, "SEEDSREMOVED" Else Print #fileNum2, "; SEEDSREMOVED" End If End If If Not hadBananas Then Print #fileNum2, "NUMBEROFBANANAS " + Str(cData.numberOfBananas) End If If Not hadStrawberries Then Print #fileNum2, "NUMBEROFSTRAWBERRIES " + Str(cData.numberOfStrawBerries) End If   Close #fileNum : Close #fileNum2 Kill(fileName) Name (tempFileName fileName) End Sub   Dim fileName As String = "config2.txt" Dim cData As ConfigData With cData .favouriteFruit = "banana" .needsPeeling = False .seedsRemoved = True .numberOfBananas = 1024 .numberOfStrawberries = 62000 End With   updateConfigData fileName, cData Print Print "Press any key to quit" Sleep
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Get-Input.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Input-String PIC X(30). 01 Input-Int PIC 9(5).   PROCEDURE DIVISION. DISPLAY "Enter a string:" ACCEPT Input-String   DISPLAY "Enter a number:" ACCEPT Input-Int   GOBACK .
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
#Common_Lisp
Common Lisp
(format t "Enter some text: ") (let ((s (read-line))) (format t "You entered ~s~%" s))   (format t "Enter a number: ") (let ((n (read))) (if (numberp n) (format t "You entered ~d.~%" n) (format t "That was not a number.")))
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
#Go
Go
package main   import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" )   func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid input", ) dialog.Run() dialog.Destroy() return false } return true }   func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } }   func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil)   window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() })   vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1) check(err, "Unable to create vertical box:") vbox.SetBorderWidth(1)   hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create first horizontal box:")   hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create second horizontal box:")   label, err := gtk.LabelNew("Enter a string and the number 75000 \n") check(err, "Unable to create label:")   sel, err := gtk.LabelNew("String: ") check(err, "Unable to create string entry label:")   nel, err := gtk.LabelNew("Number: ") check(err, "Unable to create number entry label:")   se, err := gtk.EntryNew() check(err, "Unable to create string entry:")   ne, err := gtk.EntryNew() check(err, "Unable to create number entry:")   hbox1.PackStart(sel, false, false, 2) hbox1.PackStart(se, false, false, 2)   hbox2.PackStart(nel, false, false, 2) hbox2.PackStart(ne, false, false, 2)   // button to accept ab, err := gtk.ButtonNewWithLabel("Accept") check(err, "Unable to create accept button:") ab.Connect("clicked", func() { // read and validate the entered values str1, _ := se.GetText() str2, _ := ne.GetText() if validateInput(window, str1, str2) { window.Destroy() // close window if input is OK } })   vbox.Add(label) vbox.Add(hbox1) vbox.Add(hbox2) vbox.Add(ab) window.Add(vbox)   window.ShowAll() gtk.Main() }
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.
#Groovy
Groovy
import java.nio.charset.StandardCharsets   class UTF8EncodeDecode { static byte[] utf8encode(int codePoint) { char[] characters = [codePoint] new String(characters, 0, 1).getBytes StandardCharsets.UTF_8 }   static int utf8decode(byte[] bytes) { new String(bytes, StandardCharsets.UTF_8).codePointAt(0) }   static void main(String[] args) { printf "%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"   ([0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E]).each { int codePoint -> byte[] encoded = utf8encode codePoint Formatter formatter = new Formatter() encoded.each { byte b -> formatter.format "%02X ", b } String encodedHex = formatter.toString() int decoded = utf8decode encoded printf "%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codePoint, Character.getName(codePoint), codePoint, encodedHex, decoded } } }
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#PicoLisp
PicoLisp
(let (Str "Here am I" Len (format (opt))) # Get length from command line (unless (>= (size Str) Len) # Check buffer size (prinl Str) ) ) # Return string if OK
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Python
Python
  # store this in file rc_embed.py # store this in file rc_embed.py def query(buffer_length): message = b'Here am I' L = len(message) return message[0:L*(L <= buffer_length)]  
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Nim
Nim
import uri, strformat   proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}"   let urls = ["foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:[email protected]", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://[email protected]", "https://bob:[email protected]/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"]   for url in urls: printUri(url)
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Objeck
Objeck
use Web.HTTP;   class Test { function : Main(args : String[]) ~ Nil { urls := [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:[email protected]", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64:"];   each(i : urls) { url := Url->New(urls[i]); if(url->Parsed()) { url->ToString()->PrintLine(); }; }; } }
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
#Frink
Frink
println[URLEncode["http://foo bar/"]]
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Go
Go
package main   import ( "fmt" "net/url" )   func main() { fmt.Println(url.QueryEscape("http://foo bar/")) }
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Eiffel
Eiffel
  class APPLICATION inherit ARGUMENTS create make   feature {NONE} -- Initialization   make -- Run application. local i: INTEGER s: STRING do i := 100 s := "Some string" create a.make_empty end   feature {NONE} -- Class Features   a: ARRAY[INTEGER]  
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
#Ela
Ela
x = 42   sum x y = x + y
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#jq
jq
# Input: an array # If the rightmost element, .[-1], does not occur elsewhere, return 0; # otherwise return the "depth" of its rightmost occurrence in .[0:-2] def depth: .[-1] as $x | length as $length | first(range($length-2; -1; -1) as $i | select(.[$i] == $x) | $length - 1 - $i) // 0 ;   # Generate a stream of the first $n van Eck integers: def vanEck($n): def v: recurse( if length == $n then empty else . + [depth] end ); [0] | v | .[-1];   # The task: [vanEck(10)], [vanEck(1000)][990:1001]  
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.
#Julia
Julia
function vanecksequence(N, startval=0) ret = zeros(Int, N) ret[1] = startval for i in 1:N-1 lastseen = findlast(x -> x == ret[i], ret[1:i-1]) if lastseen != nothing ret[i + 1] = i - lastseen end end ret end   println(vanecksequence(10)) println(vanecksequence(1000)[991:1000])  
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Python
Python
from __future__ import division   import math from operator import mul from itertools import product from functools import reduce     def fac(n): '''\ return the prime factors for n >>> fac(600) [5, 5, 3, 2, 2, 2] >>> fac(1000) [5, 5, 5, 2, 2, 2] >>> ''' step = lambda x: 1 + x*4 - (x//2)*2 maxq = int(math.floor(math.sqrt(n))) d = 1 q = n % 2 == 0 and 2 or 3 while q <= maxq and n % q != 0: q = step(d) d += 1 res = [] if q <= maxq: res.extend(fac(n//q)) res.extend(fac(q)) else: res=[n] return res   def fact(n): '''\ return the prime factors and their multiplicities for n >>> fact(600) [(2, 3), (3, 1), (5, 2)] >>> fact(1000) [(2, 3), (5, 3)] >>> ''' res = fac(n) return [(c, res.count(c)) for c in set(res)]   def divisors(n): 'Returns all the divisors of n' factors = fact(n) # [(primefactor, multiplicity), ...] primes, maxpowers = zip(*factors) powerranges = (range(m+1) for m in maxpowers) powers = product(*powerranges) return ( reduce(mul, (prime**power for prime, power in zip(primes, powergroup)), 1) for powergroup in powers)   def vampire(n): fangsets = set( frozenset([d, n//d]) for d in divisors(n) if (len(str(d)) == len(str(n))/2. and sorted(str(d) + str(n//d)) == sorted(str(n)) and (str(d)[-1] == 0) + (str(n//d)[-1] == 0) <=1) ) return sorted(tuple(sorted(fangs)) for fangs in fangsets)     if __name__ == '__main__': print('First 25 vampire numbers') count = n = 0 while count <25: n += 1 fangpairs = vampire(n) if fangpairs: count += 1 print('%i: %r' % (n, fangpairs)) print('\nSpecific checks for fangpairs') for n in (16758243290880, 24959017348650, 14593825548650): fangpairs = vampire(n) print('%i: %r' % (n, fangpairs))
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
#Modula-3
Modula-3
MODULE Varargs EXPORTS Main;   IMPORT IO;   VAR strings := ARRAY [1..5] OF TEXT {"foo", "bar", "baz", "quux", "zeepf"};   PROCEDURE Variable(VAR arr: ARRAY OF TEXT) = BEGIN FOR i := FIRST(arr) TO LAST(arr) DO IO.Put(arr[i] & "\n"); END; END Variable;   BEGIN Variable(strings); END Varargs.
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
#Nemerle
Nemerle
using System; using System.Console;   module Variadic { PrintAll (params args : array[object]) : void { foreach (arg in args) WriteLine(arg); }   Main() : void { PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now); } }
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#VBA
VBA
Type vector x As Double y As Double End Type Type vector2 phi As Double r As Double End Type Private Function vector_addition(u As vector, v As vector) As vector vector_addition.x = u.x + v.x vector_addition.y = u.y + v.y End Function Private Function vector_subtraction(u As vector, v As vector) As vector vector_subtraction.x = u.x - v.x vector_subtraction.y = u.y - v.y End Function Private Function scalar_multiplication(u As vector, v As Double) As vector scalar_multiplication.x = u.x * v scalar_multiplication.y = u.y * v End Function Private Function scalar_division(u As vector, v As Double) As vector scalar_division.x = u.x / v scalar_division.y = u.y / v End Function Private Function to_cart(v2 As vector2) As vector to_cart.x = v2.r * Cos(v2.phi) to_cart.y = v2.r * Sin(v2.phi) End Function Private Sub display(u As vector) Debug.Print "( " & Format(u.x, "0.000") & "; " & Format(u.y, "0.000") & ")"; End Sub Public Sub main() Dim a As vector, b As vector, c As vector2, d As Double c.phi = WorksheetFunction.Pi() / 3 c.r = 5 d = 10 a = to_cart(c) b.x = 1: b.y = -2 Debug.Print "addition  : ";: display a: Debug.Print "+";: display b Debug.Print "=";: display vector_addition(a, b): Debug.Print Debug.Print "subtraction  : ";: display a: Debug.Print "-";: display b Debug.Print "=";: display vector_subtraction(a, b): Debug.Print Debug.Print "scalar multiplication: ";: display a: Debug.Print " *";: Debug.Print d; Debug.Print "=";: display scalar_multiplication(a, d): Debug.Print Debug.Print "scalar division  : ";: display a: Debug.Print " /";: Debug.Print d; Debug.Print "=";: display scalar_division(a, d) End Sub
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Class Vector Public store As Double()   Public Sub New(init As IEnumerable(Of Double)) store = init.ToArray() End Sub   Public Sub New(x As Double, y As Double) store = {x, y} End Sub   Public Overloads Shared Operator +(v1 As Vector, v2 As Vector) Return New Vector(v1.store.Zip(v2.store, Function(a, b) a + b)) End Operator   Public Overloads Shared Operator -(v1 As Vector, v2 As Vector) Return New Vector(v1.store.Zip(v2.store, Function(a, b) a - b)) End Operator   Public Overloads Shared Operator *(v1 As Vector, scalar As Double) Return New Vector(v1.store.Select(Function(x) x * scalar)) End Operator   Public Overloads Shared Operator /(v1 As Vector, scalar As Double) Return New Vector(v1.store.Select(Function(x) x / scalar)) End Operator   Public Overrides Function ToString() As String Return String.Format("[{0}]", String.Join(",", store)) End Function End Class   Sub Main() Dim v1 As New Vector(5, 7) Dim v2 As New Vector(2, 3) Console.WriteLine(v1 + v2) Console.WriteLine(v1 - v2) Console.WriteLine(v1 * 11) Console.WriteLine(v1 / 2) ' Works with arbitrary size vectors, too. Dim lostVector As New Vector({4, 8, 15, 16, 23, 42}) Console.WriteLine(lostVector * 7) End Sub   End Module
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Swift
Swift
public func convertToUnicodeScalars( str: String, minChar: UInt32, maxChar: UInt32 ) -> [UInt32] { var scalars = [UInt32]()   for scalar in str.unicodeScalars { let val = scalar.value   guard val >= minChar && val <= maxChar else { continue }   scalars.append(val) }   return scalars }   public struct Vigenere { private let keyScalars: [UInt32] private let smallestScalar: UInt32 private let largestScalar: UInt32 private let sizeAlphabet: UInt32   public init?(key: String, smallestCharacter: Character = "A", largestCharacter: Character = "Z") { let smallScalars = smallestCharacter.unicodeScalars let largeScalars = largestCharacter.unicodeScalars   guard smallScalars.count == 1, largeScalars.count == 1 else { return nil }   self.smallestScalar = smallScalars.first!.value self.largestScalar = largeScalars.first!.value self.sizeAlphabet = (largestScalar - smallestScalar) + 1   let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)   guard !scalars.isEmpty else { return nil }   self.keyScalars = scalars   }   public func decrypt(_ str: String) -> String? { let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)   guard !txtBytes.isEmpty else { return nil }   var res = ""   for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar { guard let char = UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i % keyScalars.count]) % sizeAlphabet &+ smallestScalar) else { return nil }   res += String(char) }   return res }   public func encrypt(_ str: String) -> String? { let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)   guard !txtBytes.isEmpty else { return nil }   var res = ""   for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar { guard let char = UnicodeScalar((c &+ keyScalars[i % keyScalars.count] &- 2 &* smallestScalar) % sizeAlphabet &+ smallestScalar) else { return nil }   res += String(char) }   return res } }   let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; let key = "VIGENERECIPHER"; let cipher = Vigenere(key: key)!   print("Key: \(key)") print("Plain Text: \(text)")   let encoded = cipher.encrypt(text.uppercased())!   print("Cipher Text: \(encoded)")   let decoded = cipher.decrypt(encoded)!   print("Decoded: \(decoded)")   print("\nLarger set:")   let key2 = "Vigenère cipher" let text2 = "This is a ünicode string 😃"   let cipher2 = Vigenere(key: key2, smallestCharacter: " ", largestCharacter: "🛹")!   print("Key: \(key2)") print("Plain Text: \(text2)")   let encoded2 = cipher2.encrypt(text2)!   print("Cipher Text: \(encoded2)")   let decoded2 = cipher2.decrypt(encoded2)!   print("Decoded: \(decoded2)")
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Tcl
Tcl
package require Tcl 8.6   oo::class create Vigenere { variable key constructor {protoKey} { foreach c [split $protoKey ""] { if {[regexp {[A-Za-z]} $c]} { lappend key [scan [string toupper $c] %c] } } }   method encrypt {text} { set out "" set j 0 foreach c [split $text ""] { if {[regexp {[^a-zA-Z]} $c]} continue scan [string toupper $c] %c c append out [format %c [expr {($c+[lindex $key $j]-130)%26+65}]] set j [expr {($j+1) % [llength $key]}] } return $out }   method decrypt {text} { set out "" set j 0 foreach c [split $text ""] { if {[regexp {[^A-Z]} $c]} continue scan $c %c c append out [format %c [expr {($c-[lindex $key $j]+26)%26+65}]] set j [expr {($j+1) % [llength $key]}] } return $out } }