task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #PicoLisp | PicoLisp | (de urlEncodeTooMuch (Str)
(pack
(mapcar
'((C)
(if (or (>= "9" C "0") (>= "Z" (uppc C) "A"))
C
(list '% (hex (char C))) ) )
(chop Str) ) ) ) |
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
| #M2000_Interpreter | M2000 Interpreter |
\\ M2000 use inference to state the type of a new variable, at run time
\\ We can use literals of a numeric type
\\ @ for Decimal
\\ # for Currency
\\ ~ for Single
\\ & for Long (32bit)
\\ % for Integer (16bit)
\\ Double and Boolean have no symboles
Module TopA {
Module Alfa {
Print A=10000, Type$(A)="Double"
\\ A is local, we use =
A=10@
Print A=10, Type$(A)
\\ Or we can state the type before
Def Currency K, Z=500, M
K=1000
\\ Currency Currency Currency
Print Type$(K), Type$(Z), Type$(M)
Def Double K1, K2 as Integer=10, K3=1
\\ double integer double
Print Type$(K1), Type$(K2), Type$(K3)
Mb=1=1
\\ We get a boolean
Print Type$(Mb)
Def boolean Mb1=True
Print Type$(Mb1)
\\ True and False are Double -1 and 0 not Boolean
Mb3=True
Print Type$(Mb3)="Double"
\\ For strings we have to use $ (like in old Basic)
A$="This is a String"
Global G1 as boolean = True
\\ To change a global variable we have to use <=
G1<=1=0
\\ If we do this: G1=1=0 we make a local variable, and shadow global
\\ In a For Object {} we can make temporary variables
For This {
Local G1=122.1212
Print G1, Type$(G1)="Double"
}
Print G1, Type$(G1)="Boolean"
}
\\ shadow A for this module only
A=100
\\ Now we call Alfa
Alfa
Print (A=100)=True
}
Global A=10000
TopA
Print A=10000
Module CheckStatic {
\\ clear static variables and variables (for this module)
Clear
Module K {
\\ if no A exist created with value 100@
\\ Static variables can't be referenced
Static A=100@
Print A, Type$(A)="Decimal"
A++
}
For i=1 to 10 : K : Next i
Print A=10000
}
CheckStatic
Print A=10000
\\ reference and use of stack of values
C=100&
Module ChangeC {
\\ we leave arguments in stack of values
Module HereChangeC (&f) {
\\ interpreter execute a Read &f
f++
}
\\ now we call HereChangeC passing current stack of values
HereChangeC
}
\\ Calling a module done without checking for what parameters a module take
ChangeC &C
Print C, Type$(C)="Long"
K=10010001001@
ChangeC &K
Print K, Type$(K)="Decimal"
Module TypeRef (&x as Double) {
Print x
x++
}
D=100
TypeRef &D
Try ok {
TypeRef &K
}
If Error or Not Ok then Print Error$ ' we get wrong data type
|
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
| #Maple | Maple | a := 1:
print ("a is "||a);
"a is 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.
| #zkl | zkl | fcn vanEck(startAt=0){ // --> iterator
(startAt).walker(*).tweak(fcn(n,seen,rprev){
prev,t := rprev.value, n - seen.find(prev,n);
seen[prev] = n;
rprev.set(t);
t
}.fp1(Dictionary(),Ref(startAt))).push(startAt)
} |
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
| #Unicon | Unicon | f = %gP*=
#show+
main = f <'foo',12.5,('x','y'),100> |
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
| #Ursala | Ursala | f = %gP*=
#show+
main = f <'foo',12.5,('x','y'),100> |
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
| #V | V | [myfn
[zero? not] [swap puts pred]
while
].
100 200 300 400 500 3 myfn |
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
| #Kotlin | Kotlin | // version 1.1.2
class Vector3D(val x: Double, val y: Double, val z: Double) {
infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z
infix fun cross(v: Vector3D) =
Vector3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
fun scalarTriple(v: Vector3D, w: Vector3D) = this dot (v cross w)
fun vectorTriple(v: Vector3D, w: Vector3D) = this cross (v cross w)
override fun toString() = "($x, $y, $z)"
}
fun main(args: Array<String>) {
val a = Vector3D(3.0, 4.0, 5.0)
val b = Vector3D(4.0, 3.0, 5.0)
val c = Vector3D(-5.0, -12.0, -13.0)
println("a = $a")
println("b = $b")
println("c = $c")
println()
println("a . b = ${a dot b}")
println("a x b = ${a cross b}")
println("a . b x c = ${a.scalarTriple(b, c)}")
println("a x b x c = ${a.vectorTriple(b, c)}")
} |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #zkl | zkl | fcn validateISIN(isin){
RegExp(String("^","[A-Z]"*2,"[A-Z0-9]"*9,"[0-9]$")).matches(isin) and
luhnTest(isin.split("").apply("toInt",36).concat().toInt())
}
fcn luhnTest(n){
0 == (n.split().reverse().reduce(fcn(s,n,clk){
s + if(clk.inc()%2) n else 2*n%10 + n/5 },0,Ref(1)) %10)
} |
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
| #Tcl | Tcl | proc digitReverse {n {base 2}} {
set n [expr {[set neg [expr {$n < 0}]] ? -$n : $n}]
set result 0.0
set bit [expr {1.0 / $base}]
for {} {$n > 0} {set n [expr {$n / $base}]} {
set result [expr {$result + $bit * ($n % $base)}]
set bit [expr {$bit / $base}]
}
return [expr {$neg ? -$result : $result}]
} |
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
| #VBA | VBA | Private Function vdc(ByVal n As Integer, BASE As Variant) As Variant
Dim res As String
Dim digit As Integer, g As Integer, denom As Integer
denom = 1
Do While n
denom = denom * BASE
digit = n Mod BASE
n = n \ BASE
res = res & CStr(digit) '+ "0"
Loop
vdc = IIf(Len(res) = 0, "0", "0." & res)
End Function
Public Sub show_vdc()
Dim v As Variant, j As Integer
For i = 2 To 5
Debug.Print "Base "; i; ": ";
For j = 0 To 9
v = vdc(j, i)
Debug.Print v; " ";
Next j
Debug.Print
Next i
End Sub |
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á".
| #Objective-C | Objective-C | NSString *encoded = @"http%3A%2F%2Ffoo%20bar%2F";
NSString *normal = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", normal); |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #OCaml | OCaml | $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.decode "http%3A%2F%2Ffoo%20bar%2F" ;;
- : string = "http://foo bar/" |
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.
| #Racket | Racket | #lang racket
;; inspired by Kotlin
(define (is-#? c) (char=? c #\#))
(define left-digits
(for/hash ((i (in-naturals))
(c '((#f #f #t #t #f)
(#f #t #t #f #f)
(#f #t #f #f #t)
(#t #t #t #t #f)
(#t #f #f #f #t)
(#t #t #f #f #f)
(#t #f #t #t #t)
(#t #t #t #f #t)
(#t #t #f #t #t)
(#f #f #t #f #t))))
(values `(#f ,@c #t) i)))
(define right-digits (for/hash (([k v] left-digits)) (values (map not k) v)))
(define (lookup-blocks bits hsh fail)
(let recur ((bs bits) (r null))
(if (null? bs)
(reverse r)
(let-values (((bs′ tl) (split-at bs 7)))
(let ((d (hash-ref hsh bs′ (λ () (fail (list 'not-found bs′))))))
(recur tl (cons d r)))))))
(define (extract-blocks b fail)
(let*-values
(((e-l-m-r-e) (map is-#? (string->list (string-trim b))))
((_) (unless (= (length e-l-m-r-e) (+ 3 (* 7 6) 5 (* 7 6) 3))
(fail 'wrong-length)))
((e l-m-r-e) (split-at e-l-m-r-e 3))
((_) (unless (equal? e '(#t #f #t)) (fail 'left-sentinel)))
((l-m-r e) (split-at-right l-m-r-e 3))
((_) (unless (equal? e '(#t #f #t)) (fail 'right-sentinel)))
((l m-r) (split-at l-m-r 42))
((m r) (split-at m-r 5))
((_) (unless (equal? m '(#f #t #f #t #f)) (fail 'mid-sentinel))))
(values l r)))
(define (upc-checksum? ds)
(zero? (modulo (for/sum ((m (in-cycle '(3 1))) (d ds)) (* m d)) 10)))
(define (lookup-digits l r fail (transform values))
(let/ec fail-lookups
(define ds (append (lookup-blocks l left-digits (λ _ (fail-lookups #f)))
(lookup-blocks r right-digits (λ _ (fail-lookups #f)))))
(if (upc-checksum? ds)
(transform ds)
(fail (list 'checksum (transform ds))))))
(define (decode-upc barcode upside-down fail)
(define-values (l r) (extract-blocks barcode fail))
(or (lookup-digits l r fail)
(lookup-digits (reverse r) (reverse l) fail upside-down)))
(define (report-upc barcode)
(displayln (decode-upc barcode
(λ (v) (cons 'upside-down v))
(λ (e) (format "invalid: ~s" e)))))
(define (UPC)
(for-each report-upc
'(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # "
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # "
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # "
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # "
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # "
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # "
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # "
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # "
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # "
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
; first element again, with corrupted second digit
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ")))
(module+ main (UPC)) |
http://rosettacode.org/wiki/Update_a_configuration_file | Update a configuration file | We have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines begininning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# The first word on each non comment line is the configuration option.
# Remaining words or numbers on the line are configuration parameter
# data fields.
# Note that configuration option names are not case sensitive. However,
# configuration parameter data is case sensitive and the lettercase must
# be preserved.
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# How many bananas we have
NUMBEROFBANANAS 48
The task is to manipulate the configuration file as follows:
Disable the needspeeling option (using a semicolon prefix)
Enable the seedsremoved option by removing the semicolon and any leading whitespace
Change the numberofbananas parameter to 1024
Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000
Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case.
Options should always be disabled by prefixing them with a semicolon.
Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file.
If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry.
For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.)
The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons).
Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single
space, and any non-ASCII extended characters, tabs characters, or control codes
(other than end of line markers), should also be removed.
Related tasks
Read a configuration file
| #Wren | Wren | import "io" for File
import "/ioutil" for FileUtil
import "/dynamic" for Tuple
import "/str" for Str
var fields = ["favouriteFruit", "needsPeeling", "seedsRemoved", "numberOfBananas", "numberOfStrawberries"]
var ConfigData = Tuple.create("ConfigData", fields)
var updateConfigFile = Fn.new { |fileName, cData|
var lines = File.read(fileName).trimEnd().split(FileUtil.lineBreak)
var tempFileName = "temp_%(fileName)"
var out = File.create(tempFileName)
var hadFruit = false
var hadPeeling = false
var hadSeeds = false
var hadBananas = false
var hadStrawberries = false
for (line in lines) {
var cont = false
if (line.isEmpty || line[0] == "#") {
out.writeBytes(line + "\n")
cont = true
}
if (!cont) {
var ln = Str.upper(line.trimStart(";").trim())
if (!ln.isEmpty) {
if (ln.take(14).join() == "FAVOURITEFRUIT") {
if (!hadFruit) {
hadFruit = true
out.writeBytes("FAVOURITEFRUIT %(cData.favouriteFruit)\n")
}
} else if (ln.take(12).join() == "NEEDSPEELING") {
if (!hadPeeling) {
hadPeeling = true
if (cData.needsPeeling) {
out.writeBytes("NEEDSPEELING\n")
} else {
out.writeBytes("; NEEDSPEELING\n")
}
}
} else if (ln.take(12).join() == "SEEDSREMOVED") {
if (!hadSeeds) {
hadSeeds = true
if (cData.seedsRemoved) {
out.writeBytes("SEEDSREMOVED\n")
} else {
out.writeBytes("; SEEDSREMOVED\n")
}
}
} else if (ln.take(15).join() == "NUMBEROFBANANAS") {
if (!hadBananas) {
hadBananas = true
out.writeBytes("NUMBEROFBANANAS %(cData.numberOfBananas)\n")
}
} else if (ln.take(20).join() == "NUMBEROFSTRAWBERRIES") {
if (!hadStrawberries) {
hadStrawberries = true
out.writeBytes("NUMBEROFSTRAWBERRIES %(cData.numberOfStrawberries)\n")
}
}
}
}
}
if (!hadFruit) {
out.writeBytes("FAVOURITEFRUIT %(cData.favouriteFruit)\n")
}
if (!hadPeeling) {
if (cData.needsPeeling) {
out.writeBytes("NEEDSPEELING\n")
} else {
out.writeBytes("; NEEDSPEELING\n")
}
}
if (!hadSeeds) {
if (cData.seedsRemoved) {
out.writeBytes("SEEDSREMOVED\n")
} else {
out.writeBytes("; SEEDSREMOVED\n")
}
}
if (!hadBananas) {
out.writeBytes("NUMBEROFBANANAS %(cData.numberOfBananas)\n")
}
if (!hadStrawberries) {
out.writeBytes("NUMBEROFSTRAWBERRIES %(cData.numberOfStrawberries)\n")
}
out.close()
FileUtil.move(tempFileName, fileName, true)
}
var fileName = "config.txt"
var cData = ConfigData.new("banana", false, true, 1024, 62000)
updateConfigFile.call(fileName, cData) |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Lasso | Lasso | #!/usr/bin/lasso9
define read_input(prompt::string) => {
local(string)
// display prompt
stdout(#prompt)
// the following bits wait until the terminal gives you back a line of input
while(not #string or #string -> size == 0) => {
#string = file_stdin -> readsomebytes(1024, 1000)
}
#string -> replace(bytes('\n'), bytes(''))
return #string -> asstring
}
local(
string,
number
)
// get string
#string = read_input('Enter the string: ')
// get number
#number = integer(read_input('Enter the number: '))
// deliver the result
stdoutnl(#string + ' (' + #string -> type + ') | ' + #number + ' (' + #number -> type + ')') |
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
| #Liberty_BASIC | Liberty BASIC | Input "Enter a string. ";string$
Input "Enter the value 75000.";num |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Python | Python | import Tkinter,tkSimpleDialog
root = Tkinter.Tk()
root.withdraw()
number = tkSimpleDialog.askinteger("Integer", "Enter a Number")
string = tkSimpleDialog.askstring("String", "Enter a String")
|
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Quackery | Quackery | $ \
import tkinter
import tkinter.simpledialog as tks
root = tkinter.Tk()
root.withdraw()
to_stack(tks.askinteger("Integer", "Enter a Number"))
string_to_stack(tks.askstring("String", "Enter a String"))
\ python
swap echo cr echo$ |
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.
| #Swift | Swift | import Foundation
func encode(_ scalar: UnicodeScalar) -> Data {
return Data(String(scalar).utf8)
}
func decode(_ data: Data) -> UnicodeScalar? {
guard let string = String(data: data, encoding: .utf8) else {
assertionFailure("Failed to convert data to a valid String")
return nil
}
assert(string.unicodeScalars.count == 1, "Data should contain one scalar!")
return string.unicodeScalars.first
}
for scalar in "AöЖ€𝄞".unicodeScalars {
let bytes = encode(scalar)
let formattedBytes = bytes.map({ String($0, radix: 16)}).joined(separator: " ")
let decoded = decode(bytes)!
print("character: \(decoded), code point: U+\(String(scalar.value, radix: 16)), \tutf-8: \(formattedBytes)")
}
|
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.
| #Tcl | Tcl | proc encoder int {
set u [format %c $int]
set bytes {}
foreach byte [split [encoding convertto utf-8 $u] ""] {
lappend bytes [format %02X [scan $byte %c]]
}
return $bytes
}
proc decoder bytes {
set str {}
foreach byte $bytes {
append str [format %c [scan $byte %x]]
}
return [encoding convertfrom utf-8 $str]
}
foreach test {0x0041 0x00f6 0x0416 0x20ac 0x1d11e} {
set res $test
lappend res [encoder $test] -> [decoder [encoder $test]]
puts $res
} |
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
| #Pike | Pike | Protocols.HTTP.uri_encode( "http://foo bar/" ); |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Powershell | Powershell |
[uri]::EscapeDataString('http://foo bar/')
http%3A%2F%2Ffoo%20bar%2F
|
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | x=value assign a value to the variable x
x=y=value assign a value to both x and y
x=. or Clear[x] remove any value assigned to x
lhs=rhs (immediate assignment) rhs is evaluated when the assignment is made
lhs:=rhs (delayed assignment) rhs is evaluated each time the value of lhs is requested |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | a = 4; % declare variable and initialize double value,
s = 'abc'; % string
i8 = int8(5); % signed byte
u8 = uint8(5); % unsigned byte
i16 = int16(5); % signed 2 byte
u16 = uint16(5); % unsigned 2 byte integer
i32 = int32(5); % signed 4 byte integer
u32 = uint32(5);% unsigned 4 byte integers
i64 = int64(5); % signed 8 byte integer
u64 = uint64(5);% unsigned 8 byte integer
f32 = float32(5); % single precision floating point number
f64 = float64(5); % double precision floating point number , float 64 is the default data type.
c = 4+5i; % complex number
colvec = [1;2;4]; % column vector
crowvec = [1,2,4]; % row vector
m = [1,2,3;4,5,6]; % matrix with size 2x3 |
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
| #Visual_Basic | Visual Basic | Option Explicit
'--------------------------------------------------
Sub varargs(ParamArray a())
Dim n As Long, m As Long
Debug.Assert VarType(a) = (vbVariant Or vbArray)
For n = LBound(a) To UBound(a)
If IsArray(a(n)) Then
For m = LBound(a(n)) To UBound(a(n))
Debug.Print a(n)(m)
Next m
Else
Debug.Print a(n)
End If
Next
End Sub
'--------------------------------------------------
Sub Main()
Dim v As Variant
Debug.Print "call 1"
varargs 1, 2, 3
Debug.Print "call 2"
varargs 4, 5, 6, 7, 8
v = Array(9, 10, 11)
Debug.Print "call 3"
varargs v
ReDim v(0 To 2)
v(0) = 12
v(1) = 13
v(2) = 14
Debug.Print "call 4"
varargs 11, v
Debug.Print "call 5"
varargs v(2), v(1), v(0), 11
End Sub |
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
| #Vlang | Vlang | fn print_all(things ...string) {
for x in things {
println(x)
}
} |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Ksh | Ksh |
#!/bin/ksh
# Vector products
# # dot product (a scalar quantity) A • B = a1b1 + a2b2 + a3b3 + ...
# # cross product (a vector quantity) A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
# # scalar triple product (a scalar quantity) A • (B x C)
# # vector triple product (a vector quantity) A x (B x C)
# # Variables:
#
typeset -a A=( 3 4 5 )
typeset -a B=( 4 3 5 )
typeset -a C=( -5 -12 -13 )
# # Functions:
#
# # Function _dotprod(vec1, vec2) - Return the (scalar) dot product of 2 vectors
#
function _dotprod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _i ; typeset -si _i
typeset _dotp ; integer _dotp=0
for ((_i=0; _i<${#_vec1[*]}; _i++)); do
(( _dotp+=(_vec1[_i] * _vec2[_i]) ))
done
echo ${_dotp}
}
# # Function _crossprod(vec1, vec2, vec) - Return the (vector) cross product of 2 vectors
#
function _crossprod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Output vector
_vec3+=( $(( _vec1[1]*_vec2[2] - _vec1[2]*_vec2[1] )) )
_vec3+=( $(( _vec1[2]*_vec2[0] - _vec1[0]*_vec2[2] )) )
_vec3+=( $(( _vec1[0]*_vec2[1] - _vec1[1]*_vec2[0] )) )
}
# # Function _scal3prod(vec1, vec2, vec3) - Return the (scalar) scalar triple product of 3 vectors
#
function _scal3prod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Input vector 3
typeset _vect ; typeset -a _vect # temp vector
_crossprod _vec2 _vec3 _vect # (B x C)
echo $(_dotprod _vec1 _vect) # A • (B x C)
}
# # Function _vect3prod(vec1, vec2, vec3, vec) - Return the (vector) vector triple product of 3 vectors
#
function _vect3prod {
typeset _vec1 ; nameref _vec1="$1" # Input vector 1
typeset _vec2 ; nameref _vec2="$2" # Input vector 2
typeset _vec3 ; nameref _vec3="$3" # Input vector 3
typeset _vec4 ; nameref _vec4="$4" # Output vector
typeset _vect ; typeset -a _vect # temp vector
_crossprod _vec2 _vec3 _vect # (B x C)
_crossprod _vec1 _vect _vec4 # A x (B x C)
}
######
# main #
######
print "The dot product A • B = $(_dotprod A B)"
typeset -a arr
_crossprod A B arr
print "The cross product A x B = ( ${arr[@]} )"
print "The scalar triple product A • (B x C) = $(_scal3prod A B C)"
typeset -m crossprod=arr ; typeset -a arr
_vect3prod A B C arr
print "The vector triple product A x (B x C) = ( ${arr[@]} )"
|
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
| #VBScript | VBScript | 'http://rosettacode.org/wiki/Van_der_Corput_sequence
'Van der Corput Sequence fucntion call = VanVanDerCorput(number,base)
Base2 = "0" : Base3 = "0" : Base4 = "0" : Base5 = "0"
Base6 = "0" : Base7 = "0" : Base8 = "0" : Base9 = "0"
l = 1
h = 1
Do Until l = 9
'Set h to the value of l after each function call
'as it sets it to 0 - see lines 37 to 40.
Base2 = Base2 & ", " & VanDerCorput(h,2) : h = l
Base3 = Base3 & ", " & VanDerCorput(h,3) : h = l
Base4 = Base4 & ", " & VanDerCorput(h,4) : h = l
Base5 = Base5 & ", " & VanDerCorput(h,5) : h = l
Base6 = Base6 & ", " & VanDerCorput(h,6) : h = l
l = l + 1
Loop
WScript.Echo "Base 2: " & Base2
WScript.Echo "Base 3: " & Base3
WScript.Echo "Base 4: " & Base4
WScript.Echo "Base 5: " & Base5
WScript.Echo "Base 6: " & Base6
'Van der Corput Sequence
Function VanDerCorput(n,b)
k = RevString(Dec2BaseN(n,b))
For i = 1 To Len(k)
VanDerCorput = VanDerCorput + (CLng(Mid(k,i,1)) * b^-i)
Next
End Function
'Decimal to Base N Conversion
Function Dec2BaseN(q,c)
Dec2BaseN = ""
Do Until q = 0
Dec2BaseN = CStr(q Mod c) & Dec2BaseN
q = Int(q / c)
Loop
End Function
'Reverse String
Function RevString(s)
For j = Len(s) To 1 Step -1
RevString = RevString & Mid(s,j,1)
Next
End Function |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ToBase(n As Integer, b As Integer) As String
Dim result = ""
If b < 2 Or b > 16 Then
Throw New ArgumentException("The base is out of range")
End If
Do
Dim remainder = n Mod b
result = "0123456789ABCDEF"(remainder) + result
n = n \ b
Loop While n > 0
Return result
End Function
Sub Main()
For b = 2 To 5
Console.WriteLine("Base = {0}", b)
For i = 0 To 12
Dim s = "." + ToBase(i, b)
Console.Write("{0,6} ", s)
Next
Console.WriteLine()
Console.WriteLine()
Next
End Sub
End Module |
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á".
| #ooRexx | ooRexx | /* Rexx */
X = 0
url. = ''
X = X + 1; url.0 = X; url.X = 'http%3A%2F%2Ffoo%20bar%2F'
X = X + 1; url.0 = X; url.X = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E'
X = X + 1; url.0 = X; url.X = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E'
Do u_ = 1 to url.0
Say url.u_
Say DecodeURL(url.u_)
Say
End u_
Exit
DecodeURL: Procedure
Parse Arg encoded
decoded = ''
PCT = '%'
Do label e_ while encoded~length() > 0
Parse Var encoded head (PCT) +1 code +2 tail
decoded = decoded || head
Select
when code~strip('T')~length() = 2 & code~datatype('X') then Do
code = code~x2c()
decoded = decoded || code
End
when code~strip('T')~length() \= 0 then Do
decoded = decoded || PCT
tail = code || tail
End
otherwise
Nop
End
encoded = tail
End e_
Return decoded |
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á".
| #Perl | Perl | sub urldecode {
my $s = shift;
$s =~ tr/\+/ /;
$s =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/eg;
return $s;
}
print urldecode('http%3A%2F%2Ffoo+bar%2F')."\n";
|
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.
| #Raku | Raku | sub decode_UPC ( Str $line ) {
constant @patterns1 = ' ## #', ' ## #', ' # ##', ' #### #', ' # ##',
' ## #', ' # ####', ' ### ##', ' ## ###', ' # ##';
constant @patterns2 = @patterns1».trans( '#' => ' ', ' ' => '#' );
constant %pattern_to_digit_1 = @patterns1.antipairs;
constant %pattern_to_digit_2 = @patterns2.antipairs;
constant $re = / ^ '# #' (@patterns1) ** 6
' # # ' (@patterns2) ** 6
'# #' $ /;
$line.trim ~~ $re
orelse return;
my @digits = flat %pattern_to_digit_1{ $0».Str },
%pattern_to_digit_2{ $1».Str };
return unless ( @digits Z* ( |(3,1) xx * ) ).sum %% 10;
return @digits.join;
}
my @lines =
' # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ',
' # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ',
' # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ',
' # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ',
' # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ',
' # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ',
' # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ',
' # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ',
' # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ',
' # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ',
;
for @lines -> $line {
say decode_UPC($line)
// decode_UPC($line.flip)
// 'Invalid';
} |
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
| #LIL | LIL | # User input/text, in LIL
write "Enter a string: "
set text [readline]
set num 0
while {[canread] && $num != 75000} {
write "Enter the number 75000: "
set num [readline]
}
print $text
print $num |
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
| #Logo | Logo | make "input readlist ; in: string 75000
show map "number? :input ; [false true]
make "input readword ; in: 75000
show :input + 123 ; 75123
make "input readword ; in: string 75000
show :input ; string 75000 |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #R | R |
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
w <- gwindow("Enter a string and a number")
lyt <- glayout(cont=w)
lyt[1,1] <- "Enter a string"
lyt[1,2] <- gedit("", cont=lyt)
lyt[2,1] <- "Enter 75000"
lyt[2,2] <- gedit("", cont=lyt)
lyt[3,2] <- gbutton("validate", cont=lyt, handler=function(h,...) {
txt <- svalue(lyt[1,2])
x <- svalue(lyt[2,2])
x <- gsub(",", "", x)
x <- as.integer(x)
if(nchar(txt) > 0 && x == 75000)
gmessage("Congratulations, you followed directions", parent=w)
else
gmessage("You failed this simple task", parent=w)
})
|
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
| #Racket | Racket |
#lang racket
(require racket/gui)
(define str (get-text-from-user "Hi" "Enter a string"))
(message-box "Hi" (format "You entered: ~a" str))
(define n (get-text-from-user "Hi" "Enter a number"))
(message-box "Hi" (format "You entered: ~a"
(or (string->number n) "bogus text")))
|
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #VBA | VBA | Private Function unicode_2_utf8(x As Long) As Byte()
Dim y() As Byte
Dim r As Long
Select Case x
Case 0 To &H7F
ReDim y(0)
y(0) = x
Case &H80 To &H7FF
ReDim y(1)
y(0) = 192 + x \ 64
y(1) = 128 + x Mod 64
Case &H800 To &H7FFF
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case 32768 To 65535 '&H8000 To &HFFFF equals in VBA as -32768 to -1
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case &H10000 To &H10FFFF
ReDim y(3)
y(3) = 128 + x Mod 64
r = x \ 64
y(2) = 128 + r Mod 64
r = r \ 64
y(1) = 128 + r Mod 64
y(0) = 240 + r \ 64
Case Else
MsgBox "what else?" & x & " " & Hex(x)
End Select
unicode_2_utf8 = y
End Function
Private Function utf8_2_unicode(x() As Byte) As Long
Dim first As Long, second As Long, third As Long, fourth As Long
Dim total As Long
Select Case UBound(x) - LBound(x)
Case 0 'one byte
If x(0) < 128 Then
total = x(0)
Else
MsgBox "highest bit set error"
End If
Case 1 'two bytes and assume first byte is leading byte
If x(0) \ 32 = 6 Then
first = x(0) Mod 32
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
Else
MsgBox "mask error"
End If
Else
MsgBox "leading byte error"
End If
total = 64 * first + second
Case 2 'three bytes and assume first byte is leading byte
If x(0) \ 16 = 14 Then
first = x(0) Mod 16
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error middle byte"
End If
Else
MsgBox "leading byte error"
End If
total = 4096 * first + 64 * second + third
Case 3 'four bytes and assume first byte is leading byte
If x(0) \ 8 = 30 Then
first = x(0) Mod 8
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
If x(3) \ 64 = 2 Then
fourth = x(3) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error third byte"
End If
Else
MsgBox "mask error second byte"
End If
Else
MsgBox "mask error leading byte"
End If
total = CLng(262144 * first + 4096 * second + 64 * third + fourth)
Case Else
MsgBox "more bytes than expected"
End Select
utf8_2_unicode = total
End Function
Public Sub program()
Dim cp As Variant
Dim r() As Byte, s As String
cp = [{65, 246, 1046, 8364, 119070}] '[{&H0041,&H00F6,&H0416,&H20AC,&H1D11E}]
Debug.Print "ch unicode UTF-8 encoded decoded"
For Each cpi In cp
r = unicode_2_utf8(CLng(cpi))
On Error Resume Next
s = CStr(Hex(cpi))
Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s,
If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s,
s = ""
For Each yz In r
s = s & CStr(Hex(yz)) & " "
Next yz
Debug.Print String$(13 - Len(s), " "); s;
s = CStr(Hex(utf8_2_unicode(r)))
Debug.Print String$(8 - Len(s), " "); s
Next cpi
End Sub |
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
| #PureBasic | PureBasic | URL$ = URLEncoder("http://foo bar/") |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Python | Python | import urllib
s = 'http://foo/bar/'
s = urllib.quote(s) |
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
| #Mercury | Mercury | :- func name = string.
name = Name :-
Name = Title ++ " " ++ Given,
Title = "Dr.",
Given = "Bob". |
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
| #Modula-3 | Modula-3 | MODULE Foo EXPORTS Main;
IMPORT IO, Fmt;
VAR foo: INTEGER := 5; (* foo is global (to the module). *)
PROCEDURE Foo() =
VAR bar: INTEGER := 10; (* bar is local to the procedure Foo. *)
BEGIN
IO.Put("foo + bar = " & Fmt.Int(foo + bar) & "\n");
END Foo;
BEGIN
Foo();
END Foo. |
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
| #Vorpal | Vorpal | self.f = method(x, y[ ], z){
x.print()
for(i = 0, i < y.size(), i = i + 1){
('[' + y[i] + ']').print()
}
z.print()
}
self.f(1, 2, 3)
'---'.print()
self.f(1, 2, 3, 4)
'---'.print()
self.f(1, 2) |
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
| #Wren | Wren | var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }
printArgs.call(["Mary", "had", "3", "little", "lambs"]) |
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
| #Lambdatalk | Lambdatalk |
{def dotProduct
{lambda {:a :b}
{+ {* {A.get 0 :a} {A.get 0 :b}}
{* {A.get 1 :a} {A.get 1 :b}}
{* {A.get 2 :a} {A.get 2 :b}}}}}
-> dotProduct
{def crossProduct
{lambda {:a :b}
{A.new {- {* {A.get 1 :a} {A.get 2 :b}}
{* {A.get 2 :a} {A.get 1 :b}}}
{- {* {A.get 2 :a} {A.get 0 :b}}
{* {A.get 0 :a} {A.get 2 :b}}}
{- {* {A.get 0 :a} {A.get 1 :b}}
{* {A.get 1 :a} {A.get 0 :b}}} }}}
-> crossProduct
{def A {A.new 3 4 5}} -> A = [3,4,5]
{def B {A.new 4 3 5}} -> B = [4,3,5]
{def C {A.new -5 -12 -13}} -> C = [4,3,5]
A.B : {dotProduct {A} {B}} -> 49
AxB : {crossProduct {A} {B}} -> [5,5,-7]
A.(BxC) : {dotProduct {A} {crossProduct {B} {C}}} -> 6
Ax(BxC) : {crossProduct {A} {crossProduct {B} {C}}} -> [-267,204,-3]
|
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
| #Vlang | Vlang | fn v2(nn u32) f64 {
mut n:=nn
mut r := f64(0)
mut p := .5
for n > 0 {
if n&1 == 1 {
r += p
}
p *= .5
n >>= 1
}
return r
}
fn new_v(base u32) fn(u32) f64 {
invb := 1 / f64(base)
return fn[base,invb](nn u32) f64 {
mut n:=nn
mut r := f64(0)
mut p := invb
for n > 0 {
r += p * f64(n%base)
p *= invb
n /= base
}
return r
}
}
fn main() {
println("Base 2:")
for i := u32(0); i < 10; i++ {
println('$i ${v2(i)}')
}
println("Base 3:")
v3 := new_v(3)
for i := u32(0); i < 10; i++ {
println('$i ${v3(i)}')
}
} |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #Wren | Wren | var v2 = Fn.new { |n|
var p = 0.5
var r = 0
while (n > 0) {
if (n%2 == 1) r = r + p
p = p / 2
n = (n/2).floor
}
return r
}
var newV = Fn.new { |base|
var invb = 1 / base
return Fn.new { |n|
var p = invb
var r = 0
while (n > 0) {
r = r + p*(n%base)
p = p * invb
n = (n/base).floor
}
return r
}
}
System.print("Base 2:")
for (i in 0..9) System.print("%(i) -> %(v2.call(i))")
System.print("\nBase 3:")
var v3 = newV.call(3)
for (i in 0..9) System.print("%(i) -> %(v3.call(i))") |
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á".
| #Phix | Phix | --
-- demo\rosetta\decode_url.exw
-- ===========================
--
with javascript_semantics
function decode_url(string s)
integer skip = 0
string res = ""
for i=1 to length(s) do
if skip then
skip -= 1
else
integer ch = s[i]
if ch='%' then
sequence scanres = {}
if i+2<=length(s) then
scanres = scanf("#"&s[i+1..i+2],"%x")
end if
if length(scanres)!=1 then
return "decode error"
end if
skip = 2
ch = scanres[1][1]
elsif ch='+' then
ch = ' '
end if
res &= ch
end if
end for
return res
end function
printf(1,"%s\n",{decode_url("http%3A%2F%2Ffoo%20bar%2F")})
printf(1,"%s\n",{decode_url("google.com/search?q=%60Abdu%27l-Bah%C3%A1")})
{} = wait_key()
|
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.
| #REXX | REXX | /*REXX program to read/interpret UPC symbols and translate them to a numberic string.*/
#.0= ' ## #'
#.1= ' ## #'
#.2= ' # ##'
#.3= ' #### #'
#.4= ' # ##'
#.5= ' ## #'
#.6= ' # ####'
#.7= ' ### ##'
#.8= ' ## ###' /* [↓] right─sided UPC digits.*/
#.9= ' # ##' ; do i=0 for 10; ##.i= translate(#.i, ' #', "# ")
end /*i*/
say center('UPC', 14, "─") ' ---'copies(1234567, 6)"-----"copies(1234567, 6)'---'
@.=.
@.1 = ' # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # '
@.2 = ' # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # '
@.3 = ' # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # '
@.4 = ' # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # '
@.5 = ' # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # '
@.6 = ' # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # '
@.7 = ' # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # '
@.8 = ' # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # '
@.9 = ' # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # '
@.10= ' # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # '
ends= '# #' /*define ENDS literal const*/
do j=1 while @.j\==.; $= @.j
txt= /*initialize TXT variable*/
if left($, 9)\='' | right($, 9)\='' then txt= 'bad blanks'
$= strip($); $$= $ /*elide blanks at ends of $*/
L= length($) /*obtain length of $ string*/
if left($, 3) \==ends | right($, 3) \==ends then txt= 'bad fence'
if L \== 95 & txt=='' then txt= 'bad length'
$= substr($, 4, L - length(ends)*2) /*elide "ends". */
$= delstr($, length($) % 2 - 1, 5) /* " middle. */
sum= 0 /*initialize SUM*/
if txt=='' then do k=1 for 12; parse var $ x +7 $ /*get UPC digit.*/
do d=0 for 10; if x==#.d | x==##.d then leave /*valid digit? */
end /*d*/
if d==10 & k \==12 then do; txt= 'reversed' ; leave; end
if d==10 then do; txt= 'bad digit'; leave; end
if k // 2 then sum= sum + d * 3 /*mult. by 3. */
else sum= sum + d /* " " 1. */
txt= txt || d
end /*k*/
if left(txt,1)\=="b" then if sum//10\==0 then txt= 'bad checksum' /*invalid sum? */
say center( strip(txt), 15) ' ' $$ /*show chksum (or err msg) with the UPC*/
end /*j*/ /*stick a fork in it, we're all done. */ |
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
| #Logtalk | Logtalk |
:- object(user_input).
:- public(test/0).
test :-
repeat,
write('Enter an integer: '),
read(Integer),
integer(Integer),
!,
repeat,
write('Enter an atom: '),
read(Atom),
atom(Atom),
!.
:- end_object.
|
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
| #LOLCODE | LOLCODE | HAI 1.4
I HAS A string
GIMMEH string
I HAS A number
GIMMEH number
BTW converts number input to an integer
MAEK number A NUMBR
KTHXBYE
|
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
| #Raku | Raku | use GTK::Simple;
use GTK::Simple::App;
my GTK::Simple::App $app .= new( title => 'User Interaction' );
$app.border-width = 20;
$app.set-content(
GTK::Simple::VBox.new(
my $ = GTK::Simple::Label.new( text => 'Enter a string.' ),
my $str = GTK::Simple::Entry.new,
my $string = GTK::Simple::Label.new,
my $ = GTK::Simple::Label.new( text => 'Enter the number 75000' ),
my $val = GTK::Simple::Entry.new,
my $correct = GTK::Simple::Label.new,
)
);
$str.changed.tap: {
$string.text = "You entered: { $str.text }"
}
$val.changed.tap: {
$correct.text = "That's { 'not' unless $val.text ~~ / ^^ <ws> 75000 <ws> $$ / } 75000!"
}
$app.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.
| #Vlang | Vlang | import encoding.hex
fn decode(s string) ?[]u8 {
return hex.decode(s)
}
fn main() {
println("${'Char':-7} ${'Unicode':7}\tUTF-8 encoded\tDecoded")
for codepoint in [`A`, `ö`, `Ж`, `€`, `𝄞`] {
encoded := codepoint.bytes().hex()
decoded := decode(encoded)?
println("${codepoint:-7} U+${codepoint:04X}\t${encoded:-12}\t${decoded.bytestr()}")
}
} |
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.
| #Wren | Wren | import "/fmt" for Fmt
var utf8_encode = Fn.new { |cp| String.fromCodePoint(cp).bytes.toList }
var utf8_decode = Fn.new { |b|
var mbMask = 0x3f // non-first bytes start 10 and carry 6 bits of data
var b0 = b[0]
if (b0 < 0x80) {
return b0
} else if (b0 < 0xe0) {
var b2Mask = 0x1f // first byte of a 2-byte encoding starts 110 and carries 5 bits of data
return (b0 & b2Mask) << 6 | (b[1] & mbMask)
} else if (b0 < 0xf0) {
var b3Mask = 0x0f // first byte of a 3-byte encoding starts 1110 and carries 4 bits of data
return (b0 & b3Mask) << 12 | (b[1] & mbMask) << 6 | (b[2] & mbMask)
} else {
var b4Mask = 0x07 // first byte of a 4-byte encoding starts 11110 and carries 3 bits of data
return (b0 & b4Mask) << 18 | (b[1] & mbMask) << 12 | (b[2] & mbMask) << 6 | (b[3] & mbMask)
}
}
var tests = [
["LATIN CAPITAL LETTER A", 0x41],
["LATIN SMALL LETTER O WITH DIAERESIS", 0xf6],
["CYRILLIC CAPITAL LETTER ZHE", 0x416],
["EURO SIGN", 0x20ac],
["MUSICAL SYMBOL G CLEF", 0x1d11e]
]
System.print("Character Name Unicode UTF-8 encoding (hex)")
System.print("---------------------------------------------------------------------------------")
for (test in tests) {
var cp = test[1]
var bytes = utf8_encode.call(cp)
var utf8 = bytes.map { |b| Fmt.Xz(2, b) }.join(" ")
var cp2 = utf8_decode.call(bytes)
var uni = String.fromCodePoint(cp2)
System.print("%(Fmt.s(-11, uni)) %(Fmt.s(-37, test[0])) U+%(Fmt.s(-8, Fmt.Xz(4, cp2))) %(utf8)")
} |
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
| #R | R | URLencode("http://foo bar/") |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Racket | Racket |
#lang racket
(require net/uri-codec)
(uri-encode "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
| #Nanoquery | Nanoquery | // variable definition and initialization/assignment
//
// variables are initialized when they are defined
a = 1
b = 2
c = null
// datatypes
//
// variables may contain any datatype, and this can be
// changed at any time by assigning a new value. they may
// also contain native java types
var = "a string"
var = 123
var = new(Nanoquery.Util.Random)
var = new(java.lang.Object)
// scope
//
// all classes, functions, and control blocks have their
// own scope
x = 5
for i in range(1, 2)
// we can reference 'x' within this loop without issue
println x
// we can also define variables that have this loop as their
// scope
y = 5
end
// trying to reference the variable 'y' outside of its scope would result
// in a null reference exception
println y
//%null reference exception: variable object 'y' has not been defined
// at <global>:33
// referencing
//
// as already demonstrated, variables are referenced by using their
// name
part1 = "this is "
part2 = "a test sentence"
println part1 + part2
// other facilities
//
// variables may be marked for garbage collection in their current
// scope using the 'delete' command
test_var = "pretend this is a really large object we want to free up"
delete test_var |
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
| #Nim | Nim | var x: int = 3 # Declaration with type specification and initialization.
var y = 3 # Declaration with type inferred to "int".
var z: int # Variable is initialized to 0.
let a = 13 # Immutable variable.
# Using a var block to initialize.
var
b, c: int = 10 # Two variables initialized to 10
s* = "foobar" # This one is exported.
type Obj = ref object
i: int
s: string
var obj = Obj(i: 3, s: "abc") # Initialization with an implicit allocation by "new".
echo obj.a, " ", obj.s # Equivalent to obj[].a and obj[].s.
proc p =
var xloc = 3
echo x # Referencing a global variable.
proc q =
echo xloc # Referencing a variable in the enclosing scope. |
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
| #XLISP | XLISP | (defun print-on-separate-lines (&rest xs)
(for-each print xs))
; test the function:
(print-on-separate-lines 'i 'am 'doing 'a 'great 'work 'so 'that 'i 'cannot 'come 'down)
; to use it on a list of arguments assembled at run time, first create your list
(define test '(why should the work cease whilst i leave it and come down to you))
; and then call APPLY:
(apply print-on-separate-lines test) |
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
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def IntSize=4; \number of bytes in an integer
proc Var(N...); \Display N strings passed as arguments
int N;
[N:= Reserve(N*IntSize); \reserve space for N string pointers
repeat Text(0,N(0)); CrLf(0); \display strings pointed to by N(0)
N:= N+IntSize; \point to next string
until N=GetHp; \pointing beyond reserved space?
];
Var(4, "Mary", "had", "a", "little") |
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
| #zkl | zkl | fcn f{vm.arglist.apply2("println")}
f("Mary","had","a","little"); |
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
| #Liberty_BASIC | Liberty BASIC | print "Vector products of 3-D vectors"
print "Dot product of 3,4,5 and 4,3,5 is "
print DotProduct( "3,4,5", "4,3,5")
print "Cross product of 3,4,5 and 4,3,5 is "
print CrossProduct$( "3,4,5", "4,3,5")
print "Scalar triple product of 3,4,5, 4,3,5 -5, -12, -13 is "
print ScalarTripleProduct( "3,4,5", "4,3,5", "-5, -12, -13")
print "Vector triple product of 3,4,5, 4,3,5 -5, -12, -13 is "
print VectorTripleProduct$( "3,4,5", "4,3,5", "-5, -12, -13")
end
function DotProduct( i$, j$)
ix =val( word$( i$, 1, ","))
iy =val( word$( i$, 2, ","))
iz =val( word$( i$, 3, ","))
jx =val( word$( j$, 1, ","))
jy =val( word$( j$, 2, ","))
jz =val( word$( j$, 3, ","))
DotProduct = ix *jx +iy *jy + iz *jz
end function
function CrossProduct$( i$, j$)
ix =val( word$( i$, 1, ","))
iy =val( word$( i$, 2, ","))
iz =val( word$( i$, 3, ","))
jx =val( word$( j$, 1, ","))
jy =val( word$( j$, 2, ","))
jz =val( word$( j$, 3, ","))
cpx =iy *jz -iz *jy
cpy =iz *jx -ix *jz
cpz =ix *jy -iy *jx
CrossProduct$ =str$( cpx); ","; str$( cpy); ","; str$( cpz)
end function
function ScalarTripleProduct( i$, j$, k$))
ScalarTripleProduct =DotProduct( i$, CrossProduct$( j$, k$))
end function
function VectorTripleProduct$( i$, j$, k$))
VectorTripleProduct$ =CrossProduct$( i$, CrossProduct$( j$, k$))
end function
END SUB |
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
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func real VdC(N); \Return Nth term of van der Corput sequence in base 2
int N;
real V, U;
[V:= 0.0; U:= 0.5;
repeat N:= N/2;
if rem(0) then V:= V+U;
U:= U/2.0;
until N=0;
return V;
];
int N;
for N:= 0 to 10-1 do
[IntOut(0, N); RlOut(0, VdC(N)); CrLf(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
| #zkl | zkl | fcn vdc(n,base=2){
vdc:=0.0; denom:=1;
while(n){ reg remainder;
denom *= base;
n, remainder = n.divr(base);
vdc += (remainder.toFloat() / denom);
}
vdc
} |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #PHP | PHP | <?php
$encoded = "http%3A%2F%2Ffoo%20bar%2F";
$unencoded = rawurldecode($encoded);
echo "The unencoded string is $unencoded !\n";
?> |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #PicoLisp | PicoLisp | : (ht:Pack (chop "http%3A%2F%2Ffoo%20bar%2F") T)
-> "http://foo bar/" |
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.
| #Ruby | Ruby | DIGIT_F = {
" ## #" => 0,
" ## #" => 1,
" # ##" => 2,
" #### #" => 3,
" # ##" => 4,
" ## #" => 5,
" # ####" => 6,
" ### ##" => 7,
" ## ###" => 8,
" # ##" => 9,
}
DIGIT_R = {
"### # " => 0,
"## ## " => 1,
"## ## " => 2,
"# # " => 3,
"# ### " => 4,
"# ### " => 5,
"# # " => 6,
"# # " => 7,
"# # " => 8,
"### # " => 9,
}
END_SENTINEL = "# #"
MID_SENTINEL = " # # "
def decode_upc(s)
def decode_upc_impl(input)
upc = input.strip
if upc.length != 95 then
return false
end
pos = 0
digits = []
sum = 0
# end sentinel
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
# 6 left hand digits
for i in 0 .. 5
digit = DIGIT_F[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
# mid sentinel
if upc[pos .. pos + 4] == MID_SENTINEL then
pos += 5
else
return false
end
# 6 right hand digits
for i in 0 .. 5
digit = DIGIT_R[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
# end sentinel
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
if sum % 10 == 0 then
print digits, " "
return true
else
print "Failed Checksum "
return false
end
end
if decode_upc_impl(s) then
puts "Rightside Up"
elsif decode_upc_impl(s.reverse) then
puts "Upside Down"
else
puts "Invalid digit(s)"
end
end
def main
num = 0
print "%2d: " % [num += 1]
decode_upc(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ")
print "%2d: " % [num += 1]
decode_upc(" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ")
print "%2d: " % [num += 1]
decode_upc(" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ")
print "%2d: " % [num += 1]
decode_upc(" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ")
end
main() |
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
| #Lua | Lua | print('Enter a string: ')
s = io.stdin:read()
print('Enter a number: ')
i = tonumber(io.stdin:read())
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Keyboard "75000"+chr$(13)
Input "Integer:", A%
\\ Input erase keyboard buffer, we can't place in first Keyboard keys for second input
Keyboard "Hello World"+Chr$(13)
Input "String:", A$
Print A%, A$
}
CheckIt
|
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
| #Rascal | Rascal | import vis::Render;
import vis::Figure;
public void UserInput2(){
integer = "";
string = "";
row1 = [text("Enter a string "),
textfield("",void(str s){string = s;}),
text(str(){return " This input box will give a string by definition.\n You entered <string>";})];
row2 = [text("Enter 75000"),
textfield("",void(str v){integer = v;}),
text(str(){return " <integer == "75000" ? "Correct" : "Wrong">";})];
render(grid([row1, row2]));
} |
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
| #REBOL | REBOL | rebol [
Title: "Graphical User Input"
URL: http://rosettacode.org/wiki/User_Input_-_graphical
]
; Simple GUI's can be defined with 'layout', a special purpose dialect
; for specifying interfaces. In this case, I describe a gradient
; background with an instruction label, followed by the input fields
; and a validation button. It's possible to check dynamically as the
; user types but I wanted to keep this example as clear as possible.
view layout [
; You can define new widget styles. Here I create a padded label style
; (so that everything will line up) and a simple indicator light to
; show if there's a problem with an input field.
style label vtext 60 "unlabeled"
style indicator box maroon 24x24
backdrop effect [gradient 0x1 black coal]
vtext "Please enter a string, and the number 75000:"
; By default, GUI widgets are arranged top down. The 'across' word
; starts stacking widgets from left to right. 'return' starts a new
; line -- just like on a typewriter!
across
; Notice I'm using my new label and indicator styles here. Widgets
; that I need to access later (the input field and the indicator) are
; assigned to variables.
label "string:" s: field 240 si: indicator return
label "number:" n: field 50 ni: indicator return
pad 66
button "validate" [
; The user may have entered bogus values, so I reset the indicators:
si/color: ni/color: maroon
; Now I check to see if the values are correct. For the string, I just
; care that there is one. For the integer, I make sure that it
; evaluates to an integer and that it's value is 75000. Because I've
; already set the indicator colour, I don't care the integer
; conversion raises an error or not, so I ignore it if anything goes
; wrong.
if 0 < length? get-face s [si/color: green]
error? try [if 75000 = to-integer get-face n [ni/color: green]]
show [si ni] ; Repainting multiple objects at once.
]
] |
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.
| #zkl | zkl | println("Char Unicode UTF-8");
foreach utf,unicode_int in (T( T("\U41;",0x41), T("\Uf6;",0xf6),
T("\U416;",0x416), T("\U20AC;",0x20ac), T("\U1D11E;",0x1d11e))){
utf_int:=utf.reduce(fcn(s,c){ 0x100*s + c.toAsc() },0);
char :=unicode_int.toString(-8); // Unicode int to UTF-8 string
// UTF-8 bytes to UTF-8 string:
char2:=Data(Void,utf_int.toBigEndian(utf_int.len())).text;
println("%s %s %9s %x".fmt(char,char2,"U+%x".fmt(unicode_int),utf_int));
} |
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
| #Raku | Raku | my $url = 'http://foo bar/';
say $url.subst(/<-alnum>/, *.ord.fmt("%%%02X"), :g); |
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
| #REALbasic | REALbasic |
Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
|
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
| #Objeck | Objeck |
a : Int;
b : Int := 13;
c := 7;
|
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
| #OCaml | OCaml | let x = 28 |
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
| #Lingo | Lingo | a = vector(1,2,3)
b = vector(4,5,6)
put a * b
-- 32.0000
put a.dot(b)
-- 32.0000
put a.cross(b)
-- vector( -3.0000, 6.0000, -3.0000 ) |
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á".
| #Pike | Pike |
void main()
{
array encoded_urls = ({
"http%3A%2F%2Ffoo%20bar%2F",
"google.com/search?q=%60Abdu%27l-Bah%C3%A1"
});
foreach(encoded_urls, string url) {
string decoded = Protocols.HTTP.uri_decode( url );
write( string_to_utf8(decoded) +"\n" ); // Assume sink does 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á".
| #PowerShell | PowerShell |
[System.Web.HttpUtility]::UrlDecode("http%3A%2F%2Ffoo%20bar%2F")
|
http://rosettacode.org/wiki/UPC | UPC | Goal
Convert UPC bar codes to decimal.
Specifically:
The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards...
Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and # characters representing the presence or absence of ink).
Sample input
Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:
# # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # #
# # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # #
# # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # #
# # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # #
# # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # #
# # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # #
# # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # #
# # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # #
# # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # #
# # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # #
Some of these were entered upside down, and one entry has a timing error.
Task
Implement code to find the corresponding decimal representation of each, rejecting the error.
Extra credit for handling the rows entered upside down (the other option is to reject them).
Notes
Each digit is represented by 7 bits:
0: 0 0 0 1 1 0 1
1: 0 0 1 1 0 0 1
2: 0 0 1 0 0 1 1
3: 0 1 1 1 1 0 1
4: 0 1 0 0 0 1 1
5: 0 1 1 0 0 0 1
6: 0 1 0 1 1 1 1
7: 0 1 1 1 0 1 1
8: 0 1 1 0 1 1 1
9: 0 0 0 1 0 1 1
On the left hand side of the bar code a space represents a 0 and a # represents a 1.
On the right hand side of the bar code, a # represents a 0 and a space represents a 1
Alternatively (for the above): spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code.
The UPC-A bar code structure
It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly),
then has a # # sequence marking the start of the sequence,
then has the six "left hand" digits,
then has a # # sequence in the middle,
then has the six "right hand digits",
then has another # # (end sequence), and finally,
then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).
Finally, the last digit is a checksum digit which may be used to help detect errors.
Verification
Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.
The sum (mod 10) must be 0 (must have a zero as its last digit) if the UPC number has been read correctly.
| #Wren | Wren | import "/fmt" for Fmt
var digitL = {
" ## #": 0,
" ## #": 1,
" # ##": 2,
" #### #": 3,
" # ##": 4,
" ## #": 5,
" # ####": 6,
" ### ##": 7,
" ## ###": 8,
" # ##": 9
}
var digitR = {
"### # ": 0,
"## ## ": 1,
"## ## ": 2,
"# # ": 3,
"# ### ": 4,
"# ### ": 5,
"# # ": 6,
"# # ": 7,
"# # ": 8,
"### # ": 9
}
var endSentinel = "# #" // also at start
var midSentinel = " # # "
var decodeUpc = Fn.new { |s|
var decodeUpcImpl = Fn.new { |input|
var upc = input.trim()
if (upc.count != 95) return false
var pos = 0
var digits = []
var sum = 0
var oneThree = [1, 3]
// end sentinel
if (upc[pos..pos+2] == endSentinel) {
pos = pos + 3
} else {
return false
}
// 6 left hand digits
for (i in 0..5) {
var digit = digitL[upc[pos..pos+6]]
if (!digit) return false
digits.add(digit)
sum = sum + digit * oneThree[digits.count % 2]
pos = pos + 7
}
// mid sentinel
if (upc[pos..pos+4] == midSentinel) {
pos = pos + 5
} else {
return false
}
// 6 right hand digits
for (i in 0..5) {
var digit = digitR[upc[pos..pos+6]]
if (!digit) return false
digits.add(digit)
sum = sum + digit * oneThree[digits.count % 2]
pos = pos + 7
}
// end sentinel
if (upc[pos..pos+2] != endSentinel) return false
if (sum%10 == 0) {
System.write("%(digits) ")
return true
}
System.write("Failed Checksum ")
return false
}
if (decodeUpcImpl.call(s)) {
System.print("Rightside Up")
} else if (decodeUpcImpl.call(s[-1..0])) {
System.print("Upside Down")
} else {
System.print("Invalid digit(s)")
}
}
var barcodes = [
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
]
var n = 0
for (barcode in barcodes) {
n = n + 1
Fmt.write("$2d: ", n)
decodeUpc.call(barcode)
} |
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
| #MACRO-10 | MACRO-10 |
TITLE User Input
COMMENT !
User Input ** PDP-10 assembly language (kjx, 2022)
Assembler: MACRO-10 Operating system: TOPS-20
This program reads a string (maximum of 80 characters) and
a decimal number. The number is checked to be 75000. Invalid
input (like entering characters instead of a decimal number)
is detected, and an error message is printed in that case.
!
SEARCH MONSYM,MACSYM
.REQUIRE SYS:MACREL
STDAC. ;Set standard register names.
STRING: BLOCK 20 ;20 octal words = 80 characters.
NUMBER: BLOCK 1 ;1 word for number.
;;
;; Execution starts here:
;;
GO:: RESET% ;Initialize process.
;; Print prompt:
HRROI T1,[ASCIZ /Please type a string, 80 chars max.: /]
PSOUT%
;; Read string from terminal:
HRROI T1,STRING ;Pointer to string-buffer.
MOVEI T2,^D80 ;80 characters max.
SETZ T3 ;No special ctrl-r prompt.
RDTTY% ;Read from terminal.
ERJMP ERROR ; On error, go to ERROR.
;; Print second prompt:
NUMI: HRROI T1,[ASCIZ /Please type the decimal number 75000: /]
PSOUT%
;; Input number from terminal:
MOVEI T1,.PRIIN ;Read from terminal.
MOVEI T3,^D10 ;Decimal input.
NIN% ;Input number.
ERJMP ERROR ; On error, go to ERROR.
;; Make sure number is actually 75000.
CAIE T2,^D75000 ;Compare number...
JRST [ HRROI T1,[ASCIZ /Number is not 75000! /]
PSOUT% ; ...complain and
JRST NUMI ] ; try again.
MOVEM T2,NUMBER ;Store number if correct.
;; Now print out string and number:
HRROI T1,STRING ;String ptr into T1.
PSOUT% ;Print string.
MOVEI T1,.PRIOU ;Print on standard output.
MOVE T2,NUMBER ;Load number into T2.
MOVEI T3,^D10 ;Decimal output.
NOUT% ;And print the number.
ERJMP ERROR ; On error, go to ERROR.
;; End program:
HALTF% ;Halt program.
JRST GO ;Allow for 'continue'-command.
;;
;; The following routine prints out an error message,
;; similar to perror() in C:
;;
ERROR: MOVEI T1,.PRIOU ;Standard output.
MOVE T2,[.FHSLF,,-1] ;Own program, last error.
SETZ T3, ;No size-limit on message.
ERSTR% ;Print error-message.
JFCL ; Ignore errors from ERSTR.
JFCL ; dito.
HALTF% ;Halt program.
JRST GO ;Allow for 'continue'-command.
END GO
|
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
| #Maple | Maple | printf("String:"); string_value := readline();
printf("Integer: "); int_value := parse(readline()); |
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
| #REXX | REXX | /*REXX pgm prompts (using the OS GUI) for a string & then prompts for a specific number.*/
#= 75000 /*the number that must be entered. */
x=
N=
do while x=' '; say /*string can't be blanks or null string*/
say 'Please enter a string: '
parse pull x
if x='' then say '***error*** No string entered.'
end /*while x···*/
do while N\=#; say /*the number (below) may be ill formed.*/
say 'Please enter the number:' #
parse pull N
if datatype(N, 'N') then N= N / 1 /*normalize the number: 007 4.0 +2 */
if N\=# then say '***error*** The number is not correct: ' N.
end /*while N···*/
say
say 'The string entered is:' x /*echo the values (string and number. */
say 'The number entered is:' N /*stick a fork in it, we're all done. */ |
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
| #Ring | Ring |
Load "guilib.ring"
MyApp = New qApp {
num = 0
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
btn1 = new qpushbutton(win1) {
setGeometry(130,200,100,30)
settext("Validate")
setclickevent("Validate()")}
lineedit1 = new qlineedit(win1) {
setGeometry(10,100,250,30)
settext("")}
lineedit2 = new qlineedit(win1) {
setGeometry(10,150,50,30)
settext("0")}
label1 = new qLabel(win1) {
setGeometry(270,100,50,30)
setText("")}
label2 = new qLabel(win1) {
setGeometry(70,150,50,30)
setText("")}
label3 = new qLabel(win1) {
setGeometry(10,50,250,30)
setText("Please enter a string, and the number 75000 :")}
show()}
exec()}
func Validate
lineedit1{temp1 = text()}
num1 = isdigit(temp1)
if num1 = 0 label1{settext("OK")} else label1{settext("NOT OK")} ok
lineedit2{temp2 = text()}
num2 = number(temp2)
if num2 = 75000 label2{settext("OK")} else label2{settext("NOT OK")} ok
|
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
| #REXX | REXX | /* Rexx */
do
call testcase
say
say RFC3986
call testcase RFC3986
say
say HTML5
call testcase HTML5
say
return
end
exit
/* -------------------------------------------------------------------------- */
encode:
procedure
do
parse arg url, varn .
parse upper var varn variation
drop RFC3986 HTML5
opts. = ''
opts.RFC3986 = '-._~'
opts.HTML5 = '-._*'
rp = ''
do while length(url) > 0
parse var url tc +1 url
select
when datatype(tc, 'A') then do
rp = rp || tc
end
when tc == ' ' then do
if variation = HTML5 then
rp = rp || '+'
else
rp = rp || '%' || c2x(tc)
end
otherwise do
if pos(tc, opts.variation) > 0 then do
rp = rp || tc
end
else do
rp = rp || '%' || c2x(tc)
end
end
end
end
return rp
end
exit
/* -------------------------------------------------------------------------- */
testcase:
procedure
do
parse arg variation
X = 0
url. = ''
X = X + 1; url.0 = X; url.X = 'http://foo bar/'
X = X + 1; url.0 = X; url.X = 'mailto:"Ivan Aim" <[email protected]>'
X = X + 1; url.0 = X; url.X = 'mailto:"Irma User" <[email protected]>'
X = X + 1; url.0 = X; url.X = 'http://foo.bar.com/~user-name/_subdir/*~.html'
do i_ = 1 to url.0
say url.i_
say encode(url.i_, variation)
end i_
return
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
| #Oforth | Oforth | import: date
: testVariable
| a b c |
Date now ->a
a println ; |
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
| #ooRexx | ooRexx | a.=4711
Say 'before sub a.3='a.3
Call sub a.
Say ' after sub a.3='a.3
Exit
sub: Procedure
use Arg a.
a.3=3
Return |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product (a scalar quantity)
A • B = a1b1 + a2b2 + a3b3
The cross product (a vector quantity)
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
The scalar triple product (a scalar quantity)
A • (B x C)
The vector triple product (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a • b
Compute and display: a x b
Compute and display: a • (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
A starting page on Wolfram MathWorld is Vector Multiplication .
Wikipedia dot product.
Wikipedia cross product.
Wikipedia triple product.
Related tasks
Dot product
Quaternion type
| #Lua | Lua | Vector = {}
function Vector.new( _x, _y, _z )
return { x=_x, y=_y, z=_z }
end
function Vector.dot( A, B )
return A.x*B.x + A.y*B.y + A.z*B.z
end
function Vector.cross( A, B )
return { x = A.y*B.z - A.z*B.y,
y = A.z*B.x - A.x*B.z,
z = A.x*B.y - A.y*B.x }
end
function Vector.scalar_triple( A, B, C )
return Vector.dot( A, Vector.cross( B, C ) )
end
function Vector.vector_triple( A, B, C )
return Vector.cross( A, Vector.cross( B, C ) )
end
A = Vector.new( 3, 4, 5 )
B = Vector.new( 4, 3, 5 )
C = Vector.new( -5, -12, -13 )
print( Vector.dot( A, B ) )
r = Vector.cross(A, B )
print( r.x, r.y, r.z )
print( Vector.scalar_triple( A, B, C ) )
r = Vector.vector_triple( A, B, C )
print( r.x, r.y, r.z ) |
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á".
| #PureBasic | PureBasic | URL$ = URLDecoder("http%3A%2F%2Ffoo%20bar%2F")
Debug URL$ ; 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á".
| #Python | Python |
#Python 2.X
import urllib
print urllib.unquote("http%3A%2F%2Ffoo%20bar%2F")
#Python 3.5+
from urllib.parse import unquote
print(unquote('http%3A%2F%2Ffoo%20bar%2F'))
|
http://rosettacode.org/wiki/UPC | UPC | Goal
Convert UPC bar codes to decimal.
Specifically:
The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards...
Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and # characters representing the presence or absence of ink).
Sample input
Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:
# # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # #
# # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # #
# # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # #
# # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # #
# # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # #
# # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # #
# # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # #
# # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # #
# # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # #
# # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # #
Some of these were entered upside down, and one entry has a timing error.
Task
Implement code to find the corresponding decimal representation of each, rejecting the error.
Extra credit for handling the rows entered upside down (the other option is to reject them).
Notes
Each digit is represented by 7 bits:
0: 0 0 0 1 1 0 1
1: 0 0 1 1 0 0 1
2: 0 0 1 0 0 1 1
3: 0 1 1 1 1 0 1
4: 0 1 0 0 0 1 1
5: 0 1 1 0 0 0 1
6: 0 1 0 1 1 1 1
7: 0 1 1 1 0 1 1
8: 0 1 1 0 1 1 1
9: 0 0 0 1 0 1 1
On the left hand side of the bar code a space represents a 0 and a # represents a 1.
On the right hand side of the bar code, a # represents a 0 and a space represents a 1
Alternatively (for the above): spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code.
The UPC-A bar code structure
It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly),
then has a # # sequence marking the start of the sequence,
then has the six "left hand" digits,
then has a # # sequence in the middle,
then has the six "right hand digits",
then has another # # (end sequence), and finally,
then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).
Finally, the last digit is a checksum digit which may be used to help detect errors.
Verification
Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.
The sum (mod 10) must be 0 (must have a zero as its last digit) if the UPC number has been read correctly.
| #zkl | zkl | var lhd=Dictionary(), rhd=Dictionary();
[0..].zip(List(
"0 0 0 1 1 0 1", //--> "___##_#":0 "###__#_":0
"0 0 1 1 0 0 1",
"0 0 1 0 0 1 1",
"0 1 1 1 1 0 1",
"0 1 0 0 0 1 1",
"0 1 1 0 0 0 1",
"0 1 0 1 1 1 1",
"0 1 1 1 0 1 1",
"0 1 1 0 1 1 1",
"0 0 0 1 0 1 1") //--> "___#_##":9 "###_#__":9
).pump(Void,fcn([(n,bs)]){
bs-=" ";
lhd[bs.translate("01","_#")]=n;
rhd[bs.translate("10","_#")]=n;
});
fcn parseBarCode(barcode, one=True){ // --> 12 digits
upsideDown:='wrap{ // was I looking at this bar code upside down?
if(one and (r:=parseBarCode(barcode.reverse(),False))) return(r);
return(False);
};
var [const] start=RegExp(String("_"*9, "+#_#")), tail="_"*7;
if(not start.search(barcode)) return(upsideDown());
r,idx,d,mark := List(), start.matched[0][1], lhd, "_#_#_";
do(2){
do(6){
if(Void==(z:=d.find(barcode[idx,7]))) return(upsideDown());
r.append(z);
idx+=7;
}
if(barcode[idx,5] != mark) return(Void);
d,idx,mark = rhd, idx+5, "#_#__";
}
if(tail!=barcode[idx,7]) return(Void); // 9 trailing blanks? two checked above
r
} |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | mystring = InputString["give me a string please"];
myinteger = Input["give me an integer please"]; |
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
| #MATLAB | MATLAB | >> input('Input string: ')
Input string: 'Hello'
ans =
Hello
>> input('Input number: ')
Input number: 75000
ans =
75000
>> input('Input number, the number will be stored as a string: ','s')
Input number, the number will be stored as a string: 75000
ans =
75000 |
http://rosettacode.org/wiki/User_input/Graphical | User input/Graphical |
In this task, the goal is to input a string and the integer 75000, from graphical user interface.
See also: User input/Text
| #Ruby | Ruby | require 'tk'
def main
root = TkRoot.new
l1 = TkLabel.new(root, "text" => "input a string")
e1 = TkEntry.new(root)
l2 = TkLabel.new(root, "text" => "input the number 75000")
e2 = TkEntry.new(root) do
validate "focusout"
validatecommand lambda {e2.value.to_i == 75_000}
invalidcommand lambda {focus_number_entry(e2)}
end
ok = TkButton.new(root) do
text "OK"
command lambda {validate_input(e1, e2)}
end
Tk.grid(l1, e1)
Tk.grid(l2, e2)
Tk.grid("x",ok, "sticky" => "w")
Tk.mainloop
end
def validate_input(text_entry, number_entry)
if number_entry.value.to_i != 75_000
focus_number_entry(number_entry)
else
puts %Q{You entered: "#{text_entry.value}" and "#{number_entry.value}"}
root.destroy
end
end
def focus_number_entry(widget)
widget \
.configure("background" => "red", "foreground" => "white") \
.selection_range(0, "end") \
.focus
end
main |
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
| #Ruby | Ruby | require 'cgi'
puts CGI.escape("http://foo bar/").gsub("+", "%20")
# => "http%3A%2F%2Ffoo%20bar%2F" |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Run_BASIC | Run BASIC | urlIn$ = "http://foo bar/"
for i = 1 to len(urlIn$)
a$ = mid$(urlIn$,i,1)
if (a$ >= "0" and a$ <= "9") _
or (a$ >= "A" and a$ <= "Z") _
or (a$ >= "a" and a$ <= "z") then url$ = url$ + a$ else url$ = url$ + "%"+dechex$(asc(a$))
next i
print urlIn$;" -> ";url$ |
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
| #Ol | Ol |
; Declare the symbol 'var1' and associate number 123 with it.
(define var1 123)
(print var1)
; ==> 123
; Reassociate number 321 with var1.
(define var1 321)
(print var1)
; Create function that prints value of var1 ...
(define (show)
(print var1))
; ... and eassociate number 42 with var1.
(define var1 42)
(print var1)
; ==> 42
; var1 prints as 42, but...
(show)
; ==> 321
; ... function 'show' still print old associated value
|
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
| #Openscad | Openscad |
mynumber=5+4; // This gives a value of nine
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module checkit {
class Vector {
\\ by default are double
a,b,c
Property ToString$ {
Value {
link parent a,b,c to a,b,c
value$=format$("({0}, {1}, {2})",a,b,c)
}
}
Operator "==" {
read n
push .a==n.a and .b==n.b and .c==n.c
}
Operator Unary {
.a-! : .b-! : .c-!
}
Operator "+" {
Read v2
For this, v2 {
.a+=..a :.b+=..b:.c+=..c:
}
}
Function Mul(r) {
vv=this
for vv {
.a*=r:.b*=r:.c*=r
}
=vv
}
Function Dot(v2) {
def double sum
for this, v2 {
sum=.a*..a+.b*..b+.c*..c
}
=sum
}
Operator "*" {
Read v2
For This, v2 {
Push .b*..c-.c*..b
Push .c*..a-.a*..c
.c<=.a*..b-.b*..a
Read .b, .a
}
}
class:
module Vector {
if match("NNN") then {
Read .a,.b,.c
}
}
}
A=Vector(3,4,5)
B=Vector(4,3,5)
C=Vector(-5,-12,-13)
Print "A=";A.toString$
Print "B=";B.toString$
Print "C=";C.toString$
Print "A dot B="; A.dot(B)
AxB=A*B
Print "A x B="; AxB.toString$
Print "A dot (B x C)=";A.dot(B*C)
AxBxC=A*(B*C)
Print "A x (B x C)=";AxBxC.toString$
Def ToString$(a)=a.toString$
Print "A x (B x C)=";ToString$(A*(B*C))
}
Checkit
|
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #R | R | URLdecode("http%3A%2F%2Ffoo%20bar%2F") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.