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/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Fortran | Fortran | program test
implicit none
integer :: i !scalar integer
integer,dimension(10) :: ivec !integer vector
real :: r !scalar real
real,dimension(10) :: rvec !real vector
character(len=:),allocatable :: char1, char2 !fortran 2003 allocatable strings
!assignments:
!-- scalars:
i = 1
r = 3.14
!-- vectors:
ivec = 1 !(all elements set to 1)
ivec(1:5) = 2
rvec(1:9) = 0.0
rvec(10) = 1.0
!-- strings:
char1 = 'hello world!'
char2 = char1 !copy from one string to another
char2(1:1) = 'H' !change first character
end program test
|
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.
| #Nim | Nim | const max = 1000
var a: array[max, int]
for n in countup(0, max - 2):
for m in countdown(n - 1, 0):
if a[m] == a[n]:
a[n + 1] = n - m
break
echo "The first ten terms of the Van Eck sequence are:"
echo a[..9]
echo "\nTerms 991 to 1000 of the sequence are:"
echo a[990..^1] |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Pascal | Pascal | program VanEck;
{
* 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 previousely.}
uses
sysutils;
const
MAXNUM = 32381775;//1000*1000*1000;
MAXSEENIDX = (1 shl 7)-1;
var
PosBefore : array of UInt32;
LastSeen : array[0..MAXSEENIDX]of UInt32;// circular buffer
SeenIdx,HaveSeen : Uint32;
procedure OutSeen(Cnt:NativeInt);
var
I,S_Idx : NativeInt;
Begin
IF Cnt > MAXSEENIDX then
Cnt := MAXSEENIDX;
If Cnt > HaveSeen then
Cnt := HaveSeen;
S_Idx := SeenIdx;
S_Idx := (S_Idx-Cnt);
IF S_Idx < 0 then
inc(S_Idx,MAXSEENIDX);
For i := 1 to Cnt do
Begin
write(' ',LastSeen[S_Idx]);
S_Idx:= (S_Idx+1) AND MAXSEENIDX;
end;
writeln;
end;
procedure Test(MaxTestCnt: Uint32);
var
i, actnum, Posi, S_Idx: Uint32;
{$IFDEF FPC}
pPosBef, pSeen: pUint32;
{$ELSE}
pPosBef, pSeen: array of UInt32;
{$ENDIF}
begin
HaveSeen := 0;
if MaxTestCnt > MAXNUM then
EXIT;
Fillchar(LastSeen, SizeOf(LastSeen), #0);
//setlength and clear
setlength(PosBefore, 0);
setlength(PosBefore, MaxTestCnt);
{$IFDEF FPC}
pPosBef := @PosBefore[0];
pSeen := @LastSeen[0];
{$ELSE}
SetLength(pSeen, SizeOf(LastSeen));
setlength(pPosBef, MaxTestCnt);
move(PosBefore[0], pPosBef[0], length(pPosBef));
move(LastSeen[0], pSeen[0], length(pSeen));
{$ENDIF}
S_Idx := 0;
i := 1;
actnum := 0;
repeat
// save value
pSeen[S_Idx] := actnum;
S_Idx := (S_Idx + 1) and MAXSEENIDX;
//examine new value often out of cache
Posi := pPosBef[actnum];
pPosBef[actnum] := i;
// if Posi=0 ? actnum = 0:actnum = i-Posi
if Posi = 0 then
actnum := 0
else
actnum := i - Posi;
inc(i);
until i > MaxTestCnt;
HaveSeen := i - 1;
SeenIdx := S_Idx;
{$IFNDEF FPC}
move(pPosBef[0], PosBefore[0], length(pPosBef));
move(pSeen[0], LastSeen[0], length(pSeen));
{$ENDIF}
end;
Begin
Test(10) ; OutSeen(10000);
Test(1000); OutSeen(10);
Test(MAXNUM); OutSeen(28);
setlength(PosBefore,0);
end. |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Rust | Rust | use std::cmp::{max, min};
static TENS: [u64; 20] = [
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
10000000000000000000,
];
/// Get the number of digits present in x
fn ndigits(mut x: u64) -> u64 {
let mut n = 0;
while x != 0 {
n += 1;
x /= 10;
}
n
}
fn dtally(mut x: u64) -> u64 {
let mut t = 0;
while x != 0 {
t += 1 << ((x % 10) * 6);
x /= 10;
}
t
}
/// Get a list of all fangs of x. Get only the first divider of each fang. The second one can be found simply with x / fang.
fn fangs(x: u64) -> Vec<u64> {
let mut nd = ndigits(x) as usize;
let mut fangs = vec![];
if nd & 1 != 1 {
nd /= 2;
let lo = max(TENS[nd - 1], (x + TENS[nd] - 2) / (TENS[nd] - 1));
let hi = min(x / lo, (x as f64).sqrt() as u64);
let t = dtally(x);
for a in lo..(hi + 1) {
let b = x / a;
if a * b == x && ((a % 10) > 0 || b % 10 > 0) && t == dtally(a) + dtally(b) {
fangs.push(a);
}
}
}
fangs
}
/// Pretty print the fangs of x
fn print_fangs(x: u64, fangs: Vec<u64>) {
print!("{} = ", x);
if fangs.is_empty() {
print!("is not vampiric");
} else {
for fang in fangs {
print!("{} x {}, ", fang, x / fang);
}
}
print!("\n");
}
fn main() {
println!("The first 25 vampire numbers are :");
let mut nfangs = 0;
let mut x = 1;
while nfangs < 25 {
let fangs = fangs(x);
if !fangs.is_empty() {
nfangs += 1;
print_fangs(x, fangs);
}
x += 1;
}
println!("\nSpecial requests :");
print_fangs(16758243290880, fangs(16758243290880));
print_fangs(24959017348650, fangs(24959017348650));
print_fangs(14593825548650, fangs(14593825548650));
}
#[test]
fn test() {
assert_eq!(
fangs(16758243290880),
vec![1982736, 2123856, 2751840, 2817360]
);
assert_eq!(
fangs(24959017348650),
vec![2947050, 2949705, 4125870, 4129587, 4230765]
);
assert_eq!(fangs(14593825548650), vec![]);
} |
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
| #Scala | Scala | import Stream._
import math._
import scala.collection.mutable.ListBuffer
object VampireNumbers extends App {
val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}
val sexp = from(1, 2) // stream of integer: 1,3,5,7, ...
val rs: Stream[Int] => Stream[Pair[Long,Long]] = exps => Pair(pow(10,exps.head).toLong,(pow(10,exps.head)*10-1).toLong)#::rs(exps.tail)
val srs = rs(sexp) // stream of ranges: [10..99], [1000..9999], [100000..999999], ...
val cs: Stream[Pair[Long,Long]] => Stream[Long] = rs => (rs.head._1 to rs.head._2).toStream#:::cs(rs.tail)
val scs = cs(srs) // stream of candidates: 10,11,..,99,1000,1001,..,9999, ...
val it = scs.iterator
val checkVN: Long => Pair[Long,Seq[Pair[Long,Long]]] = n => {
val check: Pair[Long,Long] => Pair[Long,Long] = p => {
val len: Long => Int = n => n.toString.size
val (a,b) = p
if ((a%10==0)&&(b%10==0)) Pair(0,0) else
if (len(a) != len(b)) Pair(0,0) else
if (n.toString.toList.diff(a.toString.toList++b.toString.toList)!=Nil) Pair(0,0) else p
}
Pair(n,(pow(10,log10(sqrt(n).toLong).toLong).toLong+1 to sqrt(n).toLong).filter{i=>n%i==0}
.map {fac =>Pair(fac,n/fac)}.map {p => check(p)}.filter {p => p._1 != 0})
}
val et = elapsed {
val lb = new ListBuffer[Pair[Long,Seq[Pair[Long,Long]]]]
while ((lb.size<25)&&(it.hasNext)) {
checkVN(it.next) match {
case (n, Seq()) =>
case p => lb += p
}
}
lb.toList.zipWithIndex.foreach {p =>
println(p._2+1+": "+p._1._1+(p._1._2:\"")((x,y)=>" = "+x._1+" x "+x._2+y))
}
println
List(16758243290880L, 24959017348650L, 14593825548650L)
.map {checkVN(_)}
.foreach {
case (n, Seq()) => println(n+" is not vampiric")
case p => println(p._1+(p._2:\"")((x,y)=>" = "+x._1+" x "+x._2+y))
}
}
println("\n"+"elapsed time: "+et+" seconds")
} |
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
| #Perl | Perl | sub print_all {
foreach (@_) {
print "$_\n";
}
} |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Phix | Phix | procedure print_args(sequence args)
for i=1 to length(args) do
?args[i]
end for
end procedure
print_args({"Mary", "had", "a", "little", "lamb"})
|
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
| #Vedit_macro_language | Vedit macro language | Get_Input(10, "Key: ", STATLINE+NOCR) // @10 = key
Reg_Copy_Block(11, Cur_Pos, EOL_Pos) // @11 = copy of original text
EOL Ins_Newline
Ins_Text("Key = ") Reg_Ins(10) Ins_Newline
// Prepare the key into numeric registers #130..:
Buf_Switch(Buf_Free)
Reg_Ins(10)
Case_Upper_Block(0, Cur_Pos)
BOF
#2 = Reg_Size(10) // #2 = key length
for (#3=130; #3 < 130+#2; #3++) {
#@3 = Cur_Char
Char(1)
}
Buf_Quit(OK)
Ins_Text("Encrypted: ")
#4 = Cur_Pos
Reg_Ins(11) // copy of original text
Replace_Block("|!|A", "", #4, EOL_Pos, BEGIN+ALL+NOERR) // remove non-alpha chars
Case_Upper_Block(#4, EOL_Pos) // convert to upper case
Goto_Pos(#4)
#1 = 1; Call("ENCRYPT_DECRYPT") // Encrypt the line
Reg_Copy_Block(11, #4, Cur_Pos) // Copy encrypted text text to next line
Ins_Newline
Ins_Text("Decrypted: ")
Reg_Ins(11, BEGIN)
#1 = -1; Call("ENCRYPT_DECRYPT") // Decrypt the line
Return
// Encrypt or decrypt text on current line in-place, starting from cursor position.
// in: #1 = direction (1=encrypt, -1=decrypt)
// #2 = key length, #130...#189 = the key
//
:ENCRYPT_DECRYPT:
Num_Push(6,9)
#6 = 0
While (!At_EOL) {
#7 = #6+130 // pointer to key array
#8 = #@7 // get key character
#9 = (Cur_Char + #8*#1 + 26) % 26 + 'A' // decrypt/encrypt
Ins_Char(#9, OVERWRITE) // write the converted char
#6 = (#6+1) % #2
}
Num_Pop(6,9)
Return |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #FreeBASIC | FreeBASIC | 'Construct only required operators for this.
Type V3
As double x,y,z
declare operator cast() as string
End Type
#define dot *
#define cross ^
#define Show(t1,t) ? #t1;tab(22);t
operator V3.cast() as string
return "("+str(x)+","+str(y)+","+str(z)+")"
end operator
Operator dot(v1 As v3,v2 As v3) As double
Return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z
End Operator
Operator cross(v1 As v3,v2 As v3) As v3
Return type<v3>(v1.y*v2.z-v2.y*v1.z,-(v1.x*v2.z-v2.x*v1.z),v1.x*v2.y-v2.x*v1.y)
End Operator
dim as V3 a = (3, 4, 5), b = (4, 3, 5), c = (-5, -12, -13)
Show(a,a)
Show(b,b)
Show(c,c)
?
Show(a . b,a dot b)
Show(a X b,a cross b)
Show(a . b X c,a dot b cross c)
Show(a X (b X c),a cross (b cross c))
sleep |
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
| #Python | Python | def check_isin(a):
if len(a) != 12 or not all(c.isalpha() for c in a[:2]) or not all(c.isalnum() for c in a[2:]):
return False
s = "".join(str(int(c, 36)) for c in a)
return 0 == (sum(sum(divmod(2 * (ord(c) - 48), 10)) for c in s[-2::-2]) +
sum(ord(c) - 48 for c in s[::-2])) % 10
# A more readable version
def check_isin_alt(a):
if len(a) != 12:
return False
s = []
for i, c in enumerate(a):
if c.isdigit():
if i < 2:
return False
s.append(ord(c) - 48)
elif c.isupper():
if i == 11:
return False
s += divmod(ord(c) - 55, 10)
else:
return False
v = sum(s[::-2])
for k in s[-2::-2]:
k = 2 * k
v += k - 9 if k > 9 else k
return v % 10 == 0
[check_isin(s) for s in ["US0378331005", "US0373831005", "U50378331005", "US03378331005",
"AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]]
# [True, False, False, False, True, True, True] |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Nim | Nim | import rationals, strutils, sugar
type Fract = Rational[int]
proc corput(n: int; base: Positive): Fract =
result = 0.toRational
var b = 1 // base
var n = n
while n != 0:
result += n mod base * b
n = n div base
b /= base
for base in 2..5:
let list = collect(newSeq, for n in 1..10: corput(n, base))
echo "Base $#: ".format(base), list.join(" ") |
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
| #PARI.2FGP | PARI/GP | VdC(n)=n=binary(n);sum(i=1,#n,if(n[i],1.>>(#n+1-i)));
VdC(n)=sum(i=1,#binary(n),if(bittest(n,i-1),1.>>i)); \\ Alternate approach
vector(10,n,VdC(n)) |
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á".
| #Groovy | Groovy | assert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http://foo bar/' |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #Haskell | Haskell | import qualified Data.Char as Char
urlDecode :: String -> Maybe String
urlDecode [] = Just []
urlDecode ('%':xs) =
case xs of
(a:b:xss) ->
urlDecode xss
>>= return . ((Char.chr . read $ "0x" ++ [a,b]) :)
_ -> Nothing
urlDecode ('+':xs) = urlDecode xs >>= return . (' ' :)
urlDecode (x:xs) = urlDecode xs >>= return . (x :)
main :: IO ()
main = putStrLn . maybe "Bad decode" id $ urlDecode "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.
| #Factor | Factor | USING: combinators combinators.short-circuit formatting grouping
kernel locals math math.functions math.vectors sequences
sequences.repeating unicode ;
CONSTANT: numbers {
" ## #"
" ## #"
" # ##"
" #### #"
" # ##"
" ## #"
" # ####"
" ### ##"
" ## ###"
" # ##"
}
: upc>dec ( str -- seq )
[ blank? ] trim 3 tail 3 head* 42 cut 5 tail
[ 35 = 32 35 ? ] map append 7 group [ numbers index ] map ;
: valid-digits? ( seq -- ? ) [ f = ] none? ;
: valid-checksum? ( seq -- ? )
{ 3 1 } 12 cycle v* sum 10 divisor? ;
: valid-upc? ( seq -- ? )
{ [ valid-digits? ] [ valid-checksum? ] } 1&& ;
:: process-upc ( upc -- obj upside-down? )
upc upc>dec :> d
{
{ [ d valid-upc? ] [ d f ] }
{ [ upc reverse upc>dec dup valid-upc? ] [ t ] }
{ [ drop d valid-digits? ] [ "Invalid checksum" f ] }
[ "Invalid digit(s)" f ]
} cond ;
{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # "
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # "
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # "
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # "
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # "
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # "
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # "
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # "
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # "
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
}
[ process-upc "(upside down)" "" ? "%u %s\n" printf ] each |
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
| #Julia | Julia | function cleansyntax(line)
line = strip(line)
if line == ""
return "#=blank line=#"
elseif line[1] == '#'
return line
elseif line[1] == ';'
line = replace(line, r"^;[;]+" => ";")
else # active option
o, p = splitline(line)
line = p == nothing ? uppercase(o) : uppercase(o) * " " * p
end
join(filter(c -> isascii(c[1]) && !iscntrl(c[1]), split(line, "")), "")
end
"""
Run to clean up the configuration file lines prior to other function application.
"""
cleansyntax!(lines) = (for (i, li) in enumerate(lines) lines[i] = cleansyntax(li) end; lines)
isdisabled(line) = startswith(line, [';', '#'])
isenabled(line) = !isdisabled(line)
function splitline(line)
arr = split(line, r"\s+", limit=2)
if length(arr) < 2
return (arr[1], nothing)
end
return (arr[1], arr[2])
end
function disable!(lines, opt)
for (i, li) in enumerate(lines)
if isenabled(li) && splitline(li)[1] == uppercase(opt)
lines[i] = ";" * li
break # note: only first one found is disabled
end
end
lines
end
function enable!(lines, opt)
for (i, li) in enumerate(lines)
if isdisabled(li)
s = li[2:end]
if splitline(s)[1] == uppercase(opt)
lines[i] = s
break # note: only first one found is enabled
end
end
end
lines
end
function changeparam!(lines, opt, newparam)
for (i, li) in enumerate(lines)
if isenabled(li)
o, p = splitline(li)
if o == opt
lines[i] = o * " " * string(newparam)
break # note: only first one found is changed
end
end
end
lines
end
function activecfg(lines)
cfgdict = Dict()
for li in lines
if isenabled(li)
o, p = splitline(li)
cfgdict[o] = p
end
end
cfgdict
end
const filename = "fruit.cfg"
const cfh = open(filename)
const cfglines = cleansyntax!(readlines(cfh))
close(cfh)
const cfg = activecfg(cfglines)
disable!(cfglines, "NEEDSPEELING")
enable!(cfglines, "SEEDSREMOVED")
changeparam!(cfglines, "NUMBEROFBANANAS", 1024)
if !haskey(cfg, "NUMBEROFSTRAWBERRIES")
push!(cfglines, "NUMBEROFSTRAWBERRIES 62000")
end
cfg["NUMBEROFSTRAWBERRIES"] = 62000
changeparam!(cfglines, "NUMBEROFSTRAWBERRIES", 62000)
const cfw = open(filename, "w")
for li in cfglines
if li != ""
if li == "#=blank line=#"
li = ""
end
write(cfw, li * "\n")
end
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
| #Kotlin | Kotlin | // version 1.2.0
import java.io.File
class ConfigData(
val favouriteFruit: String,
val needsPeeling: Boolean,
val seedsRemoved: Boolean,
val numberOfBananas: Int,
val numberOfStrawberries: Int
)
fun updateConfigFile(fileName: String, cData: ConfigData) {
val inp = File(fileName)
val lines = inp.readLines()
val tempFileName = "temp_$fileName"
val out = File(tempFileName)
val pw = out.printWriter()
var hadFruit = false
var hadPeeling = false
var hadSeeds = false
var hadBananas = false
var hadStrawberries = false
for (line in lines) {
if (line.isEmpty() || line[0] == '#') {
pw.println(line)
continue
}
val ln = line.trimStart(';').trim(' ', '\t').toUpperCase()
if (ln.isEmpty()) continue
if (ln.take(14) == "FAVOURITEFRUIT") {
if (hadFruit) continue
hadFruit = true
pw.println("FAVOURITEFRUIT ${cData.favouriteFruit}")
}
else if (ln.take(12) == "NEEDSPEELING") {
if (hadPeeling) continue
hadPeeling = true
if (cData.needsPeeling)
pw.println("NEEDSPEELING")
else
pw.println("; NEEDSPEELING")
}
else if (ln.take(12) == "SEEDSREMOVED") {
if (hadSeeds) continue
hadSeeds = true
if (cData.seedsRemoved)
pw.println("SEEDSREMOVED")
else
pw.println("; SEEDSREMOVED")
}
else if(ln.take(15) == "NUMBEROFBANANAS") {
if (hadBananas) continue
hadBananas = true
pw.println("NUMBEROFBANANAS ${cData.numberOfBananas}")
}
else if(ln.take(20) == "NUMBEROFSTRAWBERRIES") {
if (hadStrawberries) continue
hadStrawberries = true
pw.println("NUMBEROFSTRAWBERRIES ${cData.numberOfStrawberries}")
}
}
if (!hadFruit) {
pw.println("FAVOURITEFRUIT ${cData.favouriteFruit}")
}
if (!hadPeeling) {
if (cData.needsPeeling)
pw.println("NEEDSPEELING")
else
pw.println("; NEEDSPEELING")
}
if (!hadSeeds) {
if (cData.seedsRemoved)
pw.println("SEEDSREMOVED")
else
pw.println("; SEEDSREMOVED")
}
if (!hadBananas) {
pw.println("NUMBEROFBANANAS ${cData.numberOfBananas}")
}
if (!hadStrawberries) {
pw.println("NUMBEROFSTRAWBERRIES ${cData.numberOfStrawberries}")
}
pw.close()
inp.delete()
out.renameTo(inp)
}
fun main(args: Array<String>) {
val fileName = "config.txt"
val cData = ConfigData("banana", false, true, 1024, 62000)
updateConfigFile(fileName, cData)
} |
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
| #Erlang | Erlang | {ok, [String]} = io:fread("Enter a string: ","~s").
{ok, [Number]} = io:fread("Enter a number: ","~d"). |
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
| #Euphoria | Euphoria | include get.e
sequence s
atom n
s = prompt_string("Enter a string:")
puts(1, s & '\n')
n = prompt_number("Enter a number:",{})
printf(1, "%d", n) |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Java | Java | import javax.swing.*;
public class GetInputSwing {
public static void main(String[] args) throws Exception {
int number = Integer.parseInt(
JOptionPane.showInputDialog ("Enter an Integer"));
String string = JOptionPane.showInputDialog ("Enter a String");
}
} |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #JavaScript | JavaScript | var str = prompt("Enter a string");
var value = 0;
while (value != 75000) {
value = parseInt( prompt("Enter the number 75000") );
} |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #Kotlin | Kotlin | // version 1.1.2
fun utf8Encode(codePoint: Int) = String(intArrayOf(codePoint), 0, 1).toByteArray(Charsets.UTF_8)
fun utf8Decode(bytes: ByteArray) = String(bytes, Charsets.UTF_8).codePointAt(0)
fun main(args: Array<String>) {
val codePoints = intArrayOf(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E)
println("Char Name Unicode UTF-8 Decoded")
for (codePoint in codePoints) {
var n = if(codePoint <= 0xFFFF) 4 else 5
System.out.printf("%-${n}c %-35s U+%05X ", codePoint, Character.getName(codePoint), codePoint)
val bytes = utf8Encode(codePoint)
var s = ""
for (byte in bytes) s += "%02X ".format(byte)
val decoded = utf8Decode(bytes)
n = if(decoded.toInt() <= 0xFFFF) 12 else 11
System.out.printf("%-${n}s %c\n", s, 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.
| #X86-64_Assembly | X86-64 Assembly |
option casemap:none
strlen proto :qword
strncpy proto :qword, :qword, :dword
Query proto :qword, :qword
.data
szstr db "Here am I",0
.code
Query proc Data:qword, len:qword
local d:qword, l:qword, s:dword
mov d, Data
mov l, len
invoke strlen, addr szstr
.if rax <= l
mov s, eax
invoke strncpy, d, addr szstr, s
mov eax, s
mov rax, l
mov dword ptr [rax], ecx
mov rax, 1
ret
.endif
mov rax, 0
ret
Query endp
end
|
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.
| #Zig | Zig | const std = @import("std");
export fn Query(Data: [*c]u8, Length: *usize) callconv(.C) c_int {
const value = "Here I am";
if (Length.* >= value.len) {
@memcpy(@ptrCast([*]u8, Data), value, value.len);
Length.* = value.len;
return 1;
}
return 0;
} |
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
| #Python | Python | import urllib.parse as up # urlparse for Python v2
url = up.urlparse('http://user:[email protected]:8081/path/file.html;params?query1=1#fragment')
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password)
|
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
| #Julia | Julia |
//version 1.0.1
import HTTP.URIs: escapeuri
dcd = "http://foo bar/"
enc = escapeuri(dcd)
println(dcd, " => ", enc)
|
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
| #Kotlin | Kotlin | // version 1.1.2
import java.net.URLEncoder
fun main(args: Array<String>) {
val url = "http://foo bar/"
println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20
} |
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
| #FreeBASIC | FreeBASIC | Dim [Shared] As DataType <i>vble1</i> [, <i>vble2</i>, ...] |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #GAP | GAP | # At top level, global variables are declared when they are assigned, so one only writes
global_var := 1;
# In a function, local variables are declared like this
func := function(n)
local a;
a := n*n;
return n + a;
end;
# One can test whether a variable is assigned
IsBound(global_var);
# true;
# And destroy a variable
Unbind(global_var);
# This works with list elements too
u := [11, 12, , 14];
IsBound(u[4]);
# true
IsBound(u[3]);
# false
Unbind(u[4]); |
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub van_eck {
my($init,$max) = @_;
my(%v,$k);
my @V = my $i = $init;
for (1..$max) {
$k++;
my $t = $v{$i} ? $k - $v{$i} : 0;
$v{$i} = $k;
push @V, $i = $t;
}
@V;
}
for (
['A181391', 0],
['A171911', 1],
['A171912', 2],
['A171913', 3],
['A171914', 4],
['A171915', 5],
['A171916', 6],
['A171917', 7],
['A171918', 8],
) {
my($seq, $start) = @$_;
my @seq = van_eck($start,1000);
say <<~"END";
Van Eck sequence OEIS:$seq; with the first term: $start
First 10 terms: @{[@seq[0 .. 9]]}
Terms 991 through 1000: @{[@seq[990..999]]}
END
} |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Sidef | Sidef | func is_vampire (n) {
return [] if n.ilog10.is_even
var l1 = n.isqrt.ilog10.ipow10
var l2 = n.isqrt
var s = n.digits.sort.join
gather {
n.divisors.each { |d|
d < l1 && next
d > l2 && break
var t = n/d
next if (d%%10 && t%%10)
next if ("#{d}#{t}".sort != s)
take([d, t])
}
}
}
say "First 25 Vampire Numbers:"
with (1) { |i|
for (var n = 1; i <= 25; ++n) {
var fangs = is_vampire(n)
printf("%2d. %6s : %s\n", i++, n, fangs.join(' ')) if fangs
}
}
say "\nIndividual tests:"
[16758243290880, 24959017348650, 14593825548650].each { |n|
var fangs = is_vampire(n)
say "#{n}: #{fangs ? fangs.join(', ') : 'is not a vampire number'}"
} |
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
| #Phixmonti | Phixmonti | def varfunc
1 tolist flatten
len for
get print nl
endfor
enddef
"Mary" "had" "a" "little" "lamb" 5 tolist varfunc |
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
| #PHP | PHP | <?php
function printAll() {
foreach (func_get_args() as $x) // first way
echo "$x\n";
$numargs = func_num_args(); // second way
for ($i = 0; $i < $numargs; $i++)
echo func_get_arg($i), "\n";
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awesome!");
?> |
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
| #Wren | Wren | import "/str" for Char, Str
var vigenere = Fn.new { |text, key, encrypt|
var t = encrypt ? Str.upper(text) : text
var sb = ""
var ki = 0
for (c in t) {
if (Char.isAsciiUpper(c)) {
var ci = encrypt ? (c.bytes[0] + key[ki].bytes[0] - 130) % 26 :
(c.bytes[0] - key[ki].bytes[0] + 26) % 26
sb = sb + Char.fromCode(ci + 65)
ki = (ki + 1) % key.count
}
}
return sb
}
var key = "VIGENERECIPHER"
var text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
var encoded = vigenere.call(text, key, true)
System.print(encoded)
var decoded = vigenere.call(encoded, key, false)
System.print(decoded) |
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
| #FunL | FunL | A = (3, 4, 5)
B = (4, 3, 5)
C = (-5, -12, -13)
def dot( u, v ) = sum( u(i)v(i) | i <- 0:u.>length() )
def cross( u, v ) = (u(1)v(2) - u(2)v(1), u(2)v(0) - u(0)v(2), u(0)v(1) - u(1)v(0) )
def scalarTriple( u, v, w ) = dot( u, cross(v, w) )
def vectorTriple( u, v, w ) = cross( u, cross(v, w) )
println( "A\u00b7B = ${dot(A, B)}" )
println( "A\u00d7B = ${cross(A, B)}" )
println( "A\u00b7(B\u00d7C) = ${scalarTriple(A, B, C)}" )
println( "A\u00d7(B\u00d7C) = ${vectorTriple(A, B, C)}" ) |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Quackery | Quackery | [ 2 split drop do
char A char z 1+ within
swap
char A char z 1+ within
and ] is 2chars ( $ --> b )
[ dup size 12 != iff
[ drop false ] done
dup 2chars not iff
[ drop false ] done
[] swap
witheach
[ 36 base put
char->n
base release
number$ join ]
$->n drop luhn ] is isin ( n --> b )
[ dup echo$
say " is "
isin not if
[ say "not " ]
say "valid." cr ] is task ( n --> )
$ "US0378331005" task
$ "US0373831005" task
$ "U50378331005" task
$ "US03378331005" task
$ "AU0000XVGZA3" task
$ "AU0000VXGZA3" task
$ "FR0000988040" task
|
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
| #Racket | Racket |
#lang racket
;; convert a base36 character (#\0 - #\Z) to its equivalent
;; in base 10 as a string ("0" - "35")
(define (base36-char->base10-string c)
(let ([char-int (char->integer (char-upcase c))]
[zero-int (char->integer #\0)]
[nine-int (char->integer #\9)]
[A-int (char->integer #\A)]
[Z-int (char->integer #\Z)])
(cond [(and (>= char-int zero-int) (<= char-int nine-int)) (~a c)]
[(and (>= char-int A-int) (<= char-int Z-int)) (~a (+ (- char-int A-int) 10))]
[else null])))
;; substitute equivalent base 10 numbers for base 36 characters in string
;; this is a character-by-character substitution not a conversion
;; of a base36 number to a base10 number
(define (base36-string-characters->base10-string-characters s)
(for/fold ([joined ""])
([tenstr (map base36-char->base10-string (string->list (string-upcase s)))])
(values (string-append joined tenstr))))
;; This uses the Racket Luhn solution
(define [isin-test? s]
(let ([RE (pregexp "^[A-Z]{2}[A-Z0-9]{9}[0-9]{1}$")])
(and
(regexp-match? RE s)
(luhn-test (string->number (base36-string-characters->base10-string-characters s))))))
(define test-cases '("US0378331005" "US0373831005" "U50378331005" "US03378331005" "AU0000XVGZA3" "AU0000VXGZA3" "FR0000988040"))
(map isin-test? test-cases)
;; -> '(#t #f #f #f #t #t #t)
|
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
| #Pascal | Pascal | Program VanDerCorput;
{$IFDEF FPC}
{$MODE DELPHI}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
type
tvdrCallback = procedure (nom,denom: NativeInt);
{ Base=2
function rev2(n,Pot:NativeUint):NativeUint;
var
r : Nativeint;
begin
r := 0;
while Pot > 0 do
Begin
r := r shl 1 OR (n AND 1);
n := n shr 1;
dec(Pot);
end;
rev2 := r;
end;
}
function reverse(n,base,Pot:NativeUint):NativeUint;
var
r,c : Nativeint;
begin
r := 0;
//No need to test n> 0 in this special case, n starting in upper half
while Pot > 0 do
Begin
c := n div base;
r := n+(r-c)*base;
n := c;
dec(Pot);
end;
reverse := r;
end;
procedure VanDerCorput(base,count:NativeUint;f:tvdrCallback);
//calculates count nominater and denominater of Van der Corput sequence
// to base
var
Pot,
denom,nom,
i : NativeUint;
Begin
denom := 1;
Pot := 0;
while count > 0 do
Begin
IF Pot = 0 then
f(0,1);
//start in upper half
i := denom;
inc(Pot);
denom := denom *base;
repeat
nom := reverse(i,base,Pot);
IF count > 0 then
f(nom,denom)
else
break;
inc(i);
dec(count);
until i >= denom;
end;
end;
procedure vdrOutPut(nom,denom: NativeInt);
Begin
write(nom,'/',denom,' ');
end;
var
i : NativeUint;
Begin
For i := 2 to 5 do
Begin
write(' Base ',i:2,' :');
VanDerCorput(i,9,@vdrOutPut);
writeln;
end;
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á".
| #Icon_and_Unicon | Icon and Unicon | link hexcvt
procedure main()
ue := "http%3A%2F%2Ffoo%20bar%2F"
ud := decodeURL(ue) | stop("Improperly encoded string ",image(ue))
write("encoded = ",image(ue))
write("decoded = ",image(ue))
end
procedure decodeURL(s) #: decode URL/URI encoded data
static de
initial { # build lookup table for everything
de := table()
every de[hexstring(ord(c := !string(&ascii)),2)] := c
}
c := ""
s ? until pos(0) do # decode every %xx or fail
c ||:= if ="%" then \de[move(2)] | fail
else move(1)
return c
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á".
| #J | J | require'strings convert'
urldecode=: rplc&(~.,/;"_1&a."2(,:tolower)'%',.toupper hfd i.#a.) |
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.
| #Go | Go | package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
// Regular expression to check validity of a barcode and extract digits. However we accept any number
// of spaces at the beginning or end i.e. we don't enforce a minimum of 9.
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool // False by default.
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid { // Contains at least one invalid digit.
if j == 0 { // Try reversing.
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
} |
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
| #Lasso | Lasso | #!/usr/bin/lasso9
define config => type {
data public configtxt, public path
public oncreate(
path::string = 'testing/configuration.txt'
) => {
.configtxt = file(#path) -> readstring
.path = #path
}
public get(term::string) => {
.clean
local(
regexp = regexp(-find = `(?m)^` + #term + `($|\s*=\s*|\s+)(.*)$`, -input = .configtxt, -ignorecase),
result
)
while(#regexp -> find) => {
#result = (#regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim& || true))
if(#result -> asstring >> ',') => {
#result = #result -> split(',')
#result -> foreach => {#1 -> trim}
}
return #result
}
return false
}
public set(term::string, value) => {
if(#value === false) => {
.disable(#term)
return
}
.enable(#term)
if(#value -> isanyof(::string, ::integer, ::decimal)) => {
.configtxt = regexp(-find = `(?m)^(` + #term + `) ?(.*?)$`, -replace = `$1 ` + #value, -input = .configtxt, -ignorecase) -> replaceall
}
}
public disable(term::string) => {
.clean
local(regexp = regexp(-find = `(?m)^(` + #term + `)`, -replace = `; $1`, -input = .configtxt, -ignorecase))
.configtxt = #regexp -> replaceall
}
public enable(term::string, -comment::string = '# Added ' + date) => {
.clean
local(regexp = regexp(-find = `(?m)^(; )?(` + #term + `)`, -replace = `$2`, -input = .configtxt, -ignorecase))
if(#regexp -> find) => {
.configtxt = #regexp -> replaceall
else
.configtxt -> append('\n' + (not #comment -> beginswith('#') ? '# ') +
#comment + '\n' +
string_uppercase(#term) + '\n'
)
}
}
public write => {
local(config = file(.path))
#config -> opentruncate
#config -> dowithclose => {
#config -> writestring(.configtxt)
}
}
public clean => {
local(
cleaned = array,
regexp = regexp(-find = `^(;+)\W*$`)
)
with line in .configtxt -> split('\n') do {
#line -> trim
#regexp -> input = #line
if(#line -> beginswith('#') or #line == '') => {
#cleaned -> insert(#line)
else(not (#regexp -> find))
if(#line -> beginswith(';')) => {
#line -> replace(regexp(`^;+ *`), `; `)
else
#line -> replace(regexp(`^(.*?) +(.*?)`), `$1 $2`)
}
#line -> replace(regexp(`\t`))
#cleaned -> insert(#line)
}
}
.configtxt = #cleaned -> join('\n')
}
} |
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
| #Nim | Nim | import os, re, strutils
let regex = re(r"^(;*)\s*([A-Z0-9]+)\s*([A-Z0-9]*)", {reIgnoreCase, reStudy})
type
EntryType {.pure.} = enum Empty, Enabled, Disabled, Comment, Ignore
Entry = object
etype: EntryType
name: string
value: string
Config = object
entries: seq[Entry]
path: string
# Forward reference.
proc addOption*(config: var Config; name, value: string; etype = Enabled)
proc initConfig*(path: string): Config =
if not path.isValidFilename:
raise newException(IOError, "invalid file name.")
result.path = path
if not path.fileExists: return
for line in path.lines:
var line = line.strip
if line.len == 0:
result.entries.add Entry(etype: Empty)
elif line[0] == '#':
result.entries.add Entry(etype: Comment, value: line)
else:
line = line.replace(re"^a-zA-Z0-9\x20;")
var matches = newSeq[string](3)
if line.match(regex, matches) and matches[1].len != 0:
let etype = if matches[0].len == 0: Enabled else: Disabled
result.addOption(matches[1], matches[2], etype)
proc getOptionIndex(config: Config; name: string): int =
for i, e in config.entries:
if e.etype notin [Enabled, Disabled]: continue
if e.name == name.toUpperAscii:
return i
result = -1
proc enableOption*(config: var Config; name: string) =
let i = config.getOptionIndex(name)
if i >= 0:
config.entries[i].etype = Enabled
proc disableOption*(config: var Config; name: string) =
let i = config.getOptionIndex(name)
if i >= 0:
config.entries[i].etype = Disabled
proc setOption*(config: var Config; name, value: string) =
let i = config.getOptionIndex(name)
if i >= 0:
config.entries[i].value = value
proc addOption*(config: var Config; name, value: string; etype = Enabled) =
config.entries.add Entry(etype: etype, name: name.toUpperAscii, value: value)
proc removeOption*(config: var Config; name: string) =
let i = config.getOptionIndex(name)
if i >= 0:
config.entries[i].etype = Ignore
proc store*(config: Config) =
let f = open(config.path, fmWrite)
for e in config.entries:
case e.etype
of Empty: f.writeLine("")
of Enabled: f.writeLine(e.name, ' ', e.value)
of Disabled: f.writeLine("; ", e.name, ' ', e.value)
of Comment: f.writeLine(e.value)
of Ignore: discard
when isMainModule:
var cfg = initConfig("update_demo.config")
cfg.enableOption("seedsremoved")
cfg.disableOption("needspeeling")
cfg.setOption("numberofbananas", "1024")
cfg.addOption("numberofstrawberries", "62000")
cfg.store() |
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
| #F.23 | F# | open System
let ask_for_input s =
printf "%s (End with Return): " s
Console.ReadLine()
[<EntryPoint>]
let main argv =
ask_for_input "Input a string" |> ignore
ask_for_input "Enter the number 75000" |> ignore
0 |
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
| #Factor | Factor | "Enter a string: " write
readln
"Enter a number: " write
readln string>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
| #Julia | Julia | using Gtk
function twoentrywindow()
txt = "Enter Text Here"
txtchanged = false
win = GtkWindow("Keypress Test", 500, 100) |> (GtkFrame() |> (vbox = GtkBox(:v)))
lab = GtkLabel("Enter some text in the first box and 7500 into the second box.")
txtent = GtkEntry()
set_gtk_property!(txtent,:text,"Enter Some Text Here")
nument = GtkEntry()
set_gtk_property!(nument,:text,"Enter the number seventy-five thousand here")
push!(vbox, lab, txtent, nument)
function keycall(w, event)
strtxt = get_gtk_property(txtent, :text, String)
numtxt = get_gtk_property(nument, :text, String)
if strtxt != txt && occursin("75000", numtxt)
set_gtk_property!(lab, :label, "You have accomplished the task.")
end
end
signal_connect(keycall, win, "key-press-event")
cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
showall(win)
wait(cond)
end
twoentrywindow()
|
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
| #Kotlin | Kotlin | // version 1.1
import javax.swing.JOptionPane
fun main(args: Array<String>) {
do {
val number = JOptionPane.showInputDialog("Enter 75000").toInt()
} while (number != 75000)
} |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #langur | langur | writeln "character Unicode UTF-8 encoding (hex)"
for .cp in "AöЖ€𝄞" {
val .utf8 = s2b cp2s .cp
val .cpstr = b2s .utf8
val .utf8rep = join " ", map f $"\.b:X02;", .utf8
writeln $"\.cpstr:-11; U+\.cp:X04:-8; \.utf8rep;"
} |
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.
| #Lingo | Lingo | chars = ["A", "ö", "Ж", "€", "𝄞"]
put "Character Unicode (int) UTF-8 (hex) Decoded"
repeat with c in chars
ba = bytearray(c)
put col(c, 12) & col(charToNum(c), 16) & col(ba.toHexString(1, ba.length), 14) & ba.readRawString(ba.length)
end repeat |
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.
| #zkl | zkl | // query.c
// export zklRoot=/home/ZKL
// clang query.c -I $zklRoot/VM -L $zklRoot/Lib -lzkl -pthread -lncurses -o query
// LD_LIBRARY_PATH=$zklRoot/Lib ./query
#include <stdio.h>
#include <string.h>
#include "zklObject.h"
#include "zklImports.h"
#include "zklClass.h"
#include "zklFcn.h"
#include "zklString.h"
int query(char *buf, size_t *sz)
{
Instance *r;
pVM vm;
MLIST(mlist,10);
// Bad practice: not protecting things from the garbage collector
// build the call parameters: ("query.zkl",False,False,True)
mlistBuild(mlist,stringCreate("query.zkl",I_OWNED,NoVM),
BoolFalse,BoolFalse,BoolTrue,ZNIL);
// Import is in the Vault, a store of useful stuff
// We want to call TheVault.Import.import("query.zkl",False,False,True)
// which will load/compile/run query.zkl
r = fcnRunith("Import","import",(Instance *)mlist,NoVM);
// query.zkl is a class with a var that has the query result
r = classFindVar(r,"query",0,NoVM); // -->the var contents
strcpy(buf,stringText(r)); // decode the string into a char *
*sz = strlen(buf); // screw overflow checking
return 1;
}
int main(int argc, char* argv[])
{
char buf[100];
size_t sz = sizeof(buf);
zklConstruct(argc,argv); // initialize the zkl shared library
query(buf,&sz);
printf("Query() --> \"%s\"\n",buf);
return 0;
} |
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
| #R | R |
library(urltools)
urls <- c("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 (an_url in urls) {
parsed <- url_parse(an_url)
cat(an_url,"\n")
for (idx in 1:ncol(parsed)) {
if (!is.na(parsed[[idx]])) {
cat(colnames(parsed)[[idx]],"\t:",parsed[[idx]],"\n")
}
}
cat("\n")
}
|
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Ksh | Ksh |
url_encode()
{
printf "%(url)q\n" "$*"
}
url_encode "http://foo bar/"
url_encode "https://ru.wikipedia.org/wiki/Транспайлер"
url_encode "google.com/search?q=`Abdu'l-Bahá"
|
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
| #langur | langur | val .urlEncode = f(.s) replace(
.s, re/[^A-Za-z0-9]/,
f(.s2) for .b in s2b(.s2) { _for ~= $"%\.b:X02;" },
)
val .original = "https://some website.com/"
writeln .original
writeln .urlEncode(.original) |
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
| #GlovePIE | GlovePIE | if var.end=0 then // Without the code being in this if statement, the code would keep executing until it were to stop.
var.end=1
// These variables, respectively, refer to an integer, a boolean, and a string.
var.variable1=3
var.variable2=True
var.variable3="Hi!"
// var.example1 now refers to a string object instead.
var.variable1="Bye!"
endif |
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
| #Go | Go | x := 3 |
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.
| #Phix | Phix | constant lim = 1000
sequence van_eck = repeat(0,lim),
pos_before = repeat(0,lim)
for n=1 to lim-1 do
integer vn = van_eck[n]+1,
prev = pos_before[vn]
if prev!=0 then
van_eck[n+1] = n - prev
end if
pos_before[vn] = n
end for
printf(1,"The first ten terms of the Van Eck sequence are:%v\n",{van_eck[1..10]})
printf(1,"Terms 991 to 1000 of the sequence are:%V\n",{van_eck[991..1000]})
|
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #Picat | Picat | main =>
Limit = 1000,
A = new_array(Limit+1),
bind_vars(A,0),
foreach(N in 1..Limit-1)
M = find_last_of(A[1..N],A[N+1]),
if M > 0 then
A[N+2] := N-M+1
end
end,
println(A[1..10]),
println(A[991..1000]),
nl. |
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
| #Swift | Swift | import Foundation
func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger {
let strN = String(n).sorted()
let fangLength = strN.count / 2
let start = T(pow(10, Double(fangLength - 1)))
let end = T(Double(n).squareRoot())
var fangs = [(T, T)]()
for i in start...end where n % i == 0 {
let quot = n / i
guard i % 10 != 0 || quot % 10 != 0 else {
continue
}
if "\(i)\(quot)".sorted() == strN {
fangs.append((i, quot))
}
}
return fangs
}
var count = 0
var i = 1.0
while count < 25 {
let start = Int(pow(10, i))
let end = start * 10
for num in start...end {
let fangs = vampire(n: num)
guard !fangs.isEmpty else { continue }
count += 1
print("\(num) is a vampire number with fangs: \(fangs)")
guard count != 25 else { break }
}
i += 2
}
for (vamp, fangs) in [16758243290880, 24959017348650, 14593825548650].lazy.map({ ($0, vampire(n: $0)) }) {
if fangs.isEmpty {
print("\(vamp) is not a vampire number")
} else {
print("\(vamp) is a vampire number with fangs: \(fangs)")
}
} |
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
| #Tcl | Tcl | proc factorPairs {n {from 2}} {
set result [list 1 $n]
if {$from<=1} {set from 2}
for {set i $from} {$i<=sqrt($n)} {incr i} {
if {$n%$i} {} {lappend result $i [expr {$n/$i}]}
}
return $result
}
proc vampireFactors {n} {
if {[string length $n]%2} return
set half [expr {[string length $n]/2}]
set digits [lsort [split $n ""]]
set result {}
foreach {a b} [factorPairs $n [expr {10**$half/10}]] {
if {
[string length $a]==$half && [string length $b]==$half &&
($a%10 || $b%10) && $digits eq [lsort [split $a$b ""]]
} then {
lappend result [list $a $b]
}
}
return $result
} |
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
| #PicoLisp | PicoLisp | (de varargs @
(while (args)
(println (next)) ) ) |
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
| #PL.2FI | PL/I | /* PL/I permits optional arguments, but not an infinitely varying */
/* argument list: */
s: procedure (a, b, c, d);
declare (a, b, c, d) float optional;
if ^omitted(a) then put skip list (a);
if ^omitted(b) then put skip list (b);
if ^omitted(c) then put skip list (c);
if ^omitted(d) then put skip list (d);
end s; |
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
| #XPL0 | XPL0 | code ChIn=7, ChOut=8;
int Neg, C, Len, I, Key;
char KeyWord(80);
[Neg:= false; \skip to KEYWORD
repeat C:= ChIn(8); if C=^- then Neg:= true; until C>=^A & C<=^Z;
Len:= 0; \read in KEYWORD
repeat KeyWord(Len):= C-^A; Len:= Len+1; C:= ChIn(8); until C<^A ! C>^Z;
I:= 0; \initialize cycling index
repeat C:= ChIn(1);
if C>=^a & C<=^z then C:= C-$20; \capitalize
if C>=^A & C<=^Z then \discard non-alphas
[Key:= KeyWord(I); I:= I+1; if I>=Len then I:= 0;
if Neg then Key:= -Key; \decrypting?
C:= C+Key;
if C>^Z then C:= C-26
else if C<^A then C:= C+26;
ChOut(0, C);
];
until C=$1A; \EOF
ChOut(0, $1A); \encrypted file must end with EOF otherwise the decode will hang
] |
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
| #zkl | zkl | fcn encipher(src,key,is_encode){
upperCase:=["A".."Z"].pump(String);
src=src.toUpper().inCommon(upperCase); // only uppercase
key=key.toUpper().inCommon(upperCase).pump(List,"toAsc");
const A="A".toAsc();
klen:=Walker.cycle(key.len()); // 0,1,2,3,..,keyLen-1,0,1,2,3, ...
src.pump(String,'wrap(c){ i:=klen.next(); c=c.toAsc();
(A + ( if(is_encode) c - A + key[i] - A;
else c - key[i] + 26 ) % 26).toChar()
});
} |
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
| #GAP | GAP | DotProduct := function(u, v)
return u*v;
end;
CrossProduct := function(u, v)
return [
u[2]*v[3] - u[3]*v[2],
u[3]*v[1] - u[1]*v[3],
u[1]*v[2] - u[2]*v[1] ];
end;
ScalarTripleProduct := function(u, v, w)
return DotProduct(u, CrossProduct(v, w));
end;
VectorTripleProduct := function(u, v, w)
return CrossProduct(u, CrossProduct(v, w));
end;
a := [3, 4, 5];
b := [4, 3, 5];
c := [-5, -12, -13];
DotProduct(a, b);
# 49
CrossProduct(a, b);
# [ 5, 5, -7 ]
ScalarTripleProduct(a, b, c);
# 6
# Another way to get it
Determinant([a, b, c]);
# 6
VectorTripleProduct(a, b, c);
# [ -267, 204, -3 ] |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Raku | Raku | my $ISIN = /
^ <[A..Z]>**2 <[A..Z0..9]>**9 <[0..9]> $
<?{ luhn-test $/.comb.map({ :36($_) }).join }>
/;
sub luhn-test ($number --> Bool) {
my @digits = $number.comb.reverse;
my $sum = @digits[0,2...*].sum
+ @digits[1,3...*].map({ |($_ * 2).comb }).sum;
return $sum %% 10;
}
# Testing:
say "$_ is { m/$ISIN/ ?? "valid" !! "not valid"}" for <
US0378331005
US0373831005
U50378331005
US03378331005
AU0000XVGZA3
AU0000VXGZA3
FR0000988040
>; |
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
| #Perl | Perl | sub vdc {
my @value = shift;
my $base = shift // 2;
use integer;
push @value, $value[-1] / $base while $value[-1] > 0;
my ($x, $sum) = (1, 0);
no integer;
$sum += ($_ % $base) / ($x *= $base) for @value;
return $sum;
}
for my $base ( 2 .. 5 ) {
print "base $base: ", join ' ', map { vdc($_, $base) } 0 .. 10;
print "\n";
} |
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á".
| #Java | Java | import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String encoded = "http%3A%2F%2Ffoo%20bar%2F";
String normal = URLDecoder.decode(encoded, "utf-8");
System.out.println(normal);
}
} |
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á".
| #JavaScript | JavaScript | decodeURIComponent("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.
| #J | J | upcdigit=:".;._2]0 :0
0 0 0 1 1 0 1 NB. 0
0 0 1 1 0 0 1 NB. 1
0 0 1 0 0 1 1 NB. 2
0 1 1 1 1 0 1 NB. 3
0 1 0 0 0 1 1 NB. 4
0 1 1 0 0 0 1 NB. 5
0 1 0 1 1 1 1 NB. 6
0 1 1 1 0 1 1 NB. 7
0 1 1 0 1 1 1 NB. 8
0 0 0 1 0 1 1 NB. 9
)
upc2dec=:3 :0
if. 95~: #code=. '#'=dtb dlb y do._ return.end.
if. (11$1 0) ~: 0 1 2 45 46 47 48 49 92 93 94{ code do._ return. end.
digits=. <./([:,upcdigit i.0 1~:(3 50+/i.6 7) { ])"1 code,:|.code
if. 10 e.digits do._ return.end.
if.0 ~:10|digits+/ .* 12$3 1 do._ return.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
| #Perl | Perl | use warnings;
use strict;
my $needspeeling = 0;
my $seedsremoved = 1;
my $numberofstrawberries = 62000;
my $numberofbananas = 1024;
my $favouritefruit = 'bananas';
my @out;
sub config {
my (@config) = <DATA>;
push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n"
unless grep { /^;*[ \t]*NUMBEROFSTRAWBERRIES\b/; } @config;
foreach my $line (@config) {
if (substr($line, 0, 1) eq '#') {
push @out, $line;
next;
}
next if $line =~ /^[;\t ]+$/;
my ($option, $option_name);
if ($line =~ /^([A-Z]+[0-9]*)/) {
$option_name = lc $1;
$option = eval "\\\$$option_name";
my $value = eval "\${$option_name}";
if ($value) {
$$option = $value;
}
else {
$line = '; ' . $line;
$$option = undef;
}
}
elsif ($line =~ /^;+\s*([A-Z]+[0-9]*)/) {
$option_name = lc $1;
$option = eval "\\\$$option_name";
my $value = eval "\${$option_name}";
if ($value) {
$line =~ s/^;+\s*//;
$$option = $value == 1 ? '' : $value;
}
else {
$$option = undef;
}
}
if (defined $$option) {
push @out, "\U$option_name\E $$option\n"
unless grep { /^\U$option_name\E\b/; } @out;
}
else {
$line =~ s/\s*[^[:ascii:]]+\s*$//;
$line =~ s/[[:cntrl:]\s]+$//;
push(@out, "$line\n");
}
}
}
config();
my $file = join('', @out);
$file =~ s/\n{3,}/\n\n/g;
print $file;
__DATA__
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.
# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# How many bananas we have
NUMBEROFBANANAS 48 |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Falcon | Falcon | printl("Enter a string:")
str = input()
printl("Enter a number:")
n = int(input()) |
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
| #FALSE | FALSE | [[^$' =~][,]#,]w:
[0[^'0-$$9>0@>|~][\10*+]#%]d:
w;! d;!. |
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
| #LabVIEW | LabVIEW | ' [RC] User input/graphical
' Typical LB graphical input/output example.This shows how LB takes user input.
' You'd usually do more validating of input.
nomainwin ' No console window needed.
textbox#w.tb1, 100, 20, 200, 30
textbox#w.tb2, 100, 60, 200, 30
textbox#w.tb3, 100,160, 200, 30
statictext #w.st1, "String =", 10, 30, 90, 30
statictext #w.st2, "Integer =", 10, 70, 90, 30
button #w.b1, "Read and Show", [buttonClicked], LR, 180, 70
WindowWidth =360
WindowHeight =240
UpperLeftX = 40
UpperLeftY = 40
open "User input of integer & string" for window as #w
#w "trapclose [quit]" ' Clean exit routine.
#w.tb1 "!font courier 12"
#w.tb2 "!font courier 12"
#w.tb3 "!font courier 12 bold"
#w.st1 "!font courier 12"
#w.st2 "!font courier 12"
#w.tb1 "Change this string."
#w.tb2 "Enter an integer here."
#w.tb3 "Display will be here."
#w.tb1 "!selectall"
wait
[buttonClicked] ' Button-clicked routine collects data
#w.tb1 "!contents? in1$"
#w.tb2 "!contents? in2$"
#w.tb3 in1$; " "; int( val( in2$))
wait
[quit]
close #w
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.
| #Lua | Lua |
-- Accept an integer representing a codepoint.
-- Return the values of the individual octets.
function encode (codepoint)
local codepoint_str = utf8.char(codepoint)
local result = {}
for i = 1, #codepoint_str do
result[#result + 1] = string.unpack("B", codepoint_str, i)
end
return table.unpack(result)
end
-- Accept a variable number of octets.
-- Return the corresponding Unicode character.
function decode (...)
local len = select("#", ...) -- the number of octets
local fmt = string.rep("B", len)
return string.pack(fmt, ...)
end
-- Run the given test cases.
function test_encode_decode ()
-- "A", "ö", "Ж", "€", "𝄞"
local tests = {tonumber("41", 16), tonumber("f6", 16), tonumber("416", 16),
tonumber("20ac", 16), tonumber("1d11e", 16)}
for i, test in ipairs(tests) do
print("Char: ", test)
print("Encoding: ", encode(test))
print("Decoding: ", decode(encode(test)))
end
end
|
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
| #Racket | Racket | #lang racket/base
(require racket/match net/url)
(define (debug-url-string U)
(match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U))
(printf "URL: ~s~%" U)
(printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-))
(when #t (printf "scheme: ~s~%" s))
(when u (printf "user: ~s~%" u))
(when h (printf "host: ~s~%" h))
(when p (printf "port: ~s~%" p))
;; From documentation link in text:
;; > For Unix paths, the root directory is not included in `path';
;; > its presence or absence is implicit in the path-absolute? flag.
(printf "path-absolute?: ~s~%" pa?)
(printf "path bits: ~s~%" pas)
;; prms will often be a list of lists. this will print iff
;; one of the inner lists is not null
(when (memf pair? prms)
(printf "param bits: ~s [interleaved with path bits]~%" prms))
(unless (null? q) (printf "query: ~s~%" q))
(when f (printf "fragment: ~s~%" f))
(newline))
(for-each
debug-url-string
'("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://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
| #Raku | Raku | use URI;
my @test-uris = <
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
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
>;
my $u = URI.new;
for @test-uris -> $uri {
say "URI:\t", $uri;
$u.parse($uri);
for <scheme host port path query frag> -> $t {
my $token = try {$u."$t"()} || '';
say "$t:\t", $token if $token;
}
say '';
} |
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
| #Lasso | Lasso | bytes('http://foo bar/') -> encodeurl |
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
| #Liberty_BASIC | Liberty BASIC |
dim lookUp$( 256)
for i =0 to 256
lookUp$( i) ="%" +dechex$( i)
next i
string$ ="http://foo bar/"
print "Supplied string '"; string$; "'"
print "As URL '"; url$( string$); "'"
end
function url$( i$)
for j =1 to len( i$)
c$ =mid$( i$, j, 1)
if instr( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", c$) then
url$ =url$ +c$
else
url$ =url$ +lookUp$( asc( c$))
end if
next j
end function
|
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
| #Haskell | Haskell | foobar = 15
f x = x + foobar
where foobar = 15
f x = let foobar = 15
in x + foobar
f x = do
let foobar = 15
return $ x + foobar |
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
| #HicEst | HicEst | ! Strings and arrays must be declared.
! Everything else is 8-byte float, READ/WRITE converts
CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/
REAL, PARAMETER :: named_constant = 3.1415
REAL :: n=2, cols=4, vec(cols), mtx(n, cols)
DATA vec/2,3,4,5/, mtx/1,2,3.1415,4, 5,6,7,8/
named = ALIAS(alpha, beta, gamma) ! gamma == named(3)
ALIAS(vec,n, subvec,2) ! share subvec and vec(n...n+1)
ALIAS(str,3, substr,n) ! share substr and str(3:3+n-1)
a = EXP(b + c) ! assign/initialze a=1, b=0, c=0
str = "blahblah" ! truncate/expand if needed
beta = "blahblah" ! illegal
CALL noArguments_noUSE ! global scope SUBROUTINE
CALL Arguments_or_USE(a) ! local scope SUBROUTINE
t = func() ! local scope FUNCTION
SUBROUTINE noArguments_noUSE() ! all global
vec2 = $ ! 1,2,3,...
END
SUBROUTINE Arguments_or_USE(var) ! all local
USE : vec ! use global object
var = SUM(vec)
t = TIME() ! local, static, USEd by func()
END
FUNCTION func() ! all local
USE Arguments_or_USE : t ! use local object
func = t
END |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
PRINT$SLICE: PROCEDURE (LIST, N);
DECLARE (I, N, LIST, L BASED LIST) ADDRESS;
DO I=0 TO N-1;
CALL PRINT$NUMBER(L(I));
END;
CALL PRINT(.(13,10,'$'));
END PRINT$SLICE;
DECLARE ECK (1000) ADDRESS;
DECLARE (I, J) ADDRESS;
ECK(0) = 0;
DO I=0 TO LAST(ECK)-1;
J = I - 1;
DO WHILE J <> 0FFFFH; /* WHAT IS SIGNED MATH */
IF ECK(I) = ECK(J) THEN DO;
ECK(I+1) = I-J;
GO TO NEXT;
END;
J = J - 1;
END;
ECK(I+1) = 0;
NEXT:
END;
CALL PRINT$SLICE(.ECK(0), 10);
CALL PRINT$SLICE(.ECK(990), 10);
CALL EXIT;
EOF |
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.
| #Prolog | Prolog | van_eck_init(v(0, 0, _assoc)):-
empty_assoc(_assoc).
van_eck_next(v(Index, Last_term, Last_pos), v(Index1, Next_term, Last_pos1)):-
(get_assoc(Last_term, Last_pos, V) ->
Next_term is Index - V
;
Next_term = 0
),
Index1 is Index + 1,
put_assoc(Last_term, Last_pos, Index, Last_pos1).
van_eck_sequence(N, Seq):-
van_eck_init(V),
van_eck_sequence(N, V, Seq).
van_eck_sequence(0, _, []):-!.
van_eck_sequence(N, V, [Term|Rest]):-
V = v(_, Term, _),
van_eck_next(V, V1),
N1 is N - 1,
van_eck_sequence(N1, V1, Rest).
write_list(From, To, _, _):-
To < From,
!.
write_list(_, _, _, []):-!.
write_list(From, To, N, [_|Rest]):-
From > N,
!,
N1 is N + 1,
write_list(From, To, N1, Rest).
write_list(From, To, N, [E|Rest]):-
writef('%t ', [E]),
F1 is From + 1,
N1 is N + 1,
write_list(F1, To, N1, Rest).
write_list(From, To, List):-
write_list(From, To, 1, List),
nl.
main:-
van_eck_sequence(1000, Seq),
writeln('First 10 terms of the Van Eck sequence:'),
write_list(1, 10, Seq),
writeln('Terms 991 to 1000 of the Van Eck sequence:'),
write_list(991, 1000, Seq). |
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
| #Vlang | Vlang | import math
fn max(a u64, b u64) u64 {
if a > b {
return a
}
return b
}
fn min(a u64, b u64) u64 {
if a < b {
return a
}
return b
}
fn ndigits(xx u64) int {
mut n:=0
mut x := xx
for ; x > 0; x /= 10 {
n++
}
return n
}
fn dtally(xx u64) u64 {
mut t := u64(0)
mut x := xx
for ; x > 0; x /= 10 {
t += 1 << (x % 10 * 6)
}
return t
}
__global (
tens [20]u64
)
fn init() {
tens[0] = 1
for i := 1; i < 20; i++ {
tens[i] = tens[i-1] * 10
}
}
fn fangs(x u64) []u64 {
mut f := []u64{}
mut nd := ndigits(x)
if nd&1 == 1 {
return f
}
nd /= 2
lo := max(tens[nd-1], (x+tens[nd]-2)/(tens[nd]-1))
hi := min(x/lo, u64(math.sqrt(f64(x))))
t := dtally(x)
for a := lo; a <= hi; a++ {
b := x / a
if a*b == x &&
(a%10 > 0 || b%10 > 0) &&
t == dtally(a)+dtally(b) {
f << a
}
}
return f
}
fn show_fangs(x u64, f []u64) {
print(x)
if f.len > 1 {
println('')
}
for a in f {
println(" = $a × ${x/a}")
}
}
fn main() {
for x, n := u64(1), 0; n < 26; x++ {
f := fangs(x)
if f.len > 0 {
n++
print("${n:2}: ")
show_fangs(x, f)
}
}
println('')
for x in [u64(16758243290880), 24959017348650, 14593825548650] {
f := fangs(x)
if f.len > 0 {
show_fangs(x, f)
} else {
println("$x is not vampiric")
}
}
} |
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
| #Wren | Wren | import "/fmt" for Fmt
var ndigits = Fn.new { |x|
var n = 0
while (x > 0) {
n = n + 1
x = (x/10).floor
}
return n
}
var dtally = Fn.new { |x|
var t = 0
while (x > 0) {
t = t + 2.pow((x%10) * 6)
x = (x/10).floor
}
return t
}
var tens = List.filled(15, 0)
var init = Fn.new {
tens[0] = 1
for (i in 1..14) tens[i] = tens[i-1] * 10
}
var fangs = Fn.new { |x|
var f = []
var nd = ndigits.call(x)
if ((nd&1) == 1) return f
nd = (nd/2).floor
var lo = tens[nd-1].max(((x + tens[nd] - 2) / (tens[nd] - 1)).floor)
var hi = (x/lo).floor.min(x.sqrt.floor)
var t = dtally.call(x)
var a = lo
while (a <= hi) {
var b = (x/a).floor
if (a*b == x && ((a%10) > 0 || (b%10) > 0) && t == dtally.call(a) + dtally.call(b)) {
f.add(a)
}
a = a + 1
}
return f
}
var showFangs = Fn.new { |x, f|
Fmt.write("$6d", x)
if (f.count > 1) System.print()
for (a in f) Fmt.print(" = $3d x $3d", a, (x/a).floor)
}
init.call()
var x = 1
var n = 0
while (n < 25) {
var f = fangs.call(x)
if (f.count > 0) {
n = n + 1
Fmt.write("$2d: ", n)
showFangs.call(x, f)
}
x = x + 1
}
System.print()
for (x in [16758243290880, 24959017348650, 14593825548650]) {
var f = fangs.call(x)
if (f.count > 0) {
showFangs.call(x, f)
} else {
Fmt.print("$d is not vampiric", 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
| #PowerShell | PowerShell | function print_all {
foreach ($x in $args) {
Write-Host $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
| #Prolog | Prolog | ?- write( (1) ), nl.
1
?- write( (1,2,3) ), nl.
1,2,3
|
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
| #GLSL | GLSL |
vec3 a = vec3(3, 4, 5),b = vec3(4, 3, 5),c = vec3(-5, -12, -13);
float dotProduct(vec3 a, vec3 b)
{
return a.x*b.x+a.y*b.y+a.z*b.z;
}
vec3 crossProduct(vec3 a,vec3 b)
{
vec3 c = vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y- a.y*b.x);
return c;
}
float scalarTripleProduct(vec3 a,vec3 b,vec3 c)
{
return dotProduct(a,crossProduct(b,c));
}
vec3 vectorTripleProduct(vec3 a,vec3 b,vec3 c)
{
return crossProduct(a,crossProduct(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
| #REXX | REXX | /*REXX program validates the checksum digit for an International Securities ID number.*/
parse arg z /*obtain optional ISINs from the C.L.*/
if z='' then z= "US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3" ,
'AU0000VXGZA3 FR0000988040' /* [↑] use the default list of ISINs.*/
/* [↓] process all specified ISINs.*/
do n=1 for words(z); x=word(z, n); y= x /*obtain an ISIN from the Z list. */
$= /* [↓] construct list of ISIN digits. */
do k=1 for length(x); _= substr(x,k,1) /*the ISIN may contain alphabetic chars*/
p= pos(_, 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) /*X must contain A──►Z, 0──►9.*/
if p==0 then y= /*trigger "not" valid below.*/
else $= $ || p-1 /*convert X string (base 36 ──► dec).*/
end /*k*/ /* [↑] convert alphabetic ──► digits.*/
@= /*placeholder for the "not" in message.*/
if length(y)\==12 then @= "not" /*see if the ISIN is exactly 12 chars. */
if \datatype( left(x,2),'U') then @= "not" /* " " " " 1st 2 chars cap. let.*/
if \datatype(right(x,1),'W') then @= "not" /* " " " " last char not a digit*/
if @=='' then if \luhn($) then @= "not" /* " " " " passed the Luhn test.*/
say right(x, 30) right(@, 5) "valid" /*display the yea or nay message.*/
end /*n*/ /* [↑] 1st 3 IFs could've been combined*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Luhn: procedure; parse arg x; $= 0 /*get credit card number; zero $ sum. */
y= reverse( left(0, length(x) // 2)x) /*add leading zero if needed, & reverse*/
do j=1 to length(y)-1 by 2; _= 2 * substr(y, j+1, 1)
$= $ + substr(y, j, 1) + left(_, 1) + substr(_, 2 , 1, 0)
end /*j*/ /* [↑] sum the odd and even digits.*/
return right($, 1)==0 /*return "1" if number passed Luhn test*/ |
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
| #Phix | Phix | enum BASE, FRAC, DECIMAL
constant DESC = {"Base","Fraction","Decimal"}
function vdc(integer n, atom base, integer flag)
object res = ""
atom num = 0, denom = 1, digit, g
while n do
denom *= base
digit = remainder(n,base)
n = floor(n/base)
if flag=BASE then
res &= digit+'0'
else
num = num*base+digit
end if
end while
if flag=FRAC then
g = gcd(num,denom)
return {num/g,denom/g}
elsif flag=DECIMAL then
return num/denom
end if
return {iff(length(res)=0?"0":"0."&res)}
end function
procedure show_vdc(integer flag, string fmt)
object v
for i=2 to 5 do
printf(1,"%s %d: ",{DESC[flag],i})
for j=0 to 9 do
v = vdc(j,i,flag)
if flag=FRAC and v[1]=0 then
printf(1,"0 ")
else
printf(1,fmt,v)
end if
end for
puts(1,"\n")
end for
end procedure
show_vdc(BASE,"%s ")
show_vdc(FRAC,"%d/%d ")
show_vdc(DECIMAL,"%g ")
|
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á".
| #jq | jq | # Emit . and stop as soon as "condition" is true.
def until(condition; next):
def u: if condition then . else (next|u) end;
u;
def url_decode:
# The helper function converts the input string written in the given
# "base" to an integer
def to_i(base):
explode
| reverse
| map(if 65 <= . and . <= 90 then . + 32 else . end) # downcase
| map(if . > 96 then . - 87 else . - 48 end) # "a" ~ 97 => 10 ~ 87
| reduce .[] as $c
# base: [power, ans]
([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)]) | .[1];
. as $in
| length as $length
| [0, ""] # i, answer
| until ( .[0] >= $length;
.[0] as $i
| if $in[$i:$i+1] == "%"
then [ $i + 3, .[1] + ([$in[$i+1:$i+3] | to_i(16)] | implode) ]
else [ $i + 1, .[1] + $in[$i:$i+1] ]
end)
| .[1]; # answer |
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á".
| #Julia | Julia |
using URIParser
enc = "http%3A%2F%2Ffoo%20bar%2F"
dcd = unescape(enc)
println(enc, " => ", dcd)
|
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.
| #Java | Java | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
} |
http://rosettacode.org/wiki/Update_a_configuration_file | Update a configuration file | We have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.
# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# How many bananas we have
NUMBEROFBANANAS 48
The task is to manipulate the configuration file as follows:
Disable the needspeeling option (using a semicolon prefix)
Enable the seedsremoved option by removing the semicolon and any leading whitespace
Change the numberofbananas parameter to 1024
Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000
Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case.
Options should always be disabled by prefixing them with a semicolon.
Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file.
If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry.
For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.)
The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons).
Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single
space, and any non-ASCII extended characters, tabs characters, or control codes
(other than end of line markers), should also be removed.
Related tasks
Read a configuration file
| #Phix | Phix | integer fn = open("RCTEST.INI","r")
sequence lines = get_text(fn,GT_LF_STRIPPED)
close(fn)
constant dini = new_dict()
for i=1 to length(lines) do
string li = trim(lines[i])
if length(li)
and not find(li[1],"#;") then
integer k = find(' ',li)
if k!=0 then
string rest = li[k+1..$]
li = upper(li[1..k-1])
putd(li,rest,dini)
else
putd(upper(li),1,dini)
end if
end if
end for
deld("NEEDSPEELING",dini)
setd("SEEDSREMOVED",1,dini)
setd("NUMBEROFBANANAS",1024,dini)
setd("NUMBEROFSTRAWBERRIES",62000,dini)
for i=1 to length(lines) do
string li = trim(lines[i])
if length(li)
and li[1]!='#' then
if li[1]=';' then
li = trim(li[2..$])
end if
integer k = find(' ',li)
if k!=0 then
string rest = li[k+1..$]
li = upper(li[1..k-1])
k = getd_index(li,dini)
if k=0 then
lines[i] = "; "&li&" "&rest
else
object o = getd_by_index(k,dini)
if not string(o) then o = sprint(o) end if
lines[i] = li&" "&o
deld(li,dini)
end if
else
if getd(li,dini) then
lines[i] = li
deld(li,dini)
else
lines[i] = "; "&li
end if
end if
end if
end for
function visitor(object key, object data, object /*user_data*/)
lines = append(lines,key&" "&sprint(data))
return 1
end function
traverse_dict(routine_id("visitor"),0,dini)
fn = open("RCTEST.INI","w")
puts(fn,join(lines,"\n"))
close(fn)
|
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
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
Env.cur.out.print ("Enter a string: ").flush
str := Env.cur.in.readLine
echo ("Entered :$str:")
Env.cur.out.print ("Enter 75000: ").flush
Int n
try n = Env.cur.in.readLine.toInt
catch (Err e)
{
echo ("You had to enter a number")
return
}
echo ("Entered :$n: which is " + ((n == 75000) ? "correct" : "wrong"))
}
}
|
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
| #Forth | Forth | : INPUT$ ( n -- addr n )
PAD SWAP ACCEPT
PAD SWAP ; |
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
| #Liberty_BASIC | Liberty BASIC | ' [RC] User input/graphical
' Typical LB graphical input/output example.This shows how LB takes user input.
' You'd usually do more validating of input.
nomainwin ' No console window needed.
textbox#w.tb1, 100, 20, 200, 30
textbox#w.tb2, 100, 60, 200, 30
textbox#w.tb3, 100,160, 200, 30
statictext #w.st1, "String =", 10, 30, 90, 30
statictext #w.st2, "Integer =", 10, 70, 90, 30
button #w.b1, "Read and Show", [buttonClicked], LR, 180, 70
WindowWidth =360
WindowHeight =240
UpperLeftX = 40
UpperLeftY = 40
open "User input of integer & string" for window as #w
#w "trapclose [quit]" ' Clean exit routine.
#w.tb1 "!font courier 12"
#w.tb2 "!font courier 12"
#w.tb3 "!font courier 12 bold"
#w.st1 "!font courier 12"
#w.st2 "!font courier 12"
#w.tb1 "Change this string."
#w.tb2 "Enter an integer here."
#w.tb3 "Display will be here."
#w.tb1 "!selectall"
wait
[buttonClicked] ' Button-clicked routine collects data
#w.tb1 "!contents? in1$"
#w.tb2 "!contents? in2$"
#w.tb3 in1$; " "; int( val( in2$))
wait
[quit]
close #w
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.
| #M2000_Interpreter | M2000 Interpreter |
Module EncodeDecodeUTF8 {
a$=string$("Hello" as UTF8enc)
Print Len(A$)=2.5 ' 2.5 words=5 bytes
b$=string$(a$ as UTF8dec)
Print b$
Print Len(b$)=5 ' 5 words = 10 bytes
Print Len(string$("A" as UTF8enc))=.5 ' 1 byte
Print Len(string$("ö" as UTF8enc))=1 ' 2 bytes
Print Len(string$("Ж" as UTF8enc))=1 ' 2 bytes
Print Len(string$("€" as UTF8enc))=1.5 ' 3 bytes
Print Len(string$("𝄞" as UTF8enc))=2 '4 bytes
a$=string$("𝄞" as UTF8enc)
Buffer Bytes as Byte*4
Return Bytes, 0:=a$
\\ F0 9D 84 9E
Hex Eval(bytes, 0), Eval(bytes, 1), Eval(bytes, 2), Eval(bytes, 3)
}
EncodeDecodeUTF8
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | utf = ToCharacterCode[ToString["AöЖ€", CharacterEncoding -> "UTF8"]]
ToCharacterCode[FromCharacterCode[utf, "UTF8"]] |
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
| #Ruby | Ruby | require 'uri'
test_cases = [
"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"
]
class URI::Generic; alias_method :domain, :host; end
test_cases.each do |test_case|
puts test_case
uri = URI.parse(test_case)
%w[ scheme domain port path query fragment user password ].each do |attr|
puts " #{attr.rjust(8)} = #{uri.send(attr)}" if uri.send(attr)
end
end |
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
| #Rust | Rust | use url::Url;
fn print_fields(url: Url) -> () {
println!("scheme: {}", url.scheme());
println!("username: {}", url.username());
if let Some(password) = url.password() {
println!("password: {}", password);
}
if let Some(domain) = url.domain() {
println!("domain: {}", domain);
}
if let Some(port) = url.port() {
println!("port: {}", port);
}
println!("path: {}", url.path());
if let Some(query) = url.query() {
println!("query: {}", query);
}
if let Some(fragment) = url.fragment() {
println!("fragment: {}", fragment);
}
}
fn main() {
let urls = vec![
"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 {
println!("Parsing {}", url);
match Url::parse(url) {
Ok(valid_url) => {
print_fields(valid_url);
println!();
}
Err(e) => println!("Error Parsing url - {:?}", e),
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.