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/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
| #Factor | Factor | USING: arrays io locals math prettyprint sequences ;
: dot-product ( a b -- dp ) [ * ] 2map sum ;
:: cross-product ( a b -- cp )
a first :> a1 a second :> a2 a third :> a3
b first :> b1 b second :> b2 b third :> b3
a2 b3 * a3 b2 * - ! X
a3 b1 * a1 b3 * - ! Y
a1 b2 * a2 b1 * - ! Z
3array ;
: scalar-triple-product ( a b c -- stp )
cross-product dot-product ;
: vector-triple-product ( a b c -- vtp )
cross-product cross-product ;
[let
{ 3 4 5 } :> a
{ 4 3 5 } :> b
{ -5 -12 -13 } :> c
"a: " write a .
"b: " write b .
"c: " write c . nl
"a . b: " write a b dot-product .
"a x b: " write a b cross-product .
"a . (b x c): " write a b c scalar-triple-product .
"a x (b x c): " write a b c vector-triple-product .
] |
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
| #Perl | Perl | use strict;
use English;
use POSIX;
use Test::Simple tests => 7;
ok( validate_isin('US0378331005'), 'Test 1');
ok( ! validate_isin('US0373831005'), 'Test 2');
ok( ! validate_isin('U50378331005'), 'Test 3');
ok( ! validate_isin('US03378331005'), 'Test 4');
ok( validate_isin('AU0000XVGZA3'), 'Test 5');
ok( validate_isin('AU0000VXGZA3'), 'Test 6');
ok( validate_isin('FR0000988040'), 'Test 7');
exit 0;
sub validate_isin {
my $isin = shift;
$isin =~ /\A[A-Z]{2}[A-Z\d]{9}\d\z/s or return 0;
my $base10 = join(q{}, map {scalar(POSIX::strtol($ARG, 36))}
split(//s, $isin));
return luhn_test($base10);
} |
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
| #Julia | Julia | using Printf
vandercorput(num::Integer, base::Integer) = sum(d * Float64(base) ^ -ex for (ex, d) in enumerate(digits(num, base = base)))
for base in 2:9
@printf("%10s %i:", "Base", base)
for num in 0:9 @printf("%7.3f", vandercorput(num, base)) end
println(" [...]")
end |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Kotlin | Kotlin | // version 1.1.2
data class Rational(val num: Int, val denom: Int)
fun vdc(n: Int, base: Int): Rational {
var p = 0
var q = 1
var nn = n
while (nn != 0) {
p = p * base + nn % base
q *= base
nn /= base
}
val num = p
val denom = q
while (p != 0) {
nn = p
p = q % p
q = nn
}
return Rational(num / q, denom / q)
}
fun main(args: Array<String>) {
for (b in 2..5) {
print("base $b:")
for (i in 0..9) {
val(num, denom) = vdc(i, b)
if (num != 0) print(" $num/$denom")
else print(" 0")
}
println()
}
} |
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á".
| #Erlang | Erlang | 34> http_uri: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á".
| #F.23 | F# | open System
let decode uri = Uri.UnescapeDataString(uri)
[<EntryPoint>]
let main argv =
printfn "%s" (decode "http%3A%2F%2Ffoo%20bar%2F")
0 |
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.
| #AWK | AWK |
# syntax: GAWK -f UPC.AWK
BEGIN {
ls_arr[" ## #"] = 0
ls_arr[" ## #"] = 1
ls_arr[" # ##"] = 2
ls_arr[" #### #"] = 3
ls_arr[" # ##"] = 4
ls_arr[" ## #"] = 5
ls_arr[" # ####"] = 6
ls_arr[" ### ##"] = 7
ls_arr[" ## ###"] = 8
ls_arr[" # ##"] = 9
for (i in ls_arr) {
tmp = i
gsub(/#/,"x",tmp)
gsub(/ /,"#",tmp)
gsub(/x/," ",tmp)
rs_arr[tmp] = ls_arr[i]
}
split("3,1,3,1,3,1,3,1,3,1,3,1",weight_arr,",")
bc_arr[++n] = " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # "
bc_arr[++n] = " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # "
bc_arr[++n] = " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # "
bc_arr[++n] = " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # "
bc_arr[++n] = " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # "
bc_arr[++n] = " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # "
bc_arr[++n] = " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # "
bc_arr[++n] = " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # "
bc_arr[++n] = " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # "
bc_arr[++n] = " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
bc_arr[++n] = " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### #" # NG
tmp = "123456712345671234567123456712345671234567"
printf("%2s: %-18s---%s-----%s---\n","N","UPC-A",tmp,tmp) # heading
for (i=1; i<=n; i++) {
# accept any number of spaces at beginning or end; I.E. minimum of 9 is not enforced
sub(/^ +/,"",bc_arr[i])
sub(/ +$/,"",bc_arr[i])
bc = bc_arr[i]
if (length(bc) == 95 && substr(bc,1,3) == "# #" && substr(bc,46,5) == " # # " && substr(bc,93,3) == "# #") {
upc = ""
sum = upc_build(ls_arr,1,substr(bc,4,42))
sum += upc_build(rs_arr,7,substr(bc,51,42))
if (upc ~ /^x+$/) { msg = "reversed" }
else if (upc ~ /x/) { msg = "invalid digit(s)" }
else if (sum % 10 != 0) { msg = "bad check digit" }
else { msg = upc }
}
else {
msg = "invalid format"
}
printf("%2d: %-18s%s\n",i,msg,bc)
}
exit(0)
}
function upc_build(arr,pos,bc, i,s,sum) {
pos--
for (i=1; i<=42; i+=7) {
s = substr(bc,i,7)
pos++
if (s in arr) {
upc = upc arr[s]
sum += arr[s] * weight_arr[pos]
}
else {
upc = upc "x"
}
}
return(sum)
}
|
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
| #Go | Go | package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
// line represents a single line in the configuration file.
type line struct {
kind lineKind
option string
value string
disabled bool
}
// lineKind represents the different kinds of configuration line.
type lineKind int
const (
_ lineKind = iota
ignore
parseError
comment
blank
value
)
func (l line) String() string {
switch l.kind {
case ignore, parseError, comment, blank:
return l.value
case value:
s := l.option
if l.disabled {
s = "; " + s
}
if l.value != "" {
s += " " + l.value
}
return s
}
panic("unexpected line kind")
}
func removeDross(s string) string {
return strings.Map(func(r rune) rune {
if r < 32 || r > 0x7f || unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func parseLine(s string) line {
if s == "" {
return line{kind: blank}
}
if s[0] == '#' {
return line{kind: comment, value: s}
}
s = removeDross(s)
fields := strings.Fields(s)
if len(fields) == 0 {
return line{kind: blank}
}
// Strip leading semicolons (but record that we found them)
semi := false
for len(fields[0]) > 0 && fields[0][0] == ';' {
semi = true
fields[0] = fields[0][1:]
}
// Lose the first field if it was all semicolons
if fields[0] == "" {
fields = fields[1:]
}
switch len(fields) {
case 0:
// This can only happen if the line starts
// with a semicolon but has no other information
return line{kind: ignore}
case 1:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
disabled: semi,
}
case 2:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
value: fields[1],
disabled: semi,
}
}
return line{kind: parseError, value: s}
}
// Config represents a "standard" configuration file.
type Config struct {
options map[string]int // index of each option in lines.
lines []line
}
// index returns the index of the given option in
// c.lines, or -1 if not found.
func (c *Config) index(option string) int {
if i, ok := c.options[option]; ok {
return i
}
return -1
}
// addLine adds a line to the config, ignoring
// duplicate options and "ignore" lines.
func (c *Config) addLine(l line) {
switch l.kind {
case ignore:
return
case value:
if c.index(l.option) >= 0 {
return
}
c.options[l.option] = len(c.lines)
c.lines = append(c.lines, l)
default:
c.lines = append(c.lines, l)
}
}
// ReadConfig reads a configuration file from path and returns it.
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
c := &Config{options: make(map[string]int)}
for {
s, err := r.ReadString('\n')
if s != "" {
if err == nil {
// strip newline unless we encountered an error without finding one.
s = s[:len(s)-1]
}
c.addLine(parseLine(s))
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return c, nil
}
// Set sets an option to a value, adding the option if necessary. If
// the option was previously disabled, it will be enabled.
func (c *Config) Set(option string, val string) {
if i := c.index(option); i >= 0 {
line := &c.lines[i]
line.disabled = false
line.value = val
return
}
c.addLine(line{
kind: value,
option: option,
value: val,
})
}
// Enable sets the enabled status of an option. It is
// ignored if the option does not already exist.
func (c *Config) Enable(option string, enabled bool) {
if i := c.index(option); i >= 0 {
c.lines[i].disabled = !enabled
}
}
// Write writes the configuration file to the writer.
func (c *Config) Write(w io.Writer) {
for _, line := range c.lines {
fmt.Println(line)
}
}
func main() {
c, err := ReadConfig("/tmp/cfg")
if err != nil {
log.Fatalln(err)
}
c.Enable("NEEDSPEELING", false)
c.Set("SEEDSREMOVED", "")
c.Set("NUMBEROFBANANAS", "1024")
c.Set("NUMBEROFSTRAWBERRIES", "62000")
c.Write(os.Stdout)
} |
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
| #Crystal | Crystal | puts "You entered: #{gets}"
begin
puts "You entered: #{gets.not_nil!.chomp.to_i}"
rescue ex
puts ex
end |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #D | D | import std.stdio;
void main() {
long number;
write("Enter an integer: ");
readf("%d", &number);
char[] str;
write("Enter a string: ");
readf(" %s\n", &str);
writeln("Read in '", number, "' and '", str, "'");
} |
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
| #Groovy | Groovy | import javax.swing.JOptionPane
def number = JOptionPane.showInputDialog ("Enter an Integer") as Integer
def string = JOptionPane.showInputDialog ("Enter a String")
assert number instanceof Integer
assert string instanceof String |
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.
| #Haskell | Haskell | module Main (main) where
import qualified Data.ByteString as ByteString (pack, unpack)
import Data.Char (chr, ord)
import Data.Foldable (for_)
import Data.List (intercalate)
import qualified Data.Text as Text (head, singleton)
import qualified Data.Text.Encoding as Text (decodeUtf8, encodeUtf8)
import Text.Printf (printf)
encodeCodepoint :: Int -> [Int]
encodeCodepoint = map fromIntegral . ByteString.unpack . Text.encodeUtf8 . Text.singleton . chr
decodeToCodepoint :: [Int] -> Int
decodeToCodepoint = ord . Text.head . Text.decodeUtf8 . ByteString.pack . map fromIntegral
main :: IO ()
main = do
putStrLn "Character Unicode UTF-8 encoding (hex) Decoded"
putStrLn "-------------------------------------------------"
for_ [0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E] $ \codepoint -> do
let values = encodeCodepoint codepoint
codepoint' = decodeToCodepoint values
putStrLn $ printf "%c %-7s %-20s %c"
codepoint
(printf "U+%04X" codepoint :: String)
(intercalate " " (map (printf "%02X") values))
codepoint' |
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.
| #Racket | Racket |
typedef int strfun (char * Data, size_t * Length);
strfun *Query = NULL;
|
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.
| #Raku | Raku | #!/usr/bin/env raku
sub MAIN (Int :l(:len(:$length))) {
my Str $String = "Here am I";
$*OUT.print: $String if $String.codes ≤ $length
} |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use URI;
for my $uri (do { no warnings 'qw';
qw( 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
)}) {
my $u = 'URI'->new($uri);
print "$uri\n";
for my $part (qw( scheme path fragment authority host port query )) {
eval { my $parsed = $u->$part;
print "\t", $part, "\t", $parsed, "\n" if defined $parsed;
};
}
} |
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
| #Groovy | Groovy |
def normal = "http://foo bar/"
def encoded = URLEncoder.encode(normal, "utf-8")
println encoded
|
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Haskell | Haskell | import qualified Data.Char as Char
import Text.Printf
encode :: Char -> String
encode c
| c == ' ' = "+"
| Char.isAlphaNum c || c `elem` "-._~" = [c]
| otherwise = printf "%%%02X" c
urlEncode :: String -> String
urlEncode = concatMap encode
main :: IO ()
main = putStrLn $ urlEncode "http://foo bar/" |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Elena | Elena | import system'collections;
public program()
{
var c := nil; // declaring variable.
var a := 3; // declaring and initializing variables
var b := "my string".Length;
long l := 200l; // declaring strongly typed variable
auto lst := new List<int>();
c := b + a; // assigning variable
} |
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
| #Erlang | Erlang |
two() ->
A_variable = 1,
A_variable + 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.
| #Kotlin | Kotlin | fun main() {
println("First 10 terms of Van Eck's sequence:")
vanEck(1, 10)
println("")
println("Terms 991 to 1000 of Van Eck's sequence:")
vanEck(991, 1000)
}
private fun vanEck(firstIndex: Int, lastIndex: Int) {
val vanEckMap = mutableMapOf<Int, Int>()
var last = 0
if (firstIndex == 1) {
println("VanEck[1] = 0")
}
for (n in 2..lastIndex) {
val vanEck = if (vanEckMap.containsKey(last)) n - vanEckMap[last]!! else 0
vanEckMap[last] = n
last = vanEck
if (n >= firstIndex) {
println("VanEck[$n] = $vanEck")
}
}
} |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Racket | Racket | #lang racket
;; chock full of fun... including divisors
(require math/number-theory)
;; predicate to tell if n is a vampire number
(define (sub-vampire?-and-fangs n)
(define digit-count-n (add1 (order-of-magnitude n)))
(define (string-sort-characters s) (sort (string->list s) char<?))
(define digits-in-order-n (string-sort-characters (number->string n)))
(define (fangs-of-n? d e)
(and (<= d e) ; avoid duplication
(= (add1 (order-of-magnitude d)) (add1 (order-of-magnitude e)) (/ digit-count-n 2))
(not (= 0 (modulo d 10) (modulo e 10)))
(equal? digits-in-order-n
(string-sort-characters (string-append (number->string d) (number->string e))))))
(let* ((fangses (for*/list ((d (in-list (divisors n))) #:when (fangs-of-n? d (/ n d)))
(list d (/ n d)))))
(and (not (null? fangses)) (cons n fangses))))
(define (vampire?-and-fangs n)
(and (odd? (order-of-magnitude n)) ; even number of digits - else not even worth looking!
(sub-vampire?-and-fangs n)))
(displayln "First 25 vampire numbers:")
(for ((vmp (sequence-filter identity (sequence-map vampire?-and-fangs (in-naturals 1))))
(cnt (in-range 1 (add1 25))))
(printf "#~a ~a~%" cnt vmp))
(displayln "Test the big numbers:")
(displayln (vampire?-and-fangs 16758243290880))
(displayln (vampire?-and-fangs 24959017348650))
(displayln (vampire?-and-fangs 14593825548650)) |
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
| #Raku | Raku | sub is_vampire (Int $num) {
my $digits = $num.comb.sort;
my @fangs;
(10**$num.sqrt.log(10).floor .. $num.sqrt.ceiling).map: -> $this {
next if $num % $this;
my $that = $num div $this;
next if $this %% 10 && $that %% 10;
@fangs.push("$this x $that") if ($this ~ $that).comb.sort eq $digits;
}
@fangs
}
constant @vampires = flat (3..*).map: -> $s, $e {
(10**$s .. 10**$e).hyper.map: -> $n {
next unless my @fangs = is_vampire($n);
"$n: { @fangs.join(', ') }"
}
}
say "\nFirst 25 Vampire Numbers:\n";
.say for @vampires[^25];
say "\nIndividual tests:\n";
.say for (16758243290880, 24959017348650, 14593825548650).hyper(:1batch).map: {
"$_: " ~ (is_vampire($_).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
| #Nim | Nim | proc print(xs: varargs[string, `$`]) =
for x in xs:
echo 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
| #Objective-C | Objective-C | #include <stdarg.h>
void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
{
va_list args;
va_start(args, firstObject);
id obj;
for (obj = firstObject; obj != nil; obj = va_arg(args, id))
NSLog(@"%@", obj);
va_end(args);
}
// This function can be called with any number or type of objects, as long as you terminate it with "nil":
logObjects(@"Rosetta", @"Code", @"Is", @"Awesome!", nil);
logObjects(@4, @3, @"foo", nil); |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
let vmath f v1 v2 =>
s.zip (a.stream v1) (a.stream v2)
-> s.map (@ m v =>
let [v1 v2] => v;
f (v1 { == s.end => 0 }) (v2 { == s.end => 0 });
)
-> s.collect
;
let smath f scalar vector => a.stream vector -> s.map (f scalar) -> s.collect;
let v+ => vmath +;
let v- => vmath -;
let s* => smath *;
let s/ => smath /; |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Wren | Wren | class Vector2D {
construct new(x, y) {
_x = x
_y = y
}
static fromPolar(r, theta) { new(r * theta.cos, r * theta.sin) }
x { _x }
y { _y }
+(v) { Vector2D.new(_x + v.x, _y + v.y) }
-(v) { Vector2D.new(_x - v.x, _y - v.y) }
*(s) { Vector2D.new(_x * s, _y * s) }
/(s) { Vector2D.new(_x / s, _y / s) }
toString { "(%(_x), %(_y))" }
}
var times = Fn.new { |d, v| v * d }
var v1 = Vector2D.new(5, 7)
var v2 = Vector2D.new(2, 3)
var v3 = Vector2D.fromPolar(2.sqrt, Num.pi / 4)
System.print("v1 = %(v1)")
System.print("v2 = %(v2)")
System.print("v3 = %(v3)")
System.print()
System.print("v1 + v2 = %(v1 + v2)")
System.print("v1 - v2 = %(v1 - v2)")
System.print("v1 * 11 = %(v1 * 11)")
System.print("11 * v2 = %(times.call(11, v2))")
System.print("v1 / 2 = %(v1 / 2)") |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #TXR | TXR | @(next :args)
@(do
(defun vig-op (plus-or-minus)
(op + #\A [mod [plus-or-minus (- @1 #\A) (- @2 #\A)] 26]))
(defun vig (msg key encrypt)
(mapcar (vig-op [if encrypt + -]) msg (repeat key))))
@(coll)@{key /[A-Za-z]/}@(end)
@(coll)@{msg /[A-Za-z]/}@(end)
@(cat key "")
@(filter :upcase key)
@(cat msg "")
@(filter :upcase msg)
@(bind encoded @(vig msg key t))
@(bind decoded @(vig msg key nil))
@(bind check @(vig encoded key nil))
@(output)
text: @msg
key: @key
enc: @encoded
dec: @decoded
check: @check
@(end) |
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
| #TypeScript | TypeScript | class Vigenere {
key: string
/** Create new cipher based on key */
constructor(key: string) {
this.key = Vigenere.formatText(key)
}
/** Enrypt a given text using key */
encrypt(plainText: string): string {
return Array.prototype.map.call(Vigenere.formatText(plainText), (letter: string, index: number): string => {
return String.fromCharCode((letter.charCodeAt(0) + this.key.charCodeAt(index % this.key.length) - 130) % 26 + 65)
}).join('')
}
/** Decrypt ciphertext based on key */
decrypt(cipherText: string): string {
return Array.prototype.map.call(Vigenere.formatText(cipherText), (letter: string, index: number): string => {
return String.fromCharCode((letter.charCodeAt(0) - this.key.charCodeAt(index % this.key.length) + 26) % 26 + 65)
}).join('')
}
/** Converts to uppercase and removes non characters */
private static formatText(text: string): string {
return text.toUpperCase().replace(/[^A-Z]/g, "")
}
}
/** Example usage */
(() => {
let original: string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
console.log(`Original: ${original}`)
let vig: Vigenere = new Vigenere("vigenere")
let encoded: string = vig.encrypt(original)
console.log(`After encryption: ${encoded}`)
let back: string = vig.decrypt(encoded)
console.log(`After decryption: ${back}`)
})()
|
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
| #Fantom | Fantom | class Main
{
Int dot_product (Int[] a, Int[] b)
{
a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
}
Int[] cross_product (Int[] a, Int[] b)
{
[a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0]]
}
Int scalar_triple_product (Int[] a, Int[] b, Int[] c)
{
dot_product (a, cross_product (b, c))
}
Int[] vector_triple_product (Int[] a, Int[] b, Int[] c)
{
cross_product (a, cross_product (b, c))
}
Void main ()
{
a := [3, 4, 5]
b := [4, 3, 5]
c := [-5, -12, -13]
echo ("a . b = " + dot_product (a, b))
echo ("a x b = [" + cross_product(a, b).join (", ") + "]")
echo ("a . (b x c) = " + scalar_triple_product (a, b, c))
echo ("a x (b x c) = [" + vector_triple_product(a, b, c).join (", ") + "]")
}
} |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Phix | Phix | with javascript_semantics
function Luhn(string st)
integer s = 0, d
st = reverse(st)
for i=1 to length(st) do
d = st[i]-'0'
s += iff(mod(i,2)?d,d*2-(d>4)*9)
end for
return remainder(s,10)=0
end function
function valid_ISIN(string st)
-- returns 1 if valid, else 0/2/3/4.
-- (feel free to return 0 instead of 2/3/4)
if length(st)!=12 then return 2 end if
for i=length(st) to 1 by -1 do
integer ch = st[i]
if ch>='A' then
if ch>'Z' then return 3 end if
st[i..i] = sprintf("%d",ch-55)
elsif i<=2 then
return 4
elsif ch<'0' or ch>'9' then
return 3
end if
end for
return Luhn(st)
end function
constant tests = {"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
reasons = {"wrong checksum","valid","wrong length","bad char","wrong country"}
for i=1 to length(tests) do
printf(1,"%s : %s\n",{tests[i],reasons[valid_ISIN(tests[i])+1]})
end for
|
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
| #Lua | Lua | function vdc(n, base)
local digits = {}
while n ~= 0 do
local m = math.floor(n / base)
table.insert(digits, n - m * base)
n = m
end
m = 0
for p, d in pairs(digits) do
m = m + math.pow(base, -p) * d
end
return m
end |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Maple | Maple | Halton:=proc(n,b)
local i:=n,k:=1,s:=0,r;
while i>0 do
k/=b;
i:=iquo(i,b,'r');
s+=k*r
od;
s
end;
map(Halton,[$1..10],2);
# [1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16, 5/16]
map(Halton,[$1..10],3);
# [1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27, 10/27]
map(Halton,[$1..10],4);
# [1/4, 1/2, 3/4, 1/16, 5/16, 9/16, 13/16, 1/8, 3/8, 5/8]
map(Halton,[$1..10],5);
[1/5, 2/5, 3/5, 4/5, 1/25, 6/25, 11/25, 16/25, 21/25, 2/25] |
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á".
| #Factor | Factor | USING: io kernel urls.encoding ;
IN: rosetta-code.url-decoding
"http%3A%2F%2Ffoo%20bar%2F"
"google.com/search?q=%60Abdu%27l-Bah%C3%A1"
[ url-decode print ] bi@ |
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á".
| #Free_Pascal | Free Pascal | function urlDecode(data: String): AnsiString;
var
ch: Char;
pos, skip: Integer;
begin
pos := 0;
skip := 0;
Result := '';
for ch in data do begin
if skip = 0 then begin
if (ch = '%') and (pos < data.length -2) then begin
skip := 2;
Result := Result + AnsiChar(Hex2Dec('$' + data[pos+2] + data[pos+3]));
end else begin
Result := Result + ch;
end;
end else begin
skip := skip - 1;
end;
pos := pos +1;
end;
end; |
http://rosettacode.org/wiki/UPC | UPC | Goal
Convert UPC bar codes to decimal.
Specifically:
The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards...
Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and # characters representing the presence or absence of ink).
Sample input
Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:
# # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # #
# # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # #
# # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # #
# # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # #
# # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # #
# # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # #
# # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # #
# # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # #
# # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # #
# # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # #
Some of these were entered upside down, and one entry has a timing error.
Task
Implement code to find the corresponding decimal representation of each, rejecting the error.
Extra credit for handling the rows entered upside down (the other option is to reject them).
Notes
Each digit is represented by 7 bits:
0: 0 0 0 1 1 0 1
1: 0 0 1 1 0 0 1
2: 0 0 1 0 0 1 1
3: 0 1 1 1 1 0 1
4: 0 1 0 0 0 1 1
5: 0 1 1 0 0 0 1
6: 0 1 0 1 1 1 1
7: 0 1 1 1 0 1 1
8: 0 1 1 0 1 1 1
9: 0 0 0 1 0 1 1
On the left hand side of the bar code a space represents a 0 and a # represents a 1.
On the right hand side of the bar code, a # represents a 0 and a space represents a 1
Alternatively (for the above): spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code.
The UPC-A bar code structure
It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly),
then has a # # sequence marking the start of the sequence,
then has the six "left hand" digits,
then has a # # sequence in the middle,
then has the six "right hand digits",
then has another # # (end sequence), and finally,
then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).
Finally, the last digit is a checksum digit which may be used to help detect errors.
Verification
Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.
The sum (mod 10) must be 0 (must have a zero as its last digit) if the UPC number has been read correctly.
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char const *const string;
bool consume_sentinal(bool middle, string s, size_t *pos) {
if (middle) {
if (s[*pos] == ' ' && s[*pos + 1] == '#' && s[*pos + 2] == ' ' && s[*pos + 3] == '#' && s[*pos + 4] == ' ') {
*pos += 5;
return true;
}
} else {
if (s[*pos] == '#' && s[*pos + 1] == ' ' && s[*pos + 2] == '#') {
*pos += 3;
return true;
}
}
return false;
}
int consume_digit(bool right, string s, size_t *pos) {
const char zero = right ? '#' : ' ';
const char one = right ? ' ' : '#';
size_t i = *pos;
int result = -1;
if (s[i] == zero) {
if (s[i + 1] == zero) {
if (s[i + 2] == zero) {
if (s[i + 3] == one) {
if (s[i + 4] == zero) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 9;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 0;
}
}
}
} else if (s[i + 2] == one) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {
result = 2;
}
} else if (s[i + 3] == one) {
if (s[i + 4] == zero && s[i + 5] == zero && s[i + 6] == one) {
result = 1;
}
}
}
} else if (s[i + 1] == one) {
if (s[i + 2] == zero) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero && s[i + 5] == one && s[i + 6] == one) {
result = 4;
}
} else if (s[i + 3] == one) {
if (s[i + 4] == one && s[i + 5] == one && s[i + 6] == one) {
result = 6;
}
}
} else if (s[i + 2] == one) {
if (s[i + 3] == zero) {
if (s[i + 4] == zero) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 5;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 8;
}
}
} else if (s[i + 3] == one) {
if (s[i + 4] == zero) {
if (s[i + 5] == one && s[i + 6] == one) {
result = 7;
}
} else if (s[i + 4] == one) {
if (s[i + 5] == zero && s[i + 6] == one) {
result = 3;
}
}
}
}
}
}
if (result >= 0) {
*pos += 7;
}
return result;
}
bool decode_upc(string src, char *buffer) {
const int one = 1;
const int three = 3;
size_t pos = 0;
int sum = 0;
int digit;
//1) 9 spaces (unreliable)
while (src[pos] != '#') {
if (src[pos] == 0) {
return false;
}
pos++;
}
//2) Start "# #"
if (!consume_sentinal(false, src, &pos)) {
return false;
}
//3) 6 left-hand digits (space is zero and hash is one)
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(false, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
//4) Middle "# #"
if (!consume_sentinal(true, src, &pos)) {
return false;
}
//5) 6 right-hand digits (hash is zero and space is one)
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += three * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
digit = consume_digit(true, src, &pos);
if (digit < 0) {
return false;
}
sum += one * digit;
*buffer++ = digit + '0';
*buffer++ = ' ';
//6) Final "# #"
if (!consume_sentinal(false, src, &pos)) {
return false;
}
//7) 9 spaces (unreliable)
// skip
//8) the dot product of the number and (3, 1)+ sequence mod 10 must be zero
return sum % 10 == 0;
}
void test(string src) {
char buffer[24];
if (decode_upc(src, buffer)) {
buffer[22] = 0;
printf("%sValid\n", buffer);
} else {
size_t len = strlen(src);
char *rev = malloc(len + 1);
size_t i;
if (rev == NULL) {
exit(1);
}
for (i = 0; i < len; i++) {
rev[i] = src[len - i - 1];
}
#pragma warning(push)
#pragma warning(disable : 6386)
// if len + 1 bytes are allocated, and len bytes are writable, there is no buffer overrun
rev[len] = 0;
#pragma warning(pop)
if (decode_upc(rev, buffer)) {
buffer[22] = 0;
printf("%sValid (upside down)\n", buffer);
} else {
printf("Invalid digit(s)\n");
}
free(rev);
}
}
int main() {
int num = 0;
printf("%2d: ", ++num);
test(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ");
printf("%2d: ", ++num);
test(" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ");
printf("%2d: ", ++num);
test(" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ");
printf("%2d: ", ++num);
test(" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ");
printf("%2d: ", ++num);
test(" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ");
printf("%2d: ", ++num);
test(" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ");
printf("%2d: ", ++num);
test(" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ");
printf("%2d: ", ++num);
test(" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ");
printf("%2d: ", ++num);
test(" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ");
printf("%2d: ", ++num);
test(" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ");
return 0;
} |
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
| #Haskell | Haskell | import Data.Char (toUpper)
import qualified System.IO.Strict as S |
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
| #Dart | Dart | import 'dart:io' show stdout, stdin;
main() {
stdout.write('Enter a string: ');
final string_input = stdin.readLineSync();
int number_input;
do {
stdout.write('Enter the number 75000: ');
var number_input_string = stdin.readLineSync();
try {
number_input = int.parse(number_input_string);
if (number_input != 75000)
stdout.writeln('$number_input is not 75000!');
} on FormatException {
stdout.writeln('$number_input_string is not a valid number!');
} catch ( e ) {
stdout.writeln(e);
}
} while ( number_input != 75000 );
stdout.writeln('input: $string_input\nnumber: $number_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
| #Delphi | Delphi | program UserInputText;
{$APPTYPE CONSOLE}
uses SysUtils;
var
s: string;
lStringValue: string;
lIntegerValue: Integer;
begin
WriteLn('Enter a string:');
Readln(lStringValue);
repeat
WriteLn('Enter the number 75000');
Readln(s);
lIntegerValue := StrToIntDef(s, 0);
if lIntegerValue <> 75000 then
Writeln('Invalid entry: ' + s);
until lIntegerValue = 75000;
end. |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Haskell | Haskell | import Graphics.UI.Gtk
import Control.Monad
main = do
initGUI
window <- windowNew
set window [windowTitle := "Graphical user input", containerBorderWidth := 10]
vb <- vBoxNew False 0
containerAdd window vb
hb1 <- hBoxNew False 0
boxPackStart vb hb1 PackNatural 0
hb2 <- hBoxNew False 0
boxPackStart vb hb2 PackNatural 0
lab1 <- labelNew (Just "Enter number 75000")
boxPackStart hb1 lab1 PackNatural 0
nrfield <- entryNew
entrySetText nrfield "75000"
boxPackStart hb1 nrfield PackNatural 5
strfield <- entryNew
boxPackEnd hb2 strfield PackNatural 5
lab2 <- labelNew (Just "Enter a text")
boxPackEnd hb2 lab2 PackNatural 0
accbox <- hBoxNew False 0
boxPackStart vb accbox PackNatural 5
im <- imageNewFromStock stockApply IconSizeButton
acceptButton <- buttonNewWithLabel "Accept"
buttonSetImage acceptButton im
boxPackStart accbox acceptButton PackRepel 0
txtstack <- statusbarNew
boxPackStart vb txtstack PackNatural 0
id <- statusbarGetContextId txtstack "Line"
widgetShowAll window
onEntryActivate nrfield (showStat nrfield txtstack id)
onEntryActivate strfield (showStat strfield txtstack id)
onPressed acceptButton $ do
g <- entryGetText nrfield
if g=="75000" then
widgetDestroy window
else do
msgid <- statusbarPush txtstack id "You didn't enter 75000. Try again"
return ()
onDestroy window mainQuit
mainGUI
showStat :: Entry -> Statusbar -> ContextId -> IO ()
showStat fld stk id = do
txt <- entryGetText fld
let mesg = "You entered \"" ++ txt ++ "\""
msgid <- statusbarPush stk id mesg
return () |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #J | J | utf8=: 8&u: NB. converts to UTF-8 from unicode or unicode codepoint integer
ucp=: 9&u: NB. converts to unicode from UTF-8 or unicode codepoint integer
ucp_hex=: hfd@(3 u: ucp) NB. converts to unicode codepoint hexadecimal from UTF-8, unicode or unicode codepoint integer |
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.
| #Java | Java | import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
} |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #Ruby | Ruby | # query.rb
require 'fiddle'
# Look for a C variable named QueryPointer.
# Raise an error if it is missing.
c_var = Fiddle.dlopen(nil)['QueryPointer']
int = Fiddle::TYPE_INT
voidp = Fiddle::TYPE_VOIDP
sz_voidp = Fiddle::SIZEOF_VOIDP
# Implement the C function
# int Query(void *data, size_t *length)
# in Ruby code. Store it in a global constant in Ruby (named Query)
# to protect it from Ruby's garbage collector.
#
Query = Fiddle::Closure::BlockCaller
.new(int, [voidp, voidp]) do |datap, lengthp|
message = "Here am I"
# We got datap and lengthp as Fiddle::Pointer objects.
# Read length, assuming sizeof(size_t) == sizeof(void *).
length = lengthp[0, sz_voidp].unpack('J').first
# Does the message fit in length bytes?
if length < message.bytesize
0 # failure
else
length = message.bytesize
datap[0, length] = message # Copy the message.
lengthp[0, sz_voidp] = [length].pack('J') # Update the length.
1 # success
end
end
# Set the C variable to our Query.
Fiddle::Pointer.new(c_var)[0, sz_voidp] = [Query.to_i].pack('J') |
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.
| #Rust | Rust |
//! In order to run this task, you will need to compile the C program locating in the task linked
//! above. The C program will need to be linked with the library produced by this file.
//!
//! 1. Compile this library:
//!
//! ```bash
//! $ cargo build --release
//! ```
//!
//! 2. Copy the C program into query.c.
//! 3. Compile and link the C program with the produced library:
//!
//! ```bash
//! $ LD_LIBRARY_PATH=/path/to/library gcc query.c -o query -Wall -Werror libquery
//! ```
//! 4. Run the resulting binary.
//!
//! ```bash
//! $ LD_LIBRARY_PATH=/path/to/library ./query
//! Here am I
//! ```
#![crate_type = "cdylib"]
extern crate libc;
use std::ffi::CString;
use libc::{c_char, c_int, size_t};
#[no_mangle]
#[allow(non_snake_case)]
#[allow(clippy::missing_safety_doc)]
pub unsafe extern "C" fn Query(data: *mut c_char, length: *mut size_t) -> c_int {
let string = "Here am I";
if *length + 1 < string.len() {
0
} else {
let c_string = CString::new(string).unwrap();
libc::strcpy(data, c_string.as_ptr());
*length = string.len();
1
}
}
|
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
| #Phix | Phix | with javascript_semantics
include builtins/url.e
procedure show_url_details(string uri)
?uri
sequence r = parse_url(uri)
for i=1 to length(r) do
if r[i]!=0 then
string desc = url_element_desc(i)
printf(1,"%s : %v\n",{desc,r[i]})
end if
end for
puts(1,"\n")
end procedure
constant tests = {
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"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 i=1 to length(tests) do
show_url_details(tests[i])
end for
|
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
| #Icon_and_Unicon | Icon and Unicon | link hexcvt
procedure main()
write("text = ",image(u := "http://foo bar/"))
write("encoded = ",image(ue := encodeURL(u)))
end
procedure encodeURL(s) #: encode data for inclusion in a URL/URI
static en
initial { # build lookup table for everything
en := table()
every en[c := !string(~(&digits++&letters))] := "%"||hexstring(ord(c),2)
every /en[c := !string(&cset)] := c
}
every (c := "") ||:= en[!s] # re-encode everything
return c
end
|
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
| #F.23 | F# | let x = 5 // Int
let mutable y = "mutable" // Mutable string
let recordType = { foo : 6; bar : 6 } // Record
let intWidget = new Widget<int>() // Generic class
let add2 x = 2 + x // Function value |
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.
| #Lua | Lua | -- Return a table of the first n values of the Van Eck sequence
function vanEck (n)
local seq, foundAt = {0}
while #seq < n do
foundAt = nil
for pos = #seq - 1, 1, -1 do
if seq[pos] == seq[#seq] then
foundAt = pos
break
end
end
if foundAt then
table.insert(seq, #seq - foundAt)
else
table.insert(seq, 0)
end
end
return seq
end
-- Show the set of values in table t from key numbers lo to hi
function showValues (t, lo, hi)
for i = lo, hi do
io.write(t[i] .. " ")
end
print()
end
-- Main procedure
local sequence = vanEck(1000)
showValues(sequence, 1, 10)
showValues(sequence, 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.
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION E(1000)
E(0)=0
THROUGH L1, FOR I=0, 1, I.GE.1000
THROUGH L2, FOR J=I-1, -1, J.L.0
WHENEVER E(J).E.E(I)
E(I+1) = I-J
TRANSFER TO L1
END OF CONDITIONAL
L2 CONTINUE
E(I+1)=0
L1 CONTINUE
THROUGH S, FOR I=0, 1, I.GE.10
S PRINT FORMAT FMT, I, E(I), I+990, E(I+990)
VECTOR VALUES FMT = $2HE(,I3,2H)=,I3,S5,2HE(,I3,2H)=,I3*$
END OF PROGRAM |
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
| #REXX | REXX | /*REXX program displays N vampire numbers, or verifies if a number is vampiric. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/
!.0= 1260; !.1= 11453481; !.2= 115672; !.3= 124483; !.4= 105264 /*lowest #, dig*/
!.5= 1395; !.6= 126846; !.7= 1827; !.8= 110758; !.9= 156289 /* " " " */
L= length(N); aN= abs(N) /*L: length of N; aN: absolute value*/
numeric digits max(9, length(aN) ) /*be able to handle ginormus numbers. */
# = 0 /*#: count of vampire numbers (so far)*/
if N>0 then do j=1260 until # >= N /*search until N vampire numbers found.*/
if length(j) // 2 then do; j= j*10 - 1; iterate /*bump J to even length*/
end /* [↑] check if odd. */
parse var j '' -1 _ /*obtain the last decimal digit of J. */
if j<!._ then iterate /*is number tenable based on last dig? */
f= vampire(j) /*obtain the fangs of J. */
if f=='' then iterate /*Are fangs null? Yes, not vampire. */
#= # + 1 /*bump the vampire count, Vlad. */
say right('vampire number', 20) right(#, L) "is: " right(j, 9)', fangs=' f
end /*j*/ /* [↑] process a range of numbers. */
else do; f= vampire(aN) /* [↓] process a number; obtain fangs.*/
if f=='' then say aN " isn't a vampire number."
else say aN " is a vampire number, fangs=" f
end
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
vampire: procedure; parse arg x,, $. a bot; L= length(x) /*get arg; compute len of X*/
if L//2 then return '' /*is L odd? Then ¬vampire.*/
do k=1 for L; _= substr(x, k, 1); $._= $._ || _
end /*k*/
w= L % 2 /*%: is REXX's integer ÷ */
do m=0 for 10; bot= bot || $.m
end /*m*/
top= left( reverse(bot), w)
bot= left(bot, w) /*determine limits of search*/
inc= x // 2 + 1 /*X is odd? INC=2. No? INC=1*/
beg= max(bot, 10 ** (w-1) ) /*calculate where to begin.*/
if inc==2 then if beg//2==0 then beg= beg + 1 /*possibly adjust the begin.*/
/* [↑] odd BEG if odd INC*/
do d=beg to min(top, 10**w - 1) by inc /*use smart BEG, END, INC. */
if x // d \==0 then iterate /*X not ÷ by D? Then skip,*/
q= x % d; if d>q then iterate /*is D > Q " " */
if length(q) \== w then iterate /*Len of Q ¬= W? Then skip.*/
if q*d//9 \== (q+d)//9 then iterate /*modulo 9 congruence test. */
parse var q '' -1 _ /*get last decimal dig. of Q*/
if _== 0 then if right(d, 1) == 0 then iterate
dq= d || q
t= x; do i=1 for L; p= pos( substr(dq, i, 1), t)
if p==0 then iterate d; t= delstr(t, p, 1)
end /*i*/
a= a '['d"∙"q'] ' /*construct formatted fangs.*/
end /*d*/ /* [↑] ∙ is a round bullet*/
return a /*return formatted fangs.*/ |
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
| #Oforth | Oforth | : sumNum(n) | i | 0 n loop: i [ + ] ; |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Oz | Oz | declare
class Demo from BaseObject
meth test(...)=Msg
{Record.forAll Msg Show}
end
end
D = {New Demo noop}
Constructed = {List.toTuple test {List.number 1 10 1}}
in
{D test(1 2 3 4)}
{D Constructed} |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Yabasic | Yabasic | dim vect1(2)
vect1(1) = 5 : vect1(2) = 7
dim vect2(2)
vect2(1) = 2 : vect2(2) = 3
dim vect3(arraysize(vect1(),1))
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) + vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] + [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) - vect2(n)
next n
print "[", vect1(1), ", ", vect1(2), "] - [", vect2(1), ", ", vect2(2), "] = ";
showarray(vect3)
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) * 11
next n
print "[", vect1(1), ", ", vect1(2), "] * ", 11, " = ";
showarray(vect3)
for n = 1 to arraysize(vect1(),1)
vect3(n) = vect1(n) / 2
next n
print "[", vect1(1), ", ", vect1(2), "] / ", 2, " = ";
showarray(vect3)
end
sub showarray(vect3)
print "[";
svect$ = ""
for n = 1 to arraysize(vect3(),1)
svect$ = svect$ + str$(vect3(n)) + ", "
next n
svect$ = left$(svect$, len(svect$) - 2)
print svect$;
print "]"
end sub |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #zkl | zkl | class Vector{
var length,angle; // polar coordinates, radians
fcn init(length,angle){ // angle in degrees
self.length,self.angle = vm.arglist.apply("toFloat");
self.angle=self.angle.toRad();
}
fcn toXY{ length.toRectangular(angle) }
// math is done in place
fcn __opAdd(vector){
x1,y1:=toXY(); x2,y2:=vector.toXY();
length,angle=(x1+x2).toPolar(y1+y2);
self
}
fcn __opSub(vector){
x1,y1:=toXY(); x2,y2:=vector.toXY();
length,angle=(x1-x2).toPolar(y1-y2);
self
}
fcn __opMul(len){ length*=len; self }
fcn __opDiv(len){ length/=len; self }
fcn print(msg=""){
#<<<
"Vector%s:
Length: %f
Angle: %f\Ub0;
X: %f
Y: %f"
#<<<
.fmt(msg,length,angle.toDeg(),length.toRectangular(angle).xplode())
.println();
}
fcn toString{ "Vector(%f,%f\Ub0;)".fmt(length,angle.toDeg()) }
} |
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
| #VBA | VBA | Option Explicit
Sub test()
Dim Encryp As String
Encryp = Vigenere("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher", True)
Debug.Print "Encrypt:= """ & Encryp & """"
Debug.Print "Decrypt:= """ & Vigenere(Encryp, "vigenerecipher", False) & """"
End Sub
Private Function Vigenere(sWord As String, sKey As String, Enc As Boolean) As String
Dim bw() As Byte, bk() As Byte, i As Long, c As Long
Const sW As String = "ÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ"
Const sWo As String = "AAAAACEEEEIIIINOOOOOUUUUY"
Const A As Long = 65
Const N As Long = 26
c = Len(sKey)
i = Len(sWord)
sKey = Left(IIf(c < i, StrRept(sKey, (i / c) + 1), sKey), i)
sKey = StrConv(sKey, vbUpperCase) 'Upper case
sWord = StrConv(sWord, vbUpperCase)
sKey = StrReplace(sKey, sW, sWo) 'Replace accented characters
sWord = StrReplace(sWord, sW, sWo)
sKey = RemoveChars(sKey) 'Remove characters (numerics, spaces, comas, ...)
sWord = RemoveChars(sWord)
bk = CharToAscii(sKey) 'To work with Bytes instead of String
bw = CharToAscii(sWord)
For i = LBound(bw) To UBound(bw)
Vigenere = Vigenere & Chr((IIf(Enc, ((bw(i) - A) + (bk(i) - A)), ((bw(i) - A) - (bk(i) - A)) + N) Mod N) + A)
Next i
End Function
Private Function StrRept(s As String, N As Long) As String
Dim j As Long, c As String
For j = 1 To N
c = c & s
Next
StrRept = c
End Function
Private Function StrReplace(s As String, What As String, By As String) As String
Dim t() As String, u() As String, i As Long
t = SplitString(What)
u = SplitString(By)
StrReplace = s
For i = LBound(t) To UBound(t)
StrReplace = Replace(StrReplace, t(i), u(i))
Next i
End Function
Private Function SplitString(s As String) As String()
SplitString = Split(StrConv(s, vbUnicode), Chr(0))
End Function
Private Function RemoveChars(str As String) As String
Dim b() As Byte, i As Long
b = CharToAscii(str)
For i = LBound(b) To UBound(b)
If b(i) >= 65 And b(i) <= 90 Then RemoveChars = RemoveChars & Chr(b(i))
Next i
End Function
Private Function CharToAscii(s As String) As Byte()
CharToAscii = StrConv(s, vbFromUnicode)
End Function |
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
| #Forth | Forth |
: 3f! ( &v - ) ( f: x y z - ) dup float+ dup float+ f! f! f! ;
: Vector \ Compiletime: ( f: x y z - ) ( <name> - )
create here [ 3 floats ] literal allot 3f! ; \ Runtime: ( - &v )
: >fx@ ( &v - ) ( f: - n ) postpone f@ ; immediate
: >fy@ ( &v - ) ( f: - n ) float+ f@ ;
: >fz@ ( &v - ) ( f: - n ) float+ float+ f@ ;
: .Vector ( &v - ) dup >fz@ dup >fy@ >fx@ f. f. f. ;
: Dot* ( &v1 &v2 - ) ( f - DotPrd )
2dup >fx@ >fx@ f*
2dup >fy@ >fy@ f* f+
>fz@ >fz@ f* f+ ;
: Cross* ( &v1 &v2 &vResult - )
>r 2dup >fz@ >fy@ f*
2dup >fy@ >fz@ f* f-
2dup >fx@ >fz@ f*
2dup >fz@ >fx@ f* f-
2dup >fy@ >fx@ f*
>fx@ >fy@ f* f-
r> 3f! ;
: ScalarTriple* ( &v1 &v2 &v3 - ) ( f: - ScalarTriple* )
>r pad Cross* pad r> Dot* ;
: VectorTriple* ( &v1 &v2 &v3 &vDest - )
>r swap r@ Cross* r> tuck Cross* ;
3e 4e 5e Vector A
4e 3e 5e Vector B
-5e -12e -13e Vector C
cr
cr .( a . b = ) A B Dot* f.
cr .( a x b = ) A B pad Cross* pad .Vector
cr .( a . [b x c] = ) A B C ScalarTriple* f.
cr .( a x [b x c] = ) A B C pad VectorTriple* pad .Vector |
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
| #PicoLisp | PicoLisp | (de isin (Str)
(let Str (mapcar char (chop Str))
(and
(= 12 (length Str))
(<= 65 (car Str) 90)
(<= 65 (cadr Str) 90)
(luhn
(pack
(mapcar
'((N)
(- N (if (<= 48 N 57) 48 55)) )
Str ) ) ) ) ) )
(println
(mapcar
isin
(quote
"US0378331005"
"US0373831005"
"U50378331005"
"US03783310005"
"AU0000XVGZA3"
"AU0000VXGZA3"
"FR0000988040" ) ) ) |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #PowerShell | PowerShell |
function Test-ISIN
{
[CmdletBinding()]
[OutputType([bool])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern("[A-Z]{2}\w{9}\d")]
[ValidateScript({$_.Length -eq 12})]
[string]
$Number
)
function Split-Array
{
$array = @(), @()
$input | ForEach-Object {$array[($index = -not $index)] += $_}
$array[1], $array[0]
}
filter ConvertTo-Digit
{
if ($_ -gt 9)
{
$_.ToString().ToCharArray() | ForEach-Object -Begin {$n = 0} -Process {$n += [Char]::GetNumericValue($_)} -End {$n}
}
else
{
$_
}
}
$checkDigit = $Number[-1]
$digits = ($Number -replace ".$").ToCharArray() | ForEach-Object {
if ([Char]::IsDigit($_))
{
[Char]::GetNumericValue($_)
}
else
{
[int][char]$_ - 55
}
}
$odds, $evens = ($digits -join "").ToCharArray() | Split-Array
if ($odds.Count -gt $evens.Count)
{
$odds = $odds | ForEach-Object {[Char]::GetNumericValue($_) * 2} | ConvertTo-Digit
$evens = $evens | ForEach-Object {[Char]::GetNumericValue($_)}
}
else
{
$odds = $odds | ForEach-Object {[Char]::GetNumericValue($_)}
$evens = $evens | ForEach-Object {[Char]::GetNumericValue($_) * 2} | ConvertTo-Digit
}
$sum = ($odds | Measure-Object -Sum).Sum + ($evens | Measure-Object -Sum).Sum
(10 - ($sum % 10)) % 10 -match $checkDigit
}
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | VanDerCorput[n_,base_:2]:=Table[
FromDigits[{Reverse[IntegerDigits[k,base]],0},base],
{k,n}]
VanDerCorput[10,2]
VanDerCorput[10,3]
VanDerCorput[10,4]
VanDerCorput[10,5]
|
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function x = corput (n)
b = dec2bin(1:n)-'0'; % generate sequence of binary numbers from 1 to n
l = size(b,2); % get number of binary digits
w = (1:l)-l-1; % 2.^w are the weights
x = b * ( 2.^w'); % matrix times vector multiplication for
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á".
| #FreeBASIC | FreeBASIC |
Const alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"
Function ToDecimal (cadena As String, base_ As Uinteger) As Uinteger
Dim As Uinteger i, n, result = 0
Dim As Uinteger inlength = Len(cadena)
For i = 1 To inlength
n = Instr(alphanum, Mid(Lcase(cadena),i,1)) - 1
n *= (base_^(inlength-i))
result += n
Next
Return result
End Function
Function url2string(cadena As String) As String
Dim As String c, nc, res
For j As Integer = 1 To Len(cadena)
c = Mid(cadena, j, 1)
If c = "%" Then
nc = Chr(ToDecimal((Mid(cadena, j+1, 2)), 16))
res &= nc
j += 2
Else
res &= c
End If
Next j
Return res
End Function
Dim As String URL = "http%3A%2F%2Ffoo%20bar%2F"
Print "Supplied URL '"; URL; "'"
Print "URL decoding '"; url2string(URL); "'"
URL = "google.com/search?q=%60Abdu%27l-Bah%C3%A1"
Print !"\nSupplied URL '"; URL; "'"
Print "URL decoding '"; url2string(URL); "'"
Sleep
|
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.
| #C.2B.2B | C++ | #include <iostream>
#include <locale>
#include <map>
#include <vector>
std::string trim(const std::string &str) {
auto s = str;
//rtrim
auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(it1.base(), s.end());
//ltrim
auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(s.begin(), it2);
return s;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
const std::map<std::string, int> LEFT_DIGITS = {
{" ## #", 0},
{" ## #", 1},
{" # ##", 2},
{" #### #", 3},
{" # ##", 4},
{" ## #", 5},
{" # ####", 6},
{" ### ##", 7},
{" ## ###", 8},
{" # ##", 9}
};
const std::map<std::string, int> RIGHT_DIGITS = {
{"### # ", 0},
{"## ## ", 1},
{"## ## ", 2},
{"# # ", 3},
{"# ### ", 4},
{"# ### ", 5},
{"# # ", 6},
{"# # ", 7},
{"# # ", 8},
{"### # ", 9}
};
const std::string END_SENTINEL = "# #";
const std::string MID_SENTINEL = " # # ";
void decodeUPC(const std::string &input) {
auto decode = [](const std::string &candidate) {
using OT = std::vector<int>;
OT output;
size_t pos = 0;
auto part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = LEFT_DIGITS.find(part);
if (e != LEFT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, MID_SENTINEL.length());
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = RIGHT_DIGITS.find(part);
if (e != RIGHT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
int sum = 0;
for (size_t i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output[i];
} else {
sum += output[i];
}
}
return std::make_pair(sum % 10 == 0, output);
};
auto candidate = trim(input);
auto out = decode(candidate);
if (out.first) {
std::cout << out.second << '\n';
} else {
std::reverse(candidate.begin(), candidate.end());
out = decode(candidate);
if (out.first) {
std::cout << out.second << " Upside down\n";
} else if (out.second.size()) {
std::cout << "Invalid checksum\n";
} else {
std::cout << "Invalid digit(s)\n";
}
}
}
int main() {
std::vector<std::string> barcodes = {
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
};
for (auto &barcode : barcodes) {
decodeUPC(barcode);
}
return 0;
} |
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
| #J | J | require 'regex strings'
normalize=:3 :0
seen=. a:
eol=. {:;y
t=. ''
for_line.<;._2;y do. lin=. deb line=.>line
if. '#'={.line do. t=.t,line,eol
elseif. ''-:lin do. t =. t,eol
elseif. do.
line=. 1 u:([-.-.)&(32+i.95)&.(3&u:) line
base=. ('^ *;;* *';'') rxrplc line
nm=. ;name=. {.;:toupper base
if. -. name e. seen do.
seen=. seen, name
t=. t,eol,~dtb ('; '#~';'={.lin),(('^(?i) *',nm,'\b *');(nm,' ')) rxrplc base
end.
end.
end.t
)
enable=:1 :0
(<m) 1!:2~ normalize (,y,{:);<@rxrplc~&(y;~'^; *(?i)',y,'\b');.2]1!:1<m
)
disable=:1 :0
(<m) 1!:2~ normalize (,'; ',y,{:);<@rxrplc~&(('; ',y);~'^ *(?i)',y,'\b');.2]1!:1<m
)
set=:1 :0
:
t=. 1!:1<m
pat=. '^ *(?i)',y,'\b.*'
upd=. y,' ',":x
(<m) 1!:2~ normalize (,upd,{:);<@rxrplc~&(pat;upd) t
) |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | input s:
!print\ s
!decode!utf-8 !read-line!stdin
local :astring input "Enter a string: "
true
while:
try:
to-num input "Enter the number 75000: "
/= 75000
catch value-error:
true |
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
| #EasyLang | EasyLang | write "Enter a string: "
a$ = input
print ""
repeat
write "Enter the number 75000: "
h = number input
print ""
until h = 75000
.
print a$ & " " & h |
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
| #HicEst | HicEst | CHARACTER string*100
DLG(Edit=string, Edit=num_value, Button='&OK', TItle='Enter 75000 for num_value')
WRITE(Messagebox, Name) "You entered", string, num_value |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
WOpen("size=800,800") | stop("Unable to open window")
WWrite("Enter a string:")
s := WRead()
WWrite("You entered ",image(s))
WWrite("Enter the integer 75000:")
i := WRead()
if i := integer(i) then
WWrite("You entered: ",i)
else
WWrite(image(i)," isn't an integer")
WDone()
end
link graphics |
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.
| #JavaScript | JavaScript |
/***************************************************************************\
|* Pure UTF-8 handling without detailed error reporting functionality. *|
|***************************************************************************|
|* utf8encode *|
|* < String character or UInt32 code point *|
|* > Uint8Array encoded_character *|
|* | ErrorString *|
|* *|
|* utf8encode takes a string or uint32 representing a single code point *|
|* as its argument and returns an array of length 1 up to 4 containing *|
|* utf8 code units representing that character. *|
|***************************************************************************|
|* utf8decode *|
|* < Unit8Array [highendbyte highmidendbyte lowmidendbyte lowendbyte] *|
|* > uint32 character *|
|* | ErrorString *|
|* *|
|* utf8decode takes an array of one to four uint8 representing utf8 code *|
|* units and returns a uint32 representing that code point. *|
\***************************************************************************/
const
utf8encode=
n=>
(m=>
m<0x80
?Uint8Array.from(
[ m>>0&0x7f|0x00])
:m<0x800
?Uint8Array.from(
[ m>>6&0x1f|0xc0,m>>0&0x3f|0x80])
:m<0x10000
?Uint8Array.from(
[ m>>12&0x0f|0xe0,m>>6&0x3f|0x80,m>>0&0x3f|0x80])
:m<0x110000
?Uint8Array.from(
[ m>>18&0x07|0xf0,m>>12&0x3f|0x80,m>>6&0x3f|0x80,m>>0&0x3f|0x80])
:(()=>{throw'Invalid Unicode Code Point!'})())
( typeof n==='string'
?n.codePointAt(0)
:n&0x1fffff),
utf8decode=
([m,n,o,p])=>
m<0x80
?( m&0x7f)<<0
:0xc1<m&&m<0xe0&&n===(n&0xbf)
?( m&0x1f)<<6|( n&0x3f)<<0
:( m===0xe0&&0x9f<n&&n<0xc0
||0xe0<m&&m<0xed&&0x7f<n&&n<0xc0
||m===0xed&&0x7f<n&&n<0xa0
||0xed<m&&m<0xf0&&0x7f<n&&n<0xc0)
&&o===o&0xbf
?( m&0x0f)<<12|( n&0x3f)<<6|( o&0x3f)<<0
:( m===0xf0&&0x8f<n&&n<0xc0
||m===0xf4&&0x7f<n&&n<0x90
||0xf0<m&&m<0xf4&&0x7f<n&&n<0xc0)
&&o===o&0xbf&&p===p&0xbf
?( m&0x07)<<18|( n&0x3f)<<12|( o&0x3f)<<6|( p&0x3f)<<0
:(()=>{throw'Invalid UTF-8 encoding!'})()
|
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.
| #Scala | Scala | /* Query.scala */
object Query {
def call(data: Array[Byte], length: Array[Int]): Boolean = {
val message = "Here am I"
val mb = message.getBytes("utf-8")
if (length(0) >= mb.length) {
length(0) = mb.length
System.arraycopy(mb, 0, data, 0, mb.length)
true
} else false
}
} |
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.
| #Tcl | Tcl | int Query (char * Data, size_t * Length) {
Tcl_Obj *arguments[2];
int code;
arguments[0] = Tcl_NewStringObj("Query", -1); /* -1 for "use up to zero byte" */
arguments[1] = Tcl_NewStringObj(Data, Length);
Tcl_IncrRefCount(arguments[0]);
Tcl_IncrRefCount(arguments[1]);
if (Tcl_EvalObjv(interp, 2, arguments, 0) != TCL_OK) {
/* Was an error or other exception; report here... */
Tcl_DecrRefCount(arguments[0]);
Tcl_DecrRefCount(arguments[1]);
return 0;
}
Tcl_DecrRefCount(arguments[0]);
Tcl_DecrRefCount(arguments[1]);
if (Tcl_GetObjResult(NULL, Tcl_GetObjResult(interp), &code) != TCL_OK) {
/* Not an integer result */
return 0;
}
return code;
} |
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
| #PHP | PHP | <?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:[email protected]',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
} |
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
| #J | J | require'strings convert'
urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.) |
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
| #Java | Java | import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String normal = "http://foo bar/";
String encoded = URLEncoder.encode(normal, "utf-8");
System.out.println(encoded);
}
} |
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
| #Factor | Factor | SYMBOL: foo
: use-foo ( -- )
1 foo set
foo get 2 + foo set ! foo now = 3
foo get number>string print ;
:: named-param-example ( a b -- )
a b + number>string print ;
: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ; |
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
| #Falcon | Falcon |
/* partially created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
/* global and local scrope
from the Falcon survival
guide book */
// global scope
sqr = 1.41
function square( x )
// local scope
sqr = x * x
return sqr
end
number = square( 8 ) * sqr
a = [1, 2, 3] // array
b = 1 // variable declaration
e = 1.0 // float
f = "string" // string
/* There are plenty more
data types in Falcon */
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
TakeList[Nest[If[MemberQ[#//Most, #//Last], Join[#, Length[#] - Last@Position[#//Most, #//Last]], Append[#, 0]]&, {0}, 999], {10, -10}] // Column |
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.
| #Modula-2 | Modula-2 | MODULE VanEck;
FROM InOut IMPORT WriteCard, WriteLn;
VAR i, j: CARDINAL;
eck: ARRAY [1..1000] OF CARDINAL;
BEGIN
FOR i := 1 TO 1000 DO
eck[i] := 0;
END;
FOR i := 1 TO 999 DO
j := i-1;
WHILE (j > 0) AND (eck[i] <> eck[j]) DO
DEC(j);
END;
IF j <> 0 THEN
eck[i+1] := i-j;
END;
END;
FOR i := 1 TO 10 DO
WriteCard(eck[i], 4);
END;
WriteLn();
FOR i := 991 TO 1000 DO
WriteCard(eck[i], 4);
END;
WriteLn();
END VanEck. |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Ring | Ring |
# Project : Vampire number
for p = 10 to 127000
vampire(p)
next
func vampire(listnum)
sum = 0
flag = 1
list = list(len(string(listnum)))
total = newlist(len(list),2)
for n = 1 to len(string(listnum))
liststr = string(listnum)
list[n] = liststr[n]
next
for perm = 1 to fact(len(list))
numstr = substr(list2str(list), nl, "")
num1 = number(left(numstr,len(numstr)/2))
num2 = number(right(numstr,len(numstr)/2))
if (listnum = num1 * num2)
for n = 1 to len(total)
if (num1 = total[n][2] and num2 = total[n][1]) or
(num1 = total[n][1] and num2 = total[n][2])
flag = 0
ok
next
if flag = 1
sum = sum + 1
total[sum][1] = num1
total[sum][2] = num2
see "" + listnum + ": [" + num1 + "," + num2 + "]" + nl
ok
ok
nextPermutation(list)
next
func nextPermutation(a)
elementcount = len(a)
if elementcount < 1 then return ok
pos = elementcount-1
while a[pos] >= a[pos+1]
pos -= 1
if pos <= 0 permutationReverse(a, 1, elementcount)
return ok
end
last = elementcount
while a[last] <= a[pos]
last -= 1
end
temp = a[pos]
a[pos] = a[last]
a[last] = temp
permutationReverse(a, pos+1, elementcount)
func permutationReverse a, first, last
while first < last
temp = a[first]
a[first] = a[last]
a[last] = temp
first += 1
last -= 1
end
func fact(nr)
if nr = 1
return 1
else
return nr * fact(nr-1)
ok
func newlist(x,y)
if isstring(x) x=0+x ok
if isstring(y) y=0+y ok
alist = list(x)
for t in alist
t = list(y)
next
return alist
|
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
| #Ruby | Ruby | def factor_pairs n
first = n / (10 ** (n.to_s.size / 2) - 1)
(first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact
end
def vampire_factors n
return [] if n.to_s.size.odd?
half = n.to_s.size / 2
factor_pairs(n).select do |a, b|
a.to_s.size == half && b.to_s.size == half &&
[a, b].count {|x| x%10 == 0} != 2 &&
"#{a}#{b}".chars.sort == n.to_s.chars.sort
end
end
i = vamps = 0
until vamps == 25
vf = vampire_factors(i += 1)
unless vf.empty?
puts "#{i}:\t#{vf}"
vamps += 1
end
end
[16758243290880, 24959017348650, 14593825548650].each do |n|
if (vf = vampire_factors n).empty?
puts "#{n} is not a vampire number!"
else
puts "#{n}:\t#{vf}"
end
end |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #PARI.2FGP | PARI/GP | f(a[..])=for(i=1,#a,print(a[i])) |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Pascal | Pascal | sub print_all {
foreach (@_) {
print "$_\n";
}
} |
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
| #VBScript | VBScript |
Function Encrypt(text,key)
text = OnlyCaps(text)
key = OnlyCaps(key)
j = 1
For i = 1 To Len(text)
ms = Mid(text,i,1)
m = Asc(ms) - Asc("A")
ks = Mid(key,j,1)
k = Asc(ks) - Asc("A")
j = (j Mod Len(key)) + 1
c = (m + k) Mod 26
c = Chr(Asc("A")+c)
Encrypt = Encrypt & c
Next
End Function
Function Decrypt(text,key)
key = OnlyCaps(key)
j = 1
For i = 1 To Len(text)
ms = Mid(text,i,1)
m = Asc(ms) - Asc("A")
ks = Mid(key,j,1)
k = Asc(ks) - Asc("A")
j = (j Mod Len(key)) + 1
c = (m - k + 26) Mod 26
c = Chr(Asc("A")+c)
Decrypt = Decrypt & c
Next
End Function
Function OnlyCaps(s)
For i = 1 To Len(s)
char = UCase(Mid(s,i,1))
If Asc(char) >= 65 And Asc(char) <= 90 Then
OnlyCaps = OnlyCaps & char
End If
Next
End Function
'testing the functions
orig_text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
orig_key = "vigenerecipher"
WScript.StdOut.WriteLine "Original: " & orig_text
WScript.StdOut.WriteLine "Key: " & orig_key
WScript.StdOut.WriteLine "Encrypted: " & Encrypt(orig_text,orig_key)
WScript.StdOut.WriteLine "Decrypted: " & Decrypt(Encrypt(orig_text,orig_key),orig_key)
|
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Fortran | Fortran | program VectorProducts
real, dimension(3) :: a, b, c
a = (/ 3, 4, 5 /)
b = (/ 4, 3, 5 /)
c = (/ -5, -12, -13 /)
print *, dot_product(a, b)
print *, cross_product(a, b)
print *, s3_product(a, b, c)
print *, v3_product(a, b, c)
contains
function cross_product(a, b)
real, dimension(3) :: cross_product
real, dimension(3), intent(in) :: a, b
cross_product(1) = a(2)*b(3) - a(3)*b(2)
cross_product(2) = a(3)*b(1) - a(1)*b(3)
cross_product(3) = a(1)*b(2) - b(1)*a(2)
end function cross_product
function s3_product(a, b, c)
real :: s3_product
real, dimension(3), intent(in) :: a, b, c
s3_product = dot_product(a, cross_product(b, c))
end function s3_product
function v3_product(a, b, c)
real, dimension(3) :: v3_product
real, dimension(3), intent(in) :: a, b, c
v3_product = cross_product(a, cross_product(b, c))
end function v3_product
end program VectorProducts |
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
| #PureBasic | PureBasic | EnableExplicit
Procedure.b Check_ISIN(*c.Character)
Define count.i=0, Idx.i=1, v.i=0, i.i
Dim s.i(24)
If MemoryStringLength(*c) > 12 : ProcedureReturn #False : EndIf
While *c\c
count+1
If *c\c>='0' And *c\c<='9'
If count<=2 : ProcedureReturn #False : EndIf
s(Idx)= *c\c - '0'
Idx+1
ElseIf *c\c>='A' And *c\c<='Z'
s(Idx)= (*c\c - ('A'-10)) / 10
Idx+1
s(Idx)= (*c\c - ('A'-10)) % 10
Idx+1
Else
ProcedureReturn #False
EndIf
*c + SizeOf(Character)
Wend
For i=Idx-2 To 0 Step -2
If s(i)*2 > 9
v+ s(i)*2 -9
Else
v+ s(i)*2
EndIf
v+s(i+1)
Next
ProcedureReturn Bool(v%10=0)
EndProcedure
Define.s s
OpenConsole("Validate_International_Securities_Identification_Number (ISIN)")
If ReadFile(0,"c:\code_pb\rosettacode\data\isin.txt")
While Not Eof(0)
s=ReadString(0)
Print(s+~"\t")
If Check_ISIN(@s) : PrintN("TRUE") : Else : PrintN("FALSE") : EndIf
Wend
CloseFile(0)
EndIf
Input() |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Maxima | Maxima | /* convert a decimal integer to a list of digits in base `base' */
dec2digits(d, base):= block([digits: []],
while (d>0) do block([newdi: mod(d, base)],
digits: cons(newdi, digits),
d: round( (d - newdi) / base)),
digits)$
dec2digits(123, 10);
/* [1, 2, 3] */
dec2digits( 8, 2);
/* [1, 0, 0, 0] */ |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Modula-2 | Modula-2 | MODULE Sequence;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE vc(n,base : INTEGER; VAR num,denom : INTEGER);
VAR p,q : INTEGER;
BEGIN
p := 0;
q := 1;
WHILE n#0 DO
p := p * base + (n MOD base);
q := q * base;
n := n DIV base
END;
num := p;
denom := q;
WHILE p#0 DO
n := p;
p := q MOD p;
q := n
END;
num := num DIV q;
denom := denom DIV q
END vc;
VAR
buf : ARRAY[0..31] OF CHAR;
d,n,i,b : INTEGER;
BEGIN
FOR b:=2 TO 5 DO
FormatString("base %i:", buf, b);
WriteString(buf);
FOR i:=0 TO 9 DO
vc(i,b,n,d);
IF n#0 THEN
FormatString(" %i/%i", buf, n, d);
WriteString(buf)
ELSE
WriteString(" 0")
END
END;
WriteLn
END;
ReadChar
END Sequence. |
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á".
| #Frink | Frink | URLDecode["google.com/search?q=%60Abdu%27l-Bah%C3%A1","UTF8"] |
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á".
| #Go | Go | package main
import (
"fmt"
"log"
"net/url"
)
func main() {
for _, escaped := range []string{
"http%3A%2F%2Ffoo%20bar%2F",
"google.com/search?q=%60Abdu%27l-Bah%C3%A1",
} {
u, err := url.QueryUnescape(escaped)
if err != nil {
log.Println(err)
continue
}
fmt.Println(u)
}
} |
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.
| #D | D | import std.algorithm : countUntil, each, map;
import std.array : array;
import std.conv : to;
import std.range : empty, retro;
import std.stdio : writeln;
import std.string : strip;
import std.typecons : tuple;
immutable LEFT_DIGITS = [
" ## #",
" ## #",
" # ##",
" #### #",
" # ##",
" ## #",
" # ####",
" ### ##",
" ## ###",
" # ##"
];
immutable RIGHT_DIGITS = LEFT_DIGITS.map!`a.map!"a == '#' ? ' ' : '#'".array`.array;
immutable END_SENTINEL = "# #";
immutable MID_SENTINEL = " # # ";
void decodeUPC(string input) {
auto decode(string candidate) {
int[] output;
size_t pos = 0;
auto next = pos + END_SENTINEL.length;
auto part = candidate[pos .. next];
if (part == END_SENTINEL) {
pos = next;
} else {
return tuple(false, cast(int[])[]);
}
foreach (_; 0..6) {
next = pos + 7;
part = candidate[pos .. next];
auto i = countUntil(LEFT_DIGITS, part);
if (i >= 0) {
output ~= i;
pos = next;
} else {
return tuple(false, cast(int[])[]);
}
}
next = pos + MID_SENTINEL.length;
part = candidate[pos .. next];
if (part == MID_SENTINEL) {
pos = next;
} else {
return tuple(false, cast(int[])[]);
}
foreach (_; 0..6) {
next = pos + 7;
part = candidate[pos .. next];
auto i = countUntil(RIGHT_DIGITS, part);
if (i >= 0) {
output ~= i;
pos = next;
} else {
return tuple(false, cast(int[])[]);
}
}
next = pos + END_SENTINEL.length;
part = candidate[pos .. next];
if (part == END_SENTINEL) {
pos = next;
} else {
return tuple(false, cast(int[])[]);
}
int sum = 0;
foreach (i,v; output) {
if (i % 2 == 0) {
sum += 3 * v;
} else {
sum += v;
}
}
return tuple(sum % 10 == 0, output);
}
auto candidate = input.strip;
auto output = decode(candidate);
if (output[0]) {
writeln(output[1]);
} else {
output = decode(candidate.retro.array.to!string);
if (output[0]) {
writeln(output[1], " Upside down");
} else if (output[1].empty) {
writeln("Invalid digit(s)");
} else {
writeln("Invalid checksum", output);
}
}
}
void main() {
auto barcodes = [
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
];
barcodes.each!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
| #Java | Java | import java.io.*;
import java.util.*;
import java.util.regex.*;
public class UpdateConfig {
public static void main(String[] args) {
if (args[0] == null) {
System.out.println("filename required");
} else if (readConfig(args[0])) {
enableOption("seedsremoved");
disableOption("needspeeling");
setOption("numberofbananas", "1024");
addOption("numberofstrawberries", "62000");
store();
}
}
private enum EntryType {
EMPTY, ENABLED, DISABLED, COMMENT
}
private static class Entry {
EntryType type;
String name, value;
Entry(EntryType t, String n, String v) {
type = t;
name = n;
value = v;
}
}
private static Map<String, Entry> entries = new LinkedHashMap<>();
private static String path;
private static boolean readConfig(String p) {
path = p;
File f = new File(path);
if (!f.exists() || f.isDirectory())
return false;
String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)";
Pattern regex = Pattern.compile(regexString);
try (Scanner sc = new Scanner(new FileReader(f))){
int emptyLines = 0;
String line;
while (sc.hasNext()) {
line = sc.nextLine().trim();
if (line.isEmpty()) {
addOption("" + emptyLines++, null, EntryType.EMPTY);
} else if (line.charAt(0) == '#') {
entries.put(line, new Entry(EntryType.COMMENT, line, null));
} else {
line = line.replaceAll("[^a-zA-Z0-9\\x20;]", "");
Matcher m = regex.matcher(line);
if (m.find() && !m.group(2).isEmpty()) {
EntryType t = EntryType.ENABLED;
if (!m.group(1).isEmpty())
t = EntryType.DISABLED;
addOption(m.group(2), m.group(3), t);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return true;
}
private static void addOption(String name, String value) {
addOption(name, value, EntryType.ENABLED);
}
private static void addOption(String name, String value, EntryType t) {
name = name.toUpperCase();
entries.put(name, new Entry(t, name, value));
}
private static void enableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.ENABLED;
}
private static void disableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.DISABLED;
}
private static void setOption(String name, String value) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.value = value;
}
private static void store() {
try (PrintWriter pw = new PrintWriter(path)) {
for (Entry e : entries.values()) {
switch (e.type) {
case EMPTY:
pw.println();
break;
case ENABLED:
pw.format("%s %s%n", e.name, e.value);
break;
case DISABLED:
pw.format("; %s %s%n", e.name, e.value);
break;
case COMMENT:
pw.println(e.name);
break;
default:
break;
}
}
if (pw.checkError()) {
throw new IOException("writing to file failed");
}
} catch (IOException e) {
System.out.println(e);
}
}
} |
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
| #Elena | Elena | import extensions;
public program()
{
var num := new Integer();
console.write:"Enter an integer: ".loadLineTo:num;
var word := console.write:"Enter a String: ".readLine()
} |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Elixir | Elixir |
a = IO.gets("Enter a string: ") |> String.strip
b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer
f = IO.gets("Enter a real number: ") |> String.strip |> String.to_float
IO.puts "String = #{a}"
IO.puts "Integer = #{b}"
IO.puts "Float = #{f}"
|
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
| #J | J | SIMPLEGUI=: noun define
pc simpleGui;
cc IntegerLabel static;cn "Enter the integer 75000";
cc integer edit;
cc TextLabel static;cn "Enter text";
cc text edit;
cc accept button;cn "Accept";
pshow;
)
simpleGui_run=: wd bind SIMPLEGUI
simpleGui_close=: wd bind 'pclose'
simpleGui_cancel=: simpleGui_close
simpleGui_accept_button=: verb define
ttxt=. text
tint=. _". integer
if. tint ~: 75000 do.
wdinfo 'Integer entered was not 75000.'
else.
simpleGui_close ''
'simpleGui_text simpleGui_integer'=: ttxt;tint
end.
)
simpleGui_run'' |
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.
| #jq | jq | # input: a decimal integer
# output: the corresponding binary array, most significant bit first
def binary_digits:
if . == 0 then 0
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2]
| reverse
| .[1:] # remove the leading 0
end ;
# Input: an array of binary digits, msb first.
def binary_to_decimal:
reduce reverse[] as $b ({power:1, result:0};
.result += .power * $b
| .power *= 2)
| .result; |
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.
| #Julia | Julia | for t in ("A", "ö", "Ж", "€", "𝄞")
enc = Vector{UInt8}(t)
dec = String(enc)
println(dec, " → ", enc)
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.
| #TXR | TXR | #include <stdio.h>
int query(int (*callback)(char *, size_t *))
{
char buffer[1024];
size_t size = sizeof buffer;
if (callback(buffer, &size) == 0) {
puts("query: callback failed");
} else {
char *ptr = buffer;
while (size-- > 0)
putchar (*ptr++);
putchar('\n');
}
} |
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.
| #Wren | Wren | /* query.wren */
class RCQuery {
// Both arguments are lists as we need pass by reference here
static query(Data, Length) {
var s = "Here am I"
var sc = s.count
if (sc > Length[0]) return 0 // buffer too small
for (i in 0...sc) Data[i] = s[i].bytes[0]
Length[0] = sc
return 1
}
} |
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
| #PowerShell | PowerShell |
function Get-ParsedUrl
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[System.Uri]
$InputObject
)
Process
{
foreach ($url in $InputObject)
{
$url | Select-Object -Property Scheme,
@{Name="Domain"; Expression={$_.Host}},
Port,
@{Name="Path" ; Expression={$_.LocalPath}},
Query,
Fragment,
AbsolutePath,
AbsoluteUri,
Authority,
HostNameType,
IsDefaultPort,
IsFile,
IsLoopback,
PathAndQuery,
Segments,
IsUnc,
OriginalString,
DnsSafeHost,
IdnHost,
IsAbsoluteUri,
UserEscaped,
UserInfo
}
}
}
|
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
| #JavaScript | JavaScript | var normal = 'http://foo/bar/';
var encoded = encodeURIComponent(normal); |
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
| #jq | jq | "á" | @uri |
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
| #Forth | Forth | : hypot ( a b -- a^2 + b^2 )
LOCALS| b a | \ note: reverse order from the conventional stack comment
b b * a a * + ; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.