task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #BASIC | BASIC | 10 LET A=1.3
20 LET B%=1.3: REM The sigil indicates an integer, so this will be rounded down
30 LET C$="0121": REM The sigil indicates a string data type. the leading zero is not truncated
40 DIM D(10): REM Create an array of 10 digits
50 DIM E$(5.10): REM Create an array of 5 strings, with a maximum length of 10 characters
60 LET D(1)=1.3: REM Assign the first element of d
70 LET E$(3)="ROSE": REM Assign a value to the third string
80 PRINT D(3): REM Unassigned array elements have a default value of zero
90 PRINT E$(3): REM Ten spaces because string arrays are not dynamic
100 PRINT E$(3);"TTA CODE": REM There will be spaces between rose and etta
110 DIM F%(10): REM Integers use less space than floating point values
120 PRINT G: REM This is an error because f has not been defined
130 PRINT D(0): REM This is an error because elements are numbered from one
140 LET D(11)=6: REM This is an error because d only has 10 elements
150 PRINT F%: REM This is an error because we have not provided an element number
160 END |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using A:
0
Using B:
0 0
Using C:
0 0 1
Using B:
0 0 1 0
Using C: (zero last occurred two steps back - before the one)
0 0 1 0 2
Using B:
0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
0 0 1 0 2 0 2 2 1 6
...
Task
Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
Use it to display here, on this page:
The first ten terms of the sequence.
Terms 991 - to - 1000 of the sequence.
References
Don't Know (the Van Eck Sequence) - Numberphile video.
Wikipedia Article: Van Eck's Sequence.
OEIS sequence: A181391.
| #C.23 | C# | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } } |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #FreeBASIC | FreeBASIC | 'Vampire numbers.
'FreeBASIC version 24. Windows
'Vampire.bas
Function WithinString(n As Ulongint,f As Ulongint) As Integer
var m=Str(n),p=Str(f)
For z As Integer=0 To Len(p)-1
var i=Instr(m,Chr(p[z]))
If i Then
m=Mid(m,1,i-1)+Mid(m,i+1)
Else
Return 0
End If
Next z
Return -1
End Function
Sub AllFactors(N As Ulongint,factors() As Ulongint)
Dim As String Sn=Str(n)
Dim As Integer half=Len(sn)\2
Redim factors(1 To 1)
#macro bsort(array)
For p1 As Integer = 1 To Ubound(array) - 1
For p2 As Integer = p1 + 1 To Ubound(array)
If array(p1)>array(p2) Then Swap array(p1),array(p2)
Next p2
Next p1
#endmacro
Dim As Ulongint c
For i As Ulongint = 1 To Sqr(N)
If N Mod i=0 Then
If Len(Str(i))=half Then
If WithinString(N,i) Then
c=c+1
Redim Preserve factors(1 To c)
factors(c)=i
End If
End If
If N <> i*i Then
If Len(Str(n\i))=half Then
If WithinString(N,n\i) Then
c=c+1
Redim Preserve factors(1 To c)
factors(c)=n\i
End If
End If
End If
End If
Next i
bsort(factors)
End Sub
Function VampireNumbers(N As Ulongint) As Integer
Dim As Integer flag
Dim As Ulongint LastFactor
Redim As Ulongint Factor()
AllFactors(N,Factor())
For p1 As Integer = 1 To Ubound(Factor)
For p2 As Integer=1 To Ubound(Factor)
If Factor(p1)*Factor(p2)=n Then
If Factor(p1) Mod 10<>0 Or Factor(p2) Mod 10 <>0 Then
If WithinString(n,valulng(Str(Factor(p1))+Str(Factor(p2)))) Then
If LastFactor=Factor(p2) Then Exit For,For
flag=1
Print n;": [";Factor(p1);",";Factor(p2);"]"
LastFactor=Factor(p1)
End If
End If
End If
Next p2
Next p1
If flag Then Return -1
End Function
'============== IMPLEMENT ==============================
print "First 28 Vampire numbers"
print
Print "Number: [fangs]"
Print
Dim As Ulongint n=1000
Dim As Integer count
Dim As Double t1,t2
t1=Timer
Do
n=n+1
Var s=Str(n)
If Len(s) Mod 2<>0 Then n=n*10
If vampireNumbers(n) Then count=count+1
Loop Until count=27
Print
print "Individual tests:"
print
'individual tests
n=16758243290880ull
If Not vampirenumbers(n) Then Print n;": [returns no fangs]"
Print
n=24959017348650ull
If Not vampirenumbers(n) Then Print n;": [returns no fangs]"
print
n=14593825548650ull
If Not vampirenumbers(n) then print n;": [returns no fangs]"
t2=Timer
print
Print "Completed in ";
Print t2-t1;" Seconds"
Sleep |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #TXR | TXR | 1> (carray-num #x200000)
#<carray 3 #<ffi-type uchar>>
2> (carray-get *1)
#(32 0 0)
3> (carray-num #x1FFFFF)
#<carray 3 #<ffi-type uchar>>
4> (carray-get *3)
#(31 255 255)
5> (num-carray *1)
2097152
6> (num-carray *3)
2097151 |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function ToVlq(v As ULong) As ULong
Dim array(8) As Byte
Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray
buffer.CopyTo(array, 0)
Return BitConverter.ToUInt64(array, 0)
End Function
Function FromVlq(v As ULong) As ULong
Dim collection = BitConverter.GetBytes(v).Reverse()
Return FromVlqCollection(collection)
End Function
Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)
If v > Math.Pow(2, 56) Then
Throw New OverflowException("Integer exceeds max value.")
End If
Dim index = 7
Dim significantBitReached = False
Dim mask = &H7FUL << (index * 7)
While index >= 0
Dim buffer = mask And v
If buffer > 0 OrElse significantBitReached Then
significantBitReached = True
buffer >>= index * 7
If index > 0 Then
buffer = buffer Or &H80
End If
Yield buffer
End If
mask >>= 7
index -= 1
End While
End Function
Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong
Dim v = 0UL
Dim significantBitReached = False
Using enumerator = vlq.GetEnumerator
Dim index = 0
While enumerator.MoveNext
Dim buffer = enumerator.Current
If buffer > 0 OrElse significantBitReached Then
significantBitReached = True
v <<= 7
v = v Or (buffer And &H7FUL)
End If
index += 1
If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then
Exit While
End If
End While
End Using
Return v
End Function
Sub Main()
Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}
For Each original In values
Console.WriteLine("Original: 0x{0:X}", original)
REM collection
Dim seq = ToVlqCollection(original)
Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b)))
Dim decoded = FromVlqCollection(seq)
Console.WriteLine("Decoded: 0x{0:X}", decoded)
REM ints
Dim encoded = ToVlq(original)
Console.WriteLine("Encoded: 0x{0:X}", encoded)
decoded = FromVlq(encoded)
Console.WriteLine("Decoded: 0x{0:X}", decoded)
Console.WriteLine()
Next
End Sub
End Module |
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
| #Free_Pascal | Free Pascal | program variadicRoutinesDemo(input, output, stdErr);
{$mode objFPC}
// array of const is only supported in $mode objFPC or $mode Delphi
procedure writeLines(const arguments: array of const);
var
argument: TVarRec;
begin
// inside the body `array of const` is equivalent to `array of TVarRec`
for argument in arguments do
begin
with argument do
begin
case vType of
vtInteger:
begin
writeLn(vInteger);
end;
vtBoolean:
begin
writeLn(vBoolean);
end;
vtChar:
begin
writeLn(vChar);
end;
vtAnsiString:
begin
writeLn(ansiString(vAnsiString));
end;
// and so on
end;
end;
end;
end;
begin
writeLines([42, 'is', true, #33]);
end. |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | void local fn Function1( count as long, ... )
va_list ap
long value
va_start( ap, count )
while ( count )
value = fn va_argLong( ap )
printf @"%ld",value
count--
wend
va_end( ap )
end fn
void local fn Function2( obj as CFTypeRef, ... )
va_list ap
va_start( ap, obj )
while ( obj )
printf @"%@",obj
obj = fn va_argObj(ap)
wend
va_end( ap )
end fn
window 1
// params: num of args, 1st arg, 2nd arg, etc.
fn Function1( 3, 987, 654, 321 )
print
// params: 1st arg, 2nd arg, ..., NULL
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )
HandleEvents |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Perl | Perl | use Devel::Size qw(size total_size);
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var); # 24
print total_size(\@arr); # 256 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Phix | Phix | printf(1,"An integer contains %d bytes.\n", machine_word())
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #PicoLisp | PicoLisp |
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
/* whatever data type or structure it is. */
put skip list (CURRENTSIZE(x));
/* gives the current number of bytes of X */
/* actually used by such things as a */
/* varying-length string, including its */
/* length field. */
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #PL.2FI | PL/I |
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
/* whatever data type or structure it is. */
put skip list (CURRENTSIZE(x));
/* gives the current number of bytes of X */
/* actually used by such things as a */
/* varying-length string, including its */
/* length field. */
|
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Ol | Ol |
(define :+ +)
(define (+ a b)
(if (vector? a)
(if (vector? b)
(vector-map :+ a b)
(error "error:" "not applicable (+ vector non-vector)"))
(if (vector? b)
(error "error:" "not applicable (+ non-vector vector)")
(:+ a b))))
(define :- -)
(define (- a b)
(if (vector? a)
(if (vector? b)
(vector-map :- a b)
(error "error:" "not applicable (+ vector non-vector)"))
(if (vector? b)
(error "error:" "not applicable (+ non-vector vector)")
(:- a b))))
(define :* *)
(define (* a b)
(if (vector? a)
(if (not (vector? b))
(vector-map (lambda (x) (:* x b)) a)
(error "error:" "not applicable (* vector vector)"))
(if (vector? b)
(error "error:" "not applicable (* scalar vector)")
(:* a b))))
(define :/ /)
(define (/ a b)
(if (vector? a)
(if (not (vector? b))
(vector-map (lambda (x) (:/ x b)) a)
(error "error:" "not applicable (/ vector vector)"))
(if (vector? b)
(error "error:" "not applicable (/ scalar vector)")
(:/ a b))))
(define x [1 2 3 4 5])
(define y [7 8 5 4 2])
(print x " + " y " = " (+ x y))
(print x " - " y " = " (- x y))
(print x " * " 7 " = " (* x 7))
(print x " / " 7 " = " (/ x 7))
|
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #Phix | Phix | with javascript_semantics
constant ENCRYPT = +1,
DECRYPT = -1
function Vigenere(string s, key, integer mode)
string res = ""
integer k = 1, ch
s = upper(s)
for i=1 to length(s) do
ch = s[i]
if ch>='A' and ch<='Z' then
res &= 'A'+mod(ch+mode*(key[k]+26),26)
k = mod(k,length(key))+1
end if
end for
return res
end function
constant key = "LEMON",
s = "ATTACK AT DAWN",
e = Vigenere(s,key,ENCRYPT),
d = Vigenere(e,key,DECRYPT)
printf(1,"Original: %s\nEncrypted: %s\nDecrypted: %s\n",{s,e,d})
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Sidef | Sidef | func traverse(Block callback, Dir dir) {
dir.open(\var dir_h) || return nil
dir_h.entries.each { |entry|
if (entry.is_a(Dir)) {
traverse(callback, entry)
} else {
callback(entry)
}
}
}
var dir = Dir.cwd
var pattern = /foo/ # display files that contain 'foo'
traverse(
{ |file|
if (file.basename ~~ pattern) {
say file
}
} => dir
) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Smalltalk | Smalltalk | Directory extend [
wholeContent: aPattern do: twoBlock [
self wholeContent: aPattern withLevel: 0 do: twoBlock.
]
wholeContent: aPattern withLevel: l do: twoBlock [
|cont|
cont := (self contents) asSortedCollection.
cont remove: '.'; remove: '..'.
cont
do: [ :n | |fn ps|
ps := (Directory pathSeparator) asString.
fn := (self name), ps, n.
((File name: fn) isDirectory)
ifTrue: [
twoBlock value: (n, ps) value: l.
(Directory name: fn) wholeContent: aPattern withLevel: (l+1) do: twoBlock.
]
ifFalse: [
( n =~ aPattern )
ifMatched: [ :m |
twoBlock value: n value: l
]
]
]
]
]. |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Wren | Wren | import "/math" for Math, Nums
import "/fmt" for Fmt
var waterCollected = Fn.new { |tower|
var n = tower.count
var highLeft = [0] + (1...n).map { |i| Nums.max(tower[0...i]) }.toList
var highRight = (1...n).map { |i| Nums.max(tower[i...n]) }.toList + [0]
var t = (0...n).map { |i| Math.max(Math.min(highLeft[i], highRight[i]) - tower[i], 0) }
return Nums.sum(t)
}
var towers = [
[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]
]
for (tower in towers) Fmt.print("$2d from $n", waterCollected.call(tower), tower) |
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
| #Clojure | Clojure | (defrecord Vector [x y z])
(defn dot
[U V]
(+ (* (:x U) (:x V))
(* (:y U) (:y V))
(* (:z U) (:z V))))
(defn cross
[U V]
(new Vector
(- (* (:y U) (:z V)) (* (:z U) (:y V)))
(- (* (:z U) (:x V)) (* (:x U) (:z V)))
(- (* (:x U) (:y V)) (* (:y U) (:x V)))))
(let [a (new Vector 3 4 5)
b (new Vector 4 3 5)
c (new Vector -5 -12 -13)]
(doseq
[prod (list
(dot a b)
(cross a b)
(dot a (cross b c))
(cross a (cross b c)))]
(println prod))) |
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
| #Common_Lisp | Common Lisp | (defun alphap (char)
(char<= #\A char #\Z))
(defun alpha-digit-char-p (char)
(or (alphap char) (digit-char-p char)))
(defun valid-isin-format-p (isin)
(and (= (length isin) 12)
(alphap (char isin 0))
(alphap (char isin 1))
(loop for i from 2 to 10
always (alpha-digit-char-p (char isin i)))
(digit-char-p (char isin 11))))
(defun isin->digits (isin)
(apply #'concatenate 'string
(loop for c across isin
collect (princ-to-string (digit-char-p c 36)))))
(defun luhn-test (string)
(loop for c across (reverse string)
for oddp = t then (not oddp)
if oddp
sum (digit-char-p c) into result
else
sum (let ((n (* 2 (digit-char-p c))))
(if (> n 9) (- n 9) n))
into result
finally (return (zerop (mod result 10)))))
(defun valid-isin-p (isin)
(and (valid-isin-format-p isin)
(luhn-test (isin->digits isin))))
(defun test ()
(dolist (isin '("US0378331005" "US0373831005" "U50378331005" "US03378331005"
"AU0000XVGZA3" "AU0000VXGZA3" "FR0000988040"))
(format t "~A: ~:[invalid~;valid~]~%" isin (valid-isin-p isin)))) |
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
| #CLU | CLU | vc = proc (n, base: int) returns (int, int)
p: int := 0
q: int := 1
while n ~= 0 do
p := p * base + n // base
q := q * base
n := n / base
end
num: int := p
denom: int := q
while p ~= 0 do
p, q := q // p, p
end
return(num/q, denom/q)
end vc
print_frac = proc (po: stream, num, denom: int)
if num=0 then
stream$puts(po, " 0")
else
stream$puts(po, " ")
stream$putright(po, int$unparse(num), 2)
stream$puts(po, "/")
stream$putright(po, int$unparse(denom), 2)
end
end print_frac
start_up = proc ()
po: stream := stream$primary_output()
for base: int in int$from_to(2,5) do
stream$puts(po, "base " || int$unparse(base) || ":")
for i: int in int$from_to(0, 9) do
n, d: int := vc(i, base)
print_frac(po, n, d)
end
stream$putl(po, "")
end
end start_up |
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
| #Common_Lisp | Common Lisp | (defun van-der-Corput (n base)
(loop for d = 1 then (* d base) while (<= d n)
finally
(return (/ (parse-integer
(reverse (write-to-string n :base base))
:radix base)
d))))
(loop for base from 2 to 5 do
(format t "Base ~a: ~{~6a~^~}~%" base
(loop for i to 10 collect (van-der-Corput i base)))) |
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á".
| #11l | 11l | F url_decode(s)
V r = ‘’
V i = 0
L i < s.len
I s[i] == ‘%’
[Byte] b
L i < s.len & s[i] == ‘%’
i++
b.append(Int(s[i.+2], radix' 16))
i += 2
r ‘’= b.decode(‘utf-8’)
E
r ‘’= s[i]
i++
R r
print(url_decode(‘http%3A%2F%2Ffoo%20bar%2F’))
print(url_decode(‘https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B0%D0%BD%D1%81%D0%BF%D0%B0%D0%B9%D0%BB%D0%B5%D1%80’)) |
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
| #11l | 11l | V string = input(‘Input a string: ’)
V number = Float(input(‘Input a number: ’)) |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on parseURLString(URLString)
set output to {URLString}
set indent to tab & "• "
set componentsObject to current application's class "NSURLComponents"'s componentsWithString:(URLString)
repeat with thisKey in {"scheme", "user", "password", "host", "port", "path", "query", "fragment"}
set thisValue to (componentsObject's valueForKey:(thisKey))
if (thisValue is not missing value) then set end of output to indent & thisKey & (" = " & thisValue)
end repeat
return join(output, linefeed)
end parseURLString
on join(listOfText, delimiter)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delimiter
set output to listOfText as text
set AppleScript's text item delimiters to astid
return output
end join
-- Test code:
local output, URLString
set output to {}
repeat with URLString in {"foo://example.com:8042/over/there?name=ferret#nose", ¬
"urn:example:animal:ferret:nose", ¬
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", ¬
"ftp://ftp.is.co.za/rfc/rfc1808.txt", ¬
"http://www.ietf.org/rfc/rfc2396.txt#header1", ¬
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", ¬
"mailto:[email protected]", ¬
"news:comp.infosystems.www.servers.unix", ¬
"tel:+1-816-555-1212", ¬
"telnet://192.0.2.16:80/", ¬
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2", ¬
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"}
set end of output to parseURLString(URLString's contents)
end repeat
return join(output, linefeed & linefeed) |
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# encodes the specified url - 0-9, A-Z and a-z are unchanged, #
# everything else is converted to %xx where xx are hex-digits #
PROC encode url = ( STRING url )STRING:
IF url = "" THEN "" # empty string #
ELSE
# non-empty string #
# ensure result will be big enough for a string of all encodable #
# characters #
STRING hex digits = "0123456789ABCDEF";
[ 1 : ( ( UPB url - LWB url ) + 1 ) * 3 ]CHAR result;
INT r pos := 0;
FOR u pos FROM LWB url TO UPB url DO
CHAR c = url[ u pos ];
IF ( c >= "0" AND c <= "9" )
OR ( c >= "A" AND c <= "Z" )
OR ( c >= "a" AND c <= "z" )
THEN
# no need to encode this character #
result[ r pos +:= 1 ] := c
ELSE
# must encode #
INT c code = ABS c;
result[ r pos +:= 1 ] := "%";
result[ r pos +:= 1 ] := hex digits[ ( c code OVER 16 ) + 1 ];
result[ r pos +:= 1 ] := hex digits[ ( c code MOD 16 ) + 1 ]
FI
OD;
result[ 1 : r pos ]
FI; # encode url #
# task test case #
print( ( encode url( "http://foo bar/" ), newline ) )
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
| #Batch_File | Batch File |
@echo off
::setting variables in defferent ways
set myInt1=5
set myString1=Rosetta Code
set "myInt2=5"
set "myString2=Rosetta Code"
::Arithmetic
set /a myInt1=%myInt1%+1
set /a myInt2+=1
set /a myInt3=myInt2+ 5
set myInt
set myString
pause>nul
|
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
| #BBC_BASIC | BBC BASIC | REM BBC BASIC (for Windows) has the following scalar variable types;
REM the type is explicitly indicated by means of a suffix character.
REM Variable names must start with A-Z, a-z, _ or `, and may contain
REM any of those characters plus 0-9 and @; they are case-sensitive.
A& = 123 : REM Unsigned 8-bit byte (0 to 255)
A% = 12345678 : REM Signed 32-bit integer (-2147483648 to +2147483647)
A = 123.45E6 : REM Variant 40-bit float or 32-bit integer (no suffix)
A# = 123.45E6 : REM Variant 64-bit double or 32-bit integer
A$ = "Abcdef" : REM String (0 to 65535 bytes)
REM Scalar variables do not need to be declared but must be initialised
REM before being read, otherwise a 'No such variable' error is reported
REM The static integer variables A% to Z% are permanently defined.
REM BBC BASIC also has indirection operators which allow variable-like
REM entities to be created in memory:
DIM addr 7 : REM Allocate 8 bytes of heap
?addr = 123 : REM Unsigned 8-bit byte (0 to 255)
!addr = 12345 : REM Signed 32-bit integer (-2147483648 to +2147483647)
|addr = 12.34 : REM Variant 40-bit or 64-bit float or 32-bit integer
$addr = "Abc" : REM String terminated by CR (0 to 65535 bytes)
$$addr = "Abc": REM String terminated by NUL (0 to 65535 bytes)
REM The integer indirection operators may be used in a dyadic form:
offset = 4
addr?offset = 12345678 : REM Unsigned 8-bit byte at addr+offset
addr!offset = 12345678 : REM Signed 32-bit integer at addr+offset
REM All variables in BBC BASIC have global scope unless they are used
REM as a formal parameter of a function or procedure, or are declared
REM as LOCAL or PRIVATE. This is different from most other BASICs. |
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.
| #C.2B.2B | C++ | #include <iostream>
#include <map>
class van_eck_generator {
public:
int next() {
int result = last_term;
auto iter = last_pos.find(last_term);
int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
last_pos[last_term] = index;
last_term = next_term;
++index;
return result;
}
private:
int index = 0;
int last_term = 0;
std::map<int, int> last_pos;
};
int main() {
van_eck_generator gen;
int i = 0;
std::cout << "First 10 terms of the Van Eck sequence:\n";
for (; i < 10; ++i)
std::cout << gen.next() << ' ';
for (; i < 990; ++i)
gen.next();
std::cout << "\nTerms 991 to 1000 of the sequence:\n";
for (; i < 1000; ++i)
std::cout << gen.next() << ' ';
std::cout << '\n';
return 0;
} |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Go | Go | package main
import (
"fmt"
"math"
)
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func ndigits(x uint64) (n int) {
for ; x > 0; x /= 10 {
n++
}
return
}
func dtally(x uint64) (t uint64) {
for ; x > 0; x /= 10 {
t += 1 << (x % 10 * 6)
}
return
}
var tens [20]uint64
func init() {
tens[0] = 1
for i := 1; i < 20; i++ {
tens[i] = tens[i-1] * 10
}
}
func fangs(x uint64) (f []uint64) {
nd := ndigits(x)
if nd&1 == 1 {
return
}
nd /= 2
lo := max(tens[nd-1], (x+tens[nd]-2)/(tens[nd]-1))
hi := min(x/lo, uint64(math.Sqrt(float64(x))))
t := dtally(x)
for a := lo; a <= hi; a++ {
b := x / a
if a*b == x &&
(a%10 > 0 || b%10 > 0) &&
t == dtally(a)+dtally(b) {
f = append(f, a)
}
}
return
}
func showFangs(x uint64, f []uint64) {
fmt.Print(x)
if len(f) > 1 {
fmt.Println()
}
for _, a := range f {
fmt.Println(" =", a, "×", x/a)
}
}
func main() {
for x, n := uint64(1), 0; n < 26; x++ {
if f := fangs(x); len(f) > 0 {
n++
fmt.Printf("%2d: ", n)
showFangs(x, f)
}
}
fmt.Println()
for _, x := range []uint64{16758243290880, 24959017348650, 14593825548650} {
if f := fangs(x); len(f) > 0 {
showFangs(x, f)
} else {
fmt.Println(x, "is not vampiric")
}
}
} |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #Wren | Wren | import "/fmt" for Fmt, Conv
import "/str" for Str
var toOctets = Fn.new { |n|
var s = Conv.itoa(n, 2)
var le = s.count
var r = le % 7
var d = (le/7).floor
if (r > 0) {
d = d + 1
s = Fmt.zfill(7 * d, s)
}
var chunks = Str.chunks(s, 7)
var last = "0" + chunks[-1]
s = chunks[0..-2].map { |ch| "1" + ch }.join() + last
return Str.chunks(s, 8).map { |ch| Conv.atoi(ch, 2) }.toList
}
var fromOctets = Fn.new { |octets|
var s = ""
for (oct in octets) {
var bin = Conv.itoa(oct, 2)
bin = Fmt.zfill(7, bin)
s = s + bin[-7..-1]
}
return Conv.atoi(s, 2)
}
var tests = [2097152, 2097151]
for (test in tests) {
var octets = toOctets.call(test)
var display = octets.map { |oct| "Ox" + Fmt.xz(2, oct) }.toList
System.write("%(test) -> %(Fmt.v("s", 4, display, 0, " ", "")) -> ")
System.print(fromOctets.call(octets))
} |
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
| #FutureBasic | FutureBasic | void local fn Function1( count as long, ... )
va_list ap
long value
va_start( ap, count )
while ( count )
value = fn va_argLong( ap )
printf @"%ld",value
count--
wend
va_end( ap )
end fn
void local fn Function2( obj as CFTypeRef, ... )
va_list ap
va_start( ap, obj )
while ( obj )
printf @"%@",obj
obj = fn va_argObj(ap)
wend
va_end( ap )
end fn
window 1
// params: num of args, 1st arg, 2nd arg, etc.
fn Function1( 3, 987, 654, 321 )
print
// params: 1st arg, 2nd arg, ..., NULL
fn Function2( @"One", @"Two", @"Three", @"O'Leary", NULL )
HandleEvents |
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
| #Go | Go | func printAll(things ... string) {
// it's as if you declared "things" as a []string, containing all the arguments
for _, x := range things {
fmt.Println(x)
}
} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Pop11 | Pop11 | ;;; Prints 0 because small integers need no heap storage
datasize(12) =>
;;; Prints 3: 3 character fits into single machine word, 1 word
;;; for tag, 1 for length
datasize('str') =>
;;; 3 element vector takes 5 words: 3 for values, 1 for tag, 1 for
;;; length
datasize({1 2 3}) =>
;;; Prints 3 because only first node counts
datasize([1 2 3]) => |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #PureBasic | PureBasic | Define a
Debug SizeOf(a)
; This also works for structured variables |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Python | Python | >>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
a = array(typecode, initializer)
print a, '\tSize =', a.buffer_info()[1] * a.itemsize
del a
array('l') Size = 0
array('c', 'hello world') Size = 11
array('u', u'hello \u2641') Size = 14
array('l', [1, 2, 3, 4, 5]) Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
>>> |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #ooRexx | ooRexx | v=.vector~new(12,-3); Say "v=.vector~new(12,-3) =>" v~print
v~ab(1,1,6,4); Say "v~ab(1,1,6,4) =>" v~print
v~al(45,2); Say "v~al(45,2) =>" v~print
w=v~'+'(v); Say "w=v~'+'(v) =>" w~print
x=v~'-'(w); Say "x=v~'-'(w) =>" x~print
y=x~'*'(3); Say "y=x~'*'(3) =>" y~print
z=x~'/'(0.1); Say "z=x~'/'(0.1) =>" z~print
::class vector
::attribute x
::attribute y
::method init
Use Arg a,b
self~x=a
self~y=b
::method ab /* set vector from point (a,b) to point (c,d) */
Use Arg a,b,c,d
self~x=c-a
self~y=d-b
::method al /* set vector given angle a and length l */
Use Arg a,l
self~x=l*rxCalccos(a)
self~y=l*rxCalcsin(a)
::method '+' /* add: Return sum of self and argument */
Use Arg v
x=self~x+v~x
y=self~y+v~y
res=.vector~new(x,y)
Return res
::method '-' /* subtract: Return difference of self and argument */
Use Arg v
x=self~x-v~x
y=self~y-v~y
res=.vector~new(x,y)
Return res
::method '*' /* multiply: Return self multiplied by t */
Use Arg t
x=self~x*t
y=self~y*t
res=.vector~new(x,y)
Return res
::method '/' /* divide: Return self divided by t */
Use Arg t
x=self~x/t
y=self~y/t
res=.vector~new(x,y)
Return res
::method print /* prettyprint a vector */
return '['self~x','self~y']'
::requires rxMath Library |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #PHP | PHP | <?php
$str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
$key = "VIGENERECIPHER";
printf("Text: %s\n", $str);
printf("key: %s\n", $key);
$cod = encipher($str, $key, true); printf("Code: %s\n", $cod);
$dec = encipher($cod, $key, false); printf("Back: %s\n", $dec);
function encipher($src, $key, $is_encode)
{
$key = strtoupper($key);
$src = strtoupper($src);
$dest = '';
/* strip out non-letters */
for($i = 0; $i <= strlen($src); $i++) {
$char = substr($src, $i, 1);
if(ctype_upper($char)) {
$dest .= $char;
}
}
for($i = 0; $i <= strlen($dest); $i++) {
$char = substr($dest, $i, 1);
if(!ctype_upper($char)) {
continue;
}
$dest = substr_replace($dest,
chr (
ord('A') +
($is_encode
? ord($char) - ord('A') + ord($key[$i % strlen($key)]) - ord('A')
: ord($char) - ord($key[$i % strlen($key)]) + 26
) % 26
)
, $i, 1);
}
return $dest;
}
?>
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Swift | Swift | import Foundation
let fileSystem = FileManager.default
let rootPath = "/"
// Enumerate the directory tree (which likely recurses internally)...
if let fsTree = fileSystem.enumerator(atPath: rootPath) {
while let fsNodeName = fsTree.nextObject() as? NSString {
let fullPath = "\(rootPath)/\(fsNodeName)"
var isDir: ObjCBool = false
fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir)
if !isDir.boolValue && fsNodeName.pathExtension == "txt" {
print(fsNodeName)
}
}
} |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Tcl | Tcl |
package require fileutil
proc walkin {path cmd} {
set normalized [::fileutil::fullnormalize $path]
set myname [lindex [info level 0] 0]
set children [glob -nocomplain -directory $path -types hidden *]
lappend children {*}[glob -nocomplain -directory $path *]
foreach child $children[set children {}] {
if {[file tail $child] in {. ..}} {
continue
}
if {[file isdirectory $child]} {
if {[file type $child] eq "link"} {
set normalizedchild [fileutil::fullnormalize $child]
if {[string first $normalized/ $normalizedchild] == 0} {
#symlink to a directory in $path. Avoid cyclic traversal.
#Don't descend.
} else {
$myname $child $cmd
}
}
}
{*}$cmd $child
}
}
walkin /home/usr {apply {fname {
set tail [file tail $fname]
if {[string match *.mp3 $tail]} {
puts $fname
}
}}}
|
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #XPL0 | XPL0 | func WaterCollected(Array, Width); \Return amount of water collected
int Array, Width, Height, I, Row, Col, Left, Right, Water;
[Water:= 0; Height:= 0;
for I:= 0 to Width-1 do \find max height
if Array(I) > Height then Height:= Array(I);
for Row:= 2 to Height do
for Col:= 1 to Width-2 do \(zero-based)
if Row > Array(Col) then \empty location
[Left:= false; Right:= false; \check for barriers
for I:= 0 to Width-1 do
if Array(I) >= Row then \have barrier
[if I < Col then Left:= true;
if I > Col then Right:= true;
];
if Left & Right then Water:= Water+1;
];
return Water;
];
int Towers, I;
[Towers:=[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6],
[0]]; \for determining sub-array lengths
for I:= 0 to 7-1 do
[IntOut( 0, WaterCollected(Towers(I), (Towers(I+1)-Towers(I))/4) );
ChOut(0, ^ );
];
] |
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
| #CLU | CLU | vector = cluster [T: type] is make, dot_product, cross_product,
equal, power, mul, unparse
where T has add: proctype (T,T) returns (T) signals (overflow),
sub: proctype (T,T) returns (T) signals (overflow),
mul: proctype (T,T) returns (T) signals (overflow),
equal: proctype (T,T) returns (bool),
unparse: proctype (T) returns (string)
rep = struct[x, y, z: T]
make = proc (x, y, z: T) returns (cvt)
return(rep${x:x, y:y, z:z})
end make
dot_product = proc (a, b: cvt) returns (T) signals (overflow)
return (a.x*b.x + a.y*b.y + a.z*b.z) resignal overflow
end dot_product
cross_product = proc (a, b: cvt) returns (cvt) signals (overflow)
begin
x: T := a.y * b.z - a.z * b.y
y: T := a.z * b.x - a.x * b.z
z: T := a.x * b.y - a.y * b.x
return(down(make(x,y,z)))
end resignal overflow
end cross_product
equal = proc (a, b: cvt) returns (bool)
return (a.x = b.x & a.y = b.y & a.z = b.z)
end equal
% Allow cross_product to be written as ** and dot_product to be written as *
power = proc (a, b: cvt) returns (cvt) signals (overflow)
return(down(cross_product(up(a),up(b)))) resignal overflow
end power
mul = proc (a, b: cvt) returns (T) signals (overflow)
return(dot_product(up(a),up(b))) resignal overflow
end mul
% Standard to_string routine. Properly, `parse' should also be defined,
% and x = parse(unparse(x)) forall x; but I'm not bothering here.
unparse = proc (v: cvt) returns (string)
return( "(" || T$unparse(v.x)
|| ", " || T$unparse(v.y)
|| ", " || T$unparse(v.z) || ")" )
end unparse
end vector
start_up = proc ()
vi = vector[int] % integer math is good enough for the examples
po: stream := stream$primary_output()
a, b, c: vi
a := vi$make(3, 4, 5)
b := vi$make(4, 3, 5)
c := vi$make(-5, -12, -13)
stream$putl(po, " a = " || vi$unparse(a))
stream$putl(po, " b = " || vi$unparse(b))
stream$putl(po, " c = " || vi$unparse(c))
stream$putl(po, " a . b = " || int$unparse(a * b))
stream$putl(po, " a x b = " || vi$unparse(a ** b))
stream$putl(po, "a . (b x c) = " || int$unparse(a * b ** c))
stream$putl(po, "a x (b x c) = " || vi$unparse(a ** b ** c))
end start_up |
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
| #D | D | import std.stdio;
void main() {
auto isins = [
"US0378331005",
"US0373831005",
"U50378331005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040",
];
foreach (isin; isins) {
writeln(isin, " is ", ISINvalidate(isin) ? "valid" : "not valid");
}
}
bool ISINvalidate(string isin) {
import std.array : appender;
import std.conv : to;
import std.regex : matchFirst;
import std.string : strip, toUpper;
isin = isin.strip.toUpper;
if (isin.matchFirst(`^[A-Z]{2}[A-Z0-9]{9}\d$`).empty) {
return false;
}
auto sb = appender!string;
foreach (c; isin[0..12]) {
sb.put(
[c].to!int(36)
.to!string
);
}
import luhn;
return luhnTest(sb.data);
} |
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
| #Cowgol | Cowgol | include "cowgol.coh";
sub vc(n: uint16, base: uint16): (num: uint16, denom: uint16) is
var p: uint16 := 0;
var q: uint16 := 1;
while n != 0 loop
p := p * base + n % base;
q := q * base;
n := n / base;
end loop;
num := p;
denom := q;
while p != 0 loop
n := p;
p := q % p;
q := n;
end loop;
num := num / q;
denom := denom / q;
end sub;
sub printfrac(num: uint16, denom: uint16) is
if num == 0 then
print(" 0");
else
print(" ");
print_i16(num);
print("/");
print_i16(denom);
end if;
end sub;
var i: uint16;
var base: uint16;
var num: uint16;
var denom: uint16;
base := 2;
while base < 6 loop
print("base ");
print_i16(base);
print(":");
i := 0;
while i < 10 loop
(num, denom) := vc(i, base);
printfrac(num, denom);
i := i + 1;
end loop;
print_nl();
base := base + 1;
end loop; |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is
1
×
2
1
+
0
×
2
0
{\displaystyle 1\times 2^{1}+0\times 2^{0}}
.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of
2
−
1
{\displaystyle 2^{-1}}
, or
1
/
2
{\displaystyle 1/2}
.
The weight for the second column to the right of the point is
2
−
2
{\displaystyle 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
. And so on.
If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore
0
×
2
−
1
+
1
×
2
−
2
{\displaystyle 0\times 2^{-1}+1\times 2^{-2}}
or
1
/
4
{\displaystyle 1/4}
.
Distribution of 2500 points each: Van der Corput (top) vs pseudorandom
0
≤
x
<
1
{\displaystyle 0\leq x<1}
Monte Carlo simulations
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
Hint
A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is
1
×
2
3
+
0
×
2
2
+
1
×
2
1
+
1
×
2
0
{\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}}
.
Reflected this would become .1101 or
1
×
2
−
1
+
1
×
2
−
2
+
0
×
2
−
3
+
1
×
2
−
4
{\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}}
Task description
Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2.
Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0).
As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
See also
The Basic Low Discrepancy Sequences
Non-decimal radices/Convert
Van der Corput sequence
| #D | D | double vdc(int n, in double base=2.0) pure nothrow @safe @nogc {
double vdc = 0.0, denom = 1.0;
while (n) {
denom *= base;
vdc += (n % base) / denom;
n /= base;
}
return vdc;
}
void main() {
import std.stdio, std.algorithm, std.range;
foreach (immutable b; 2 .. 6)
writeln("\nBase ", b, ": ", 10.iota.map!(n => vdc(n, b)));
} |
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #ABAP | ABAP | REPORT Z_DECODE_URL.
DATA: lv_encoded_url TYPE string VALUE 'http%3A%2F%2Ffoo%20bar%2F',
lv_decoded_url TYPE string.
CALL METHOD CL_HTTP_UTILITY=>UNESCAPE_URL
EXPORTING
ESCAPED = lv_encoded_url
RECEIVING
UNESCAPED = lv_decoded_url.
WRITE: 'Encoded URL: ', lv_encoded_url, /, 'Decoded URL: ', lv_decoded_url. |
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á".
| #Action.21 | Action! | PROC Append(CHAR ARRAY s CHAR c)
s(0)==+1
s(s(0))=c
RETURN
CHAR FUNC GetCharFromHex(CHAR c1,c2)
CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
BYTE i,res
res=0
FOR i=0 TO 15
DO
IF c1=hex(i) THEN res==+i LSH 4 FI
IF c2=hex(i) THEN res==+i FI
OD
RETURN (res)
PROC Decode(CHAR ARRAY in,out)
BYTE i
CHAR c
out(0)=0
i=1
WHILE i<=in(0)
DO
c=in(i)
i==+1
IF c='+ THEN
Append(out,' )
ELSEIF c='% THEN
c=GetCharFromHex(in(i),in(i+1))
i==+2
Append(out,c)
ELSE
Append(out,c)
FI
OD
RETURN
PROC PrintInv(CHAR ARRAY a)
BYTE i
IF a(0)>0 THEN
FOR i=1 TO a(0)
DO
Put(a(i)%$80)
OD
FI
RETURN
PROC Test(CHAR ARRAY in)
CHAR ARRAY out(256)
PrintInv("input ")
PrintF(" %S%E",in)
Decode(in,out)
PrintInv("decoded")
PrintF(" %S%E%E",out)
RETURN
PROC Main()
Test("http%3A%2F%2Ffoo%20bar%2F")
Test("http%3A%2F%2Ffoo+bar%2F*_-.html")
RETURN |
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
| #AArch64_Assembly | AArch64 Assembly |
//Consts
.equ BUFFERSIZE, 100
.equ STDIN, 0 // linux input console
.equ STDOUT, 1 // linux output console
.equ READ, 63
.equ WRITE, 64
.equ EXIT, 93
.data
enterText: .asciz "Enter text: "
carriageReturn: .asciz "\n"
//Read Buffer
.bss
buffer: .skip BUFFERSIZE
.text
.global _start
quadEnterText: .quad enterText
quadBuffer: .quad buffer
quadCarriageReturn: .quad carriageReturn
writeMessage:
mov x2,0 // reset size counter to 0
checkSize: // get size of input
ldrb w1,[x0,x2] // load char with offset of x2
add x2,x2,#1 // add 1 char read legnth
cbz w1,output // if char found
b checkSize // loop
output:
mov x1,x0 // move string address into system call func parm
mov x0,STDOUT
mov x8,WRITE
svc 0 // trigger system write
ret
_start:
//Output enter text
ldr x0,quadEnterText // load enter message
bl writeMessage // output enter message
//Read User Input
mov x0,STDIN // linux input console
ldr x1,quadBuffer // load buffer address
mov x2,BUFFERSIZE // load buffer size
mov x8,READ // request to read data
svc 0 // trigger system read input
//Output User Message
mov x2, #0 // prep end of string
ldr x1,quadBuffer // load buffer address
strb w2,[x1, x0] // store x2 0 byte at the end of input string, offset x0
ldr x0,quadBuffer // load buffer address
bl writeMessage
//Output newline
ldr x0,quadCarriageReturn
bl writeMessage
//End Program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // trigger end of program
|
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
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC Main()
CHAR ARRAY sUser(255)
REAL r75000,rUser
Put(125) PutE() ;clear the screen
ValR("75000",r75000)
Print("Please enter a text: ")
InputS(sUser)
DO
Print("Please enter number ")
PrintR(r75000) Print(": ")
InputR(rUser)
UNTIL RealEqual(rUser,r75000)
OD
PutE()
Print("Text: ") PrintE(sUser)
Print("Number: ") PrintRE(rUser)
RETURN |
http://rosettacode.org/wiki/UTF-8_encode_and_decode | UTF-8 encode and decode | As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
€ EURO SIGN U+20AC E2 82 AC
𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| #11l | 11l | F unicode_code(ch)
R ‘U+’hex(ch.code).zfill(4)
F utf8hex(ch)
R ch.encode(‘utf-8’).map(c -> hex(c)).join(‘ ’)
print(‘#<11 #<15 #<15’.format(‘Character’, ‘Unicode’, ‘UTF-8 encoding (hex)’))
V chars = [‘A’, ‘ö’, ‘Ж’, ‘€’]
L(char) chars
print(‘#<11 #<15 #<15’.format(char, unicode_code(char), utf8hex(char))) |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #Ada | Ada | with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
package Exported is
function Query (Data : chars_ptr; Size : access size_t)
return int;
pragma Export (C, Query, "Query");
end Exported; |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #C.23 | C# | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo://example.com:8042/over/there?name=ferret#nose");
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true");
ParseUrl("ftp://ftp.is.co.za/rfc/rfc1808.txt");
ParseUrl("http://www.ietf.org/rfc/rfc2396.txt#header1");
ParseUrl("ldap://[2001:db8::7]/c=GB?objectClass?one");
ParseUrl("mailto:[email protected]");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet://192.0.2.16:80/");
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
|
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
| #Apex | Apex | EncodingUtil.urlEncode('http://foo bar/', 'UTF-8') |
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
| #AppleScript | AppleScript | AST URL 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
| #Boo | Boo | a ← 10 |
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
| #BQN | BQN | a ← 10 |
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.
| #Clojure | Clojure | (defn van-eck
([] (van-eck 0 0 {}))
([val n seen]
(lazy-seq
(cons val
(let [next (- n (get seen val n))]
(van-eck next
(inc n)
(assoc seen val n)))))))
(println "First 10 terms:" (take 10 (van-eck)))
(println "Terms 991 to 1000 terms:" (take 10 (drop 990 (van-eck)))) |
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.
| #CLU | CLU | % Generate the first N elements of the Van Eck sequence
eck = proc (n: int) returns (array[int])
ai = array[int]
e: ai := ai$fill(0, n, 0)
for i: int in int$from_to(ai$low(e), ai$high(e)-1) do
for j: int in int$from_to_by(i-1, ai$low(e), -1) do
if e[i] = e[j] then
e[i+1] := i-j
break
end
end
end
return(e)
end eck
% Show 0..9 and 990..999
start_up = proc ()
po: stream := stream$primary_output()
e: array[int] := eck(1000)
stream$puts(po, " 0 - 9: ")
for i: int in int$from_to(0,9) do
stream$putright(po, int$unparse(e[i]), 4)
end
stream$puts(po, "\n990 - 999: ")
for i: int in int$from_to(990,999) do
stream$putright(po, int$unparse(e[i]), 4)
end
stream$putl(po, "")
end start_up |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Haskell | Haskell | import Data.List (sort)
import Control.Arrow ((&&&))
-- VAMPIRE NUMBERS ------------------------------------------------------------
vampires :: [Int]
vampires = filter (not . null . fangs) [1 ..]
fangs :: Int -> [(Int, Int)]
fangs n
| odd w = []
| otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n)
where
ndigit :: Int -> Int
ndigit 0 = 0
ndigit n = 1 + ndigit (quot n 10)
w = ndigit n
xmin = 10 ^ (quot w 2 - 1)
xmax = xmin * 10
isfang x =
x > xmin &&
x < y &&
y < xmax && -- same length
(quot x 10 /= 0 || quot y 10 /= 0) && -- not zero-ended
sort (show n) == sort (show x ++ show y)
where
y = quot n x
-- FACTORS --------------------------------------------------------------------
integerFactors :: Int -> [Int]
integerFactors n
| n < 1 = []
| otherwise =
lows ++
(quot n <$>
(if intSquared == n -- A perfect square,
then tail -- and cofactor of square root would be redundant.
else id)
(reverse lows))
where
(intSquared, lows) =
(^ 2) &&& (filter ((0 ==) . rem n) . enumFromTo 1) $
floor (sqrt $ fromIntegral n)
-- TEST -----------------------------------------------------------------------
main :: IO [()]
main =
mapM
(print . ((,) <*>) fangs)
(take 25 vampires ++ [16758243290880, 24959017348650, 14593825548650]) |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #XPL0 | XPL0 | func OctIn(Dev); \Input from device value of sequence of octets
int Dev, N, Oct;
[N:= 0;
repeat Oct:= HexIn(Dev);
N:= N<<7 + (Oct&$7F);
until (Oct&$80) = 0;
return N;
];
proc OctOut(Dev, Num, Lev); \Output value to device as sequence of octets
int Dev, Num, Lev, Rem;
[Rem:= Num & $7F;
Num:= Num >> 7;
if Num # 0 then OctOut(Dev, Num, Lev+1);
if Lev > 0 then Rem:= Rem + $80;
SetHexDigits(2);
HexOut(Dev, Rem);
ChOut(Dev, ^ );
];
\Device 8 is a circular buffer that can be written and read back.
int N;
[for N:= 0 to $40_0000 do
[OctOut(8, N, 0);
if N # OctIn(8) then
[Text(0, "Error!"); exit];
];
OctOut(0, $1F_FFFF, 0); CrLf(0);
OctOut(0, $20_0000, 0); CrLf(0);
OctOut(0, $7F, 0); CrLf(0);
OctOut(0, $4000, 0); CrLf(0);
OctOut(0, 0, 0); CrLf(0);
OctOut(0, $3F_FFFE, 0); CrLf(0);
OctOut(0, $FFFF_FFFF, 0); CrLf(0);
] |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
display these sequences of octets;
convert these sequences of octets back to numbers, and check that they are equal to original numbers.
| #zkl | zkl | fcn to_seq(x){ //--> list of ints
z:=(x.log2()/7);
(0).pump(z+1,List,'wrap(j){
x.shiftRight((z-j)*7).bitAnd(0x7f).bitOr((j!=z) and 0x80 or 0)
});
}
fcn from_seq(in){ in.reduce(fcn(p,n){ p.shiftLeft(7).bitOr(n.bitAnd(0x7f)) },0) } |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Golo | Golo | #!/usr/bin/env golosh
----
This module demonstrates variadic functions.
----
module Variadic
import gololang.Functions
----
Varargs have the three dots after them just like Java.
----
function varargsFunc = |args...| {
foreach arg in args {
println(arg)
}
}
function main = |args| {
varargsFunc(1, 2, 3, 4, 5, "against", "one")
# to call a variadic function with an array we use the unary function
unary(^varargsFunc)(args)
} |
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
| #Groovy | Groovy | def printAll( Object[] args) { args.each{ arg -> println arg } }
printAll(1, 2, "three", ["3", "4"]) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #R | R | # Results are system dependent
num <- c(1, 3, 6, 10)
object.size(num) # e.g. 56 bytes
#Allocating vectors using ':' results in less memory being (reportedly) used
num2 <- 1:4
object.size(num2) # e.g. 40 bytes
#Memory shared by objects isn't always counted
l <- list(a=c(1, 3, 6, 10), b=1:4)
object.size(l) # e.g. 280 bytes
l2 <- list(num, num2)
object.size(l2) # e.g. 128 bytes |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Racket | Racket |
#lang racket
(require ffi/unsafe)
(define-syntax-rule (sizes t ...)
(begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(sizes _byte _short _int _long _llong _float _double)
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Raku | Raku | # Textual strings are measured in characters (graphemes)
my $string = "abc";
# Arrays are measured in elements.
say $string.chars; # 3
my @array = 1..5;
say @array.elems; # 5
# Buffers may be viewed either as a byte-string or as an array of elements.
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes; # 26
say $buffer.elems; # 26 |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Perl | Perl | package Vector;
use Moose;
use feature 'say';
use overload '+' => \&add,
'-' => \&sub,
'*' => \&mul,
'/' => \&div,
'""' => \&stringify;
has 'x' => (is =>'rw', isa => 'Num', required => 1);
has 'y' => (is =>'rw', isa => 'Num', required => 1);
sub add {
my($a, $b) = @_;
Vector->new( x => $a->x + $b->x, y => $a->y + $b->y);
}
sub sub {
my($a, $b) = @_;
Vector->new( x => $a->x - $b->x, y => $a->y - $b->y);
}
sub mul {
my($a, $b) = @_;
Vector->new( x => $a->x * $b, y => $a->y * $b);
}
sub div {
my($a, $b) = @_;
Vector->new( x => $a->x / $b, y => $a->y / $b);
}
sub stringify {
my $self = shift;
"(" . $self->x . "," . $self->y . ')';
}
package main;
my $a = Vector->new(x => 5, y => 7);
my $b = Vector->new(x => 2, y => 3);
say "a: $a";
say "b: $b";
say "a+b: ",$a+$b;
say "a-b: ",$a-$b;
say "a*11: ",$a*11;
say "a/2: ",$a/2; |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #PicoLisp | PicoLisp | (de vigenereKey (Str)
(extract
'((C)
(when (>= "Z" (uppc C) "A")
(- (char (uppc C)) 65) ) )
(chop Str) ) )
(de vigenereEncrypt (Str Key)
(pack
(mapcar
'((C K)
(char (+ 65 (% (+ C K) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) )
(de vigenereDecrypt (Str Key)
(pack
(mapcar
'((C K)
(char (+ 65 (% (+ 26 (- C K)) 26))) )
(vigenereKey Str)
(apply circ (vigenereKey Key)) ) ) ) |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #PL.2FI | PL/I |
cypher: procedure options (main); /* 21 September 2012 */
declare t(26) character (26);
declare (i, j, k, L) fixed binary;
declare (original, encoded, coder) character (1000) varying initial ('');
declare cypher character (30) varying;
declare (co, ct, cc) character (1);
/* Set up cypher table. */
t(1) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
do i = 2 to 26;
t(i) = substr(t(i-1), 2, 25) || substr(t(i-1), 1, 1);
end;
cypher = 'VIGILANCE';
original = 'Meet me on Tuesday evening at seven.';
put edit ('Message=', original) (a);
original = uppercase(original);
/* Create the cypher text, same length as original, or longer. */
coder = repeat(cypher, length(original)/length(cypher));
/* Encode the original message, character by character. */
/* Non-alphabetic characters are ignored. */
L = 0;
do i = 1 to length(original);
co = substr(original, i, 1);
j = index(t(1), co);
if j = 0 then iterate; /* Ignore non-alphabetic character */
L = L + 1;
ct = substr(coder, L, 1);
k = index(t(1), ct);
encoded = encoded || substr(t(j), k, 1);
end;
put skip data (encoded);
/* DECODING. */
put skip list ('Decoded=');
do i = 1 to length(encoded);
cc = substr(coder, i, 1);
j = index(t(1), cc);
k = index(t(j), substr(encoded, i, 1));
put edit (substr(t(1), k, 1) ) (a(1));
end;
end cypher;
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #TXR | TXR | (build (ftw "." (lambda (path type stat level base)
(if (ends-with ".tl" path)
(add path))))) |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #UNIX_Shell | UNIX Shell | find . -name '*.txt' -type f |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Yabasic | Yabasic | data 7
data "1,5,3,7,2", "5,3,7,2,6,4,5,9,1,2", "2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1"
data "5,5,5,5", "5,6,7,8", "8,7,7,6", "6,7,10,7,6"
read n
for i = 1 to n
read n$
wcbt(n$)
next i
sub wcbt(s$)
local tower$(1), hr(1), hl(1), n, i, ans, k
n = token(s$, tower$(), ",")
redim hr(n)
redim hl(n)
for i = n to 1 step -1
if i < n then
k = hr(i + 1)
else
k = 0
end if
hr(i) = max(val(tower$(i)), k)
next i
for i = 1 to n
if i then
k = hl(i - 1)
else
k = 0
end if
hl(i) = max(val(tower$(i)), k)
ans = ans + min(hl(i), hr(i)) - val(tower$(i))
next i
print ans," ",n$
end sub |
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
| #Common_Lisp | Common Lisp | (defclass 3d-vector ()
((x :type number :initarg :x)
(y :type number :initarg :y)
(z :type number :initarg :z)))
(defmethod print-object ((object 3d-vector) stream)
(print-unreadable-object (object stream :type t)
(with-slots (x y z) object
(format stream "~a ~a ~a" x y z))))
(defun make-3d-vector (x y z)
(make-instance '3d-vector :x x :y y :z z))
(defmethod dot-product ((a 3d-vector) (b 3d-vector))
(with-slots ((a1 x) (a2 y) (a3 z)) a
(with-slots ((b1 x) (b2 y) (b3 z)) b
(+ (* a1 b1) (* a2 b2) (* a3 b3)))))
(defmethod cross-product ((a 3d-vector)
(b 3d-vector))
(with-slots ((a1 x) (a2 y) (a3 z)) a
(with-slots ((b1 x) (b2 y) (b3 z)) b
(make-instance '3d-vector
:x (- (* a2 b3) (* a3 b2))
:y (- (* a3 b1) (* a1 b3))
:z (- (* a1 b2) (* a2 b1))))))
(defmethod scalar-triple-product ((a 3d-vector)
(b 3d-vector)
(c 3d-vector))
(dot-product a (cross-product b c)))
(defmethod vector-triple-product ((a 3d-vector)
(b 3d-vector)
(c 3d-vector))
(cross-product a (cross-product b c)))
(defun vector-products-example ()
(let ((a (make-3d-vector 3 4 5))
(b (make-3d-vector 4 3 5))
(c (make-3d-vector -5 -12 -13)))
(values (dot-product a b)
(cross-product a b)
(scalar-triple-product a b c)
(vector-triple-product a b c)))) |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
Details
The format of an ISIN is as follows:
┌───────────── a 2-character ISO country code (A-Z)
│ ┌─────────── a 9-character security code (A-Z, 0-9)
│ │ ┌── a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103.
Perform the Luhn test on this base-10 number.
There is a separate task for this test: Luhn test of credit card numbers.
You don't have to replicate the implementation of this test here ─── you can just call the existing function from that task. (Add a comment stating if you did this.)
Test cases
ISIN
Validity
Comment
US0378331005
valid
US0373831005
not valid
The transposition typo is caught by the checksum constraint.
U50378331005
not valid
The substitution typo is caught by the format constraint.
US03378331005
not valid
The duplication typo is caught by the format constraint.
AU0000XVGZA3
valid
AU0000VXGZA3
valid
Unfortunately, not all transposition typos are caught by the checksum constraint.
FR0000988040
valid
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Luhn test of credit card numbers
Also see
Interactive online ISIN validator
Wikipedia article: International Securities Identification Number
| #Elixir | Elixir | isin? = fn str ->
if str =~ ~r/\A[A-Z]{2}[A-Z0-9]{9}\d\z/ do
String.codepoints(str)
|> Enum.map_join(&String.to_integer(&1, 36))
|> Luhn.valid?
else
false
end
end
IO.puts " ISIN Valid?"
~w(US0378331005
US0373831005
U50378331005
US03378331005
AU0000XVGZA3
AU0000VXGZA3
FR0000988040)
|> Enum.each(&IO.puts "#{&1}\t#{isin?.(&1)}") |
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
| #Factor | Factor | USING: combinators.short-circuit.smart formatting kernel luhn
math math.parser qw sequences strings unicode ;
IN: rosetta-code.isin
CONSTANT: test-cases qw{
US0378331005 US0373831005 U50378331005 US03378331005
AU0000XVGZA3 AU0000VXGZA3 FR0000988040
}
: valid-length? ( str -- ? ) length 12 = ;
: valid-country-code? ( str -- ? ) first2 [ Letter? ] both? ;
: valid-security-code? ( str -- ? )
[ 2 11 ] dip subseq [ alpha? ] all? ;
: valid-checksum-digit? ( str -- ? ) last digit? ;
: valid-format? ( str -- ? ) {
[ valid-length? ]
[ valid-country-code? ]
[ valid-security-code? ]
[ valid-checksum-digit? ]
} && ;
: base36>base10 ( str -- n )
>upper [ dup LETTER? [ 55 - number>string ] [ 1string ] if ]
{ } map-as concat string>number ;
: isin? ( str -- ? )
{ [ valid-format? ] [ base36>base10 luhn? ] } && ;
: main ( -- )
test-cases [
dup isin? "" " not" ? "%s is%s valid\n" printf
] each ;
MAIN: main |
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
| #EasyLang | EasyLang | func vdc b n . v .
s = 1
v = 0
while n > 0
s *= b
m = n mod b
v += m / s
n = n div b
.
.
for b = 2 to 5
write "base " & b & ":"
for n range 10
call vdc b n v
write " " & v
.
print ""
. |
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
| #EDSAC_order_code | EDSAC order code |
[Van der Corput sequence for Rosetta Code.
EDSAC solution, Initial Orders 2.]
[Library subroutine M3 - prints header at load time and is then overwritten.
Here, the last character sets the teleprinter to figures.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*VAN!DER!CORPUT!SEQUENCE@A*BIT!!!#35A*BIT@&#
..PZ [blank tape then re-sync]
[Define load addresses]
T55K P100F [V parameter: van der Corput subroutines]
T51K P64F [G parameter: print subroutine]
T47K P400F [M parameter: main routine]
[Subroutines to return n'th element of van der Corput sequence.
17-bit version: Call by GV, pass n in 0F (not preserved), result in 4F.
35-bit version: Call by G1V, pass n in 0D (not preserved), result in 4D.]
E25K TV GK
G2@ [jump to 17-bit version]
G25@ [jump to 35-bit version]
[17-bit version.
On EDSAC, it's a matter of reversing the bits after the binary point
To save time, we use a table to reverse the 16 bits in groups of 4.]
[2] A3F T24@ [plant return link as usual]
H5 6@ [set mult reg to 0...01111 binary]
A55@ T4F [set marker bit 0...01 in result]
[7] A4F L4F T4F [shift result 4 left]
CF [acc := next 4 bits of n]
LD [shift into address field]
A58@ T14@ [plant A order to load from table]
[14] AF [{planted) load bits from table]
A4F [add to result]
G22@ [jump out if marker bit has reached sign bit]
T4F [update result]
AF R4F TF [shift n 4 right]
E7@ [always loop back]
[22] S57@ [done, remove marker bit]
T4F [store final result]
[24] ZF [(planted) jump to return to caller]
[35-bit version. Very similar to the 17-bit version, except that
after reversing 8 groups of 4, there are 2 bits left over,
which require separate treatment.]
[25] A3F T54@ [plant return link as usual]
H56@ [set mult reg to 0...01111 binary]
YF L2F [set marker bit 0...0100 in result]
[30] L4F T4D [shift result 4 left]
CF LD A58@ T36@ AF A4F T4F [update from table as in 17-bit version]
ADR4FTD [shift n 4 right]
A4D [load result]
E30@ [if marker bit hasn't reached sign bit, loop back]
[Last 2 bits]
[44] L1FT4D [shift result 2 right]
CF LD A58@ T50@ [plant A order as in 17-bit version]
[50] AF [Planted) load bits from table]
R1F A4F T4F [shift table entry 2 right and add to result]
[54] ZF [(planted) jump to return to caller]
[Constants]
[55] PD [17-bit 1]
[56] P7D [17-bit 15]
[57] K4096F [17-bit 10...0 binary]
[58] A59@ [order to load from table{0}]
[Table to reverse group of 4 bits, e.g. table{0010b} = 0100b]
[59] PFP4FP2FP6FP1FP5FP3FP7FPDP4DP2DP6DP1DP5DP3DP7D
[Library subroutine P1 to print number in range 0 <= x < 1.
Caller must print leading '0.' if required. 21 storage locations.]
E25K TG
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Main routine]
E25K TM GK
[0] PF PF [n, 35 bits, must be at even address]
[2] PF [negative count of terms]
[3] P10F [<=== EDIT number of terms, in address field]
[4] PD [17-bit integer 1]
[5] MF [dot (in figures mode)]
[6] @F [carriage return]
[7] &F [line feed]
[8] !F [space character]
[9] K4096F [null character]
[Enter with acc = 0]
[10] T#@ [n := 0]
S3@ T2@ [initialize negative count]
[13] A@ TF [pass 17-bit n in 0F]
[15] A15@ GV [call 17-bit van der Corput routine]
TD [clear 0D, including sandwich bit]
A4F T1F [extend 17-bit result to 35 bits in 0D]
O4@ O5@ [print '0.']
[22] A22@ GG P5F [print result to 5 decimals]
O8@ O8@ [print 2 spaces]
A#@ TD [pass 35-bit n in 0D]
[29] A29@ G1V [call 35-bit van der Corput routine]
A4D TD [pass result in 0D]
O4@ O5@ [print '0.']
[35] A35@ GG P10F [print result to 10 decimals]
O6@ O7@ [print CR LF]
A2@ A2F [inc negative count]
E48@ [jump out if count = 0]
T2@ [update count]
A@ A4@ T@ [inc n]
E13@ [loop back]
[48] O9@ [print null to flush teleprinter buffer]
ZF [stop]
E10Z [define entry point]
PF [acc = 0 on entry]
[end]
|
http://rosettacode.org/wiki/URL_decoding | URL decoding | This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
Test cases
The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá".
| #Ada | Ada | with AWS.URL;
with Ada.Text_IO; use Ada.Text_IO;
procedure Decode is
Encoded : constant String := "http%3A%2F%2Ffoo%20bar%2F";
begin
Put_Line (AWS.URL.Decode (Encoded));
end Decode;
|
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á".
| #ALGOL_68 | ALGOL 68 | # returns c decoded as a hex digit #
PROC hex value = ( CHAR c )INT: IF c >= "0" AND c <= "9" THEN ABS c - ABS "0"
ELIF c >= "A" AND c <= "F" THEN 10 + ( ABS c - ABS "A" )
ELSE 10 + ( ABS c - ABS "a" )
FI;
# returns the URL encoded string decoded - minimal error handling #
PROC url decode = ( STRING encoded )STRING:
BEGIN
[ LWB encoded : UPB encoded ]CHAR result;
INT result pos := LWB encoded;
INT pos := LWB encoded;
INT max pos := UPB encoded;
INT max encoded := max pos - 3;
WHILE pos <= UPB encoded
DO
IF encoded[ pos ] /= "%" AND pos <= max encoded
THEN
# not a coded character #
result[ result pos ] := encoded[ pos ];
pos +:= 1
ELSE
# have an encoded character #
result[ result pos ] := REPR ( ( 16 * hex value( encoded[ pos + 1 ] ) )
+ hex value( encoded[ pos + 2 ] )
);
pos +:= 3
FI;
result pos +:= 1
OD;
result[ LWB result : result pos - 1 ]
END # url decode # ;
# test the url decode procedure #
print( ( url decode( "http%3A%2F%2Ffoo%20bar%2F" ), newline ) );
print( ( url decode( "google.com/search?q=%60Abdu%27l-Bah%C3%A1" ), newline ) ) |
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
| #Ada | Ada | function Get_String return String is
Line : String (1 .. 1_000);
Last : Natural;
begin
Get_Line (Line, Last);
return Line (1 .. Last);
end Get_String;
function Get_Integer return Integer is
S : constant String := Get_String;
begin
return Integer'Value (S);
-- may raise exception Constraint_Error if value entered is not a well-formed integer
end Get_Integer;
|
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #ALGOL_68 | ALGOL 68 | print("Enter a string: ");
STRING s := read string;
print("Enter a number: ");
INT i := read int;
~ |
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.
| #8th | 8th |
hex \ so bytes print nicely
[
"\u0041",
"\u00F6",
"\u0416",
"\u20AC"
]
\ add the 0x1D11E one; the '\u' string notation requires four hex digits
"" 1D11E s:+ a:push
\ for each test, print it out and its bytes:
(
dup . space
b:new
( . space drop ) b:each
cr
) a:each! drop
cr
\ now the inverse:
[
[41],
[C3,B6],
[D0,96],
[E2,82,AC],
[$F0,9D,84,9E]
]
(
dup . space
b:new >s . cr
) a:each! drop
bye
|
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.
| #Action.21 | Action! | TYPE Unicode=[BYTE bc1,bc2,bc3]
BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
BYTE FUNC DecodeHex(CHAR c)
BYTE i
FOR i=0 TO 15
DO
IF c=hex(i) THEN
RETURN (i)
FI
OD
Break()
RETURN (255)
BYTE FUNC DecodeHex2(CHAR c1,c2)
BYTE h1,h2,res
h1=DecodeHex(c1)
h2=DecodeHex(c2)
res=(h1 LSH 4)%h2
RETURN (res)
PROC ValUnicode(CHAR ARRAY s Unicode POINTER u)
BYTE i,len
len=s(0)
IF len<6 AND len>8 THEN Break() FI
IF s(1)#'U OR s(2)#'+ THEN Break() FI
IF len=6 THEN
u.bc1=0
ELSEIF len=7 THEN
u.bc1=DecodeHex(s(3))
IF u.bc1>$10 THEN Break() FI
ELSE
u.bc1=DecodeHex2(s(3),s(4))
FI
u.bc2=DecodeHex2(s(len-3),s(len-2))
u.bc3=DecodeHex2(s(len-1),s(len))
RETURN
PROC PrintHex2(BYTE x)
Put(hex(x RSH 4))
Put(hex(x&$0F))
RETURN
PROC StrUnicode(Unicode POINTER u)
Print("U+")
IF u.bc1>$F THEN
PrintHex2(u.bc1)
ELSEIF u.bc1>0 THEN
Put(hex(u.bc1))
FI
PrintHex2(u.bc2)
PrintHex2(u.bc3)
RETURN
PROC PrintArray(BYTE ARRAY a BYTE len)
BYTE i
Put('[)
FOR i=0 TO len-1
DO
IF i>0 THEN Put(32 )FI
PrintHex2(a(i))
OD
Put('])
RETURN
PROC Encode(Unicode POINTER u BYTE ARRAY buf BYTE POINTER len)
IF u.bc1>0 THEN
len^=4
buf(0)=$F0 % (u.bc1 RSH 2)
buf(1)=$80 % ((u.bc1 & $03) LSH 4) % (u.bc2 RSH 4)
buf(2)=$80 % ((u.bc2 & $0F) LSH 2) % (u.bc3 RSH 6)
buf(3)=$80 % (u.bc3 & $3F)
ELSEIF u.bc2>=$08 THEN
len^=3
buf(0)=$E0 % (u.bc2 RSH 4)
buf(1)=$80 % ((u.bc2 & $0F) LSH 2) % (u.bc3 RSH 6)
buf(2)=$80 % (u.bc3 & $3F)
ELSEIF u.bc2>0 OR u.bc3>=$80 THEN
len^=2
buf(0)=$C0 % (u.bc2 LSH 2) % (u.bc3 RSH 6)
buf(1)=$80 % (u.bc3 & $3F)
ELSE
len^=1
buf(0)=u.bc3
FI
RETURN
PROC Decode(BYTE ARRAY buf BYTE len Unicode POINTER u)
IF len=1 THEN
u.bc1=0
u.bc2=0
u.bc3=buf(0)
ELSEIF len=2 THEN
u.bc1=0
u.bc2=(buf(0) & $1F) RSH 2
u.bc3=(buf(0) LSH 6) % (buf(1) & $3F)
ELSEIF len=3 THEN
u.bc1=0
u.bc2=(buf(0) LSH 4) % ((buf(1) & $3F) RSH 2)
u.bc3=(buf(1) LSH 6) % (buf(2) & $3F)
ELSEIF len=4 THEN
u.bc1=((buf(0) & $07) LSH 2) % ((buf(1) & $3F) RSH 4)
u.bc2=(buf(1) LSH 4) % ((buf(2) & $3F) RSH 2)
u.bc3=((buf(2) & $03) LSH 6) % (buf(3) & $3F)
ELSE
Break()
FI
RETURN
PROC Main()
DEFINE PTR="CARD"
DEFINE COUNT="11"
PTR ARRAY case(COUNT)
Unicode uni,res
BYTE ARRAY buf(4)
BYTE i,len
case(0)="U+0041"
case(1)="U+00F6"
case(2)="U+0416"
case(3)="U+20AC"
case(4)="U+1D11E"
case(5)="U+0024"
case(6)="U+00A2"
case(7)="U+0939"
case(8)="U+20AC"
case(9)="U+D55C"
case(10)="U+10348"
FOR i=0 TO COUNT-1
DO
IF i=0 THEN
PrintE("From RosettaCode:")
ELSEIF i=5 THEN
PutE() PrintE("From Wikipedia:")
FI
ValUnicode(case(i),uni)
Encode(uni,buf,@len)
Decode(buf,len,res)
StrUnicode(uni) Print(" -> ")
PrintArray(buf,len) Print(" -> ")
StrUnicode(res) PutE()
OD
RETURN |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #AutoHotkey | AutoHotkey | ; Example: The following is a working script that displays a summary of all top-level windows.
; For performance and memory conservation, call RegisterCallback() only once for a given callback:
if not EnumAddress ; Fast-mode is okay because it will be called only from this thread:
EnumAddress := RegisterCallback("EnumWindowsProc", "Fast")
DetectHiddenWindows On ; Due to fast-mode, this setting will go into effect for the callback too.
; Pass control to EnumWindows(), which calls the callback repeatedly:
DllCall("EnumWindows", UInt, EnumAddress, UInt, 0)
MsgBox %Output% ; Display the information accumulated by the callback.
EnumWindowsProc(hwnd, lParam)
{
global Output
WinGetTitle, title, ahk_id %hwnd%
WinGetClass, class, ahk_id %hwnd%
if title
Output .= "HWND: " . hwnd . "`tTitle: " . title . "`tClass: " . class . "`n"
return true ; Tell EnumWindows() to continue until all windows have been enumerated.
} |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
| #C | C | #if 0
I rewrote the driver according to good sense, my style,
and discussion.
This is file main.c on Autumn 2011 ubuntu linux release.
The emacs compile command output:
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Mon Mar 12 20:25:27
make -k CFLAGS=-Wall main.o
cc -Wall -c -o main.o main.c
Compilation finished at Mon Mar 12 20:25:27
#endif
#include <stdio.h>
#include <stdlib.h>
extern int Query(char *Data, unsigned *Length);
int main(int argc, char *argv[]) {
char Buffer[1024], *pc;
unsigned Size = sizeof(Buffer);
if (!Query(Buffer, &Size))
fputs("failed to call Query", stdout);
else
for (pc = Buffer; Size--; ++pc)
putchar(*pc);
putchar('\n');
return EXIT_SUCCESS;
}
|
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Crystal | Crystal | require "uri"
examples = ["foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"https://bob:password@[::1]/place?a=1&b=2%202"]
examples.each do |example|
puts "Parsing \"#{example}\":"
url = URI.parse example
{% for name in ["scheme", "host", "hostname", "port", "path", "userinfo",
"user", "password", "fragment", "query"] %}
unless url.{{name.id}}.nil?
puts " {{name.id}}: \"#{url.{{name.id}}}\""
end
{% end %}
unless url.query_params.empty?
puts " query_params:"
url.query_params.each do |k, v|
puts " #{k}: \"#{v}\""
end
end
puts
end |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, the characters:
! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded (%) in case of possible confusion.
Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
Here is the official standard: https://tools.ietf.org/html/rfc3986,
and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
Test cases
According to T. Berners-Lee
foo://example.com:8042/over/there?name=ferret#nose should parse into:
scheme = foo
domain = example.com
port = :8042
path = over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose should parse into:
scheme = urn
path = example:animal:ferret:nose
other URLs that must be parsed include:
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:[email protected]
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| #Elixir | Elixir | test_cases = [
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://[email protected]",
"https://bob:[email protected]/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
]
Enum.each(test_cases, fn str ->
IO.puts "\n#{str}"
IO.inspect URI.parse(str)
end) |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #Arturo | Arturo | encoded: encode.url.slashes "http://foo bar/"
print encoded |
http://rosettacode.org/wiki/URL_encoding | URL encoding | Task
Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
Extended characters with character codes of 128 decimal (80 hex) and above.
Example
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
Variations
Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards.
Options
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
Related tasks
URL decoding
URL parser
| #AutoHotkey | AutoHotkey | MsgBox, % UriEncode("http://foo bar/")
; Modified from http://goo.gl/0a0iJq
UriEncode(Uri)
{
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
f := A_FormatInteger
SetFormat, IntegerFast, H
While Code := NumGet(Var, A_Index - 1, "UChar")
If (Code >= 0x30 && Code <= 0x39 ; 0-9
|| Code >= 0x41 && Code <= 0x5A ; A-Z
|| Code >= 0x61 && Code <= 0x7A) ; a-z
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
SetFormat, IntegerFast, %f%
Return, Res
} |
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
| #Bracmat | Bracmat | (myfunc=i j.!arg:(?i.?j)&!i+!j) |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. VAN-ECK.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CALCULATION.
02 ECK PIC 999 OCCURS 1000 TIMES.
02 I PIC 9999.
02 J PIC 9999.
01 OUTPUT-FORMAT.
02 ITEM PIC ZZ9.
02 IDX PIC ZZZ9.
PROCEDURE DIVISION.
B. PERFORM GENERATE-ECK.
PERFORM SHOW VARYING I FROM 1 BY 1 UNTIL I = 11.
PERFORM SHOW VARYING I FROM 991 BY 1 UNTIL I = 1001.
STOP RUN.
SHOW.
MOVE I TO IDX.
MOVE ECK(I) TO ITEM.
DISPLAY 'ECK(' IDX ') = ' ITEM.
GENERATE-ECK SECTION.
B. SET ECK(1) TO 0.
SET I TO 1.
PERFORM GENERATE-TERM
VARYING I FROM 2 BY 1 UNTIL I = 1001.
GENERATE-TERM SECTION.
B. SUBTRACT 2 FROM I GIVING J.
LOOP.
IF J IS LESS THAN 1 GO TO TERM-IS-NEW.
IF ECK(J) = ECK(I - 1) GO TO TERM-IS-OLD.
SUBTRACT 1 FROM J.
GO TO LOOP.
TERM-IS-NEW.
SET ECK(I) TO 0.
GO TO DONE.
TERM-IS-OLD.
COMPUTE ECK(I) = (I - J) - 1.
DONE. EXIT. |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactly the same decimal digits as the original number
at most one of them has a trailing zero
An example of a vampire number and its fangs: 1260 : (21, 60)
Task
Print the first 25 vampire numbers and their fangs.
Check if the following numbers are vampire numbers and, if so, print them and their fangs:
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
See also
numberphile.com.
vampire search algorithm
vampire numbers on OEIS
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write("First 25 vampire numbers and their fangs:")
every fangs := vampire(n := seq())\25 do write(right(n,20),":",fangs)
write("\nOther numbers:")
every n := 16758243290880 | 24959017348650 | 14593825548650 do
write(right(n,20),": ",vampire(n)|"toothless")
end
procedure vampire(n)
ns := string(n)
if *ns % 2 = 1 then fail
every (fangs := "") ||:= " "||fangCheck(n, *ns/2, f1 := 2 to integer(sqrt(n)), n/f1)
if *fangs > 0 then return fangs
end
procedure fangCheck(n, n2, f1, f2)
if f1*f2 ~= n then fail
if n2 ~= *(f1|f2) then fail
if (f1|f2) % 10 ~= 0 then
if csort(f1||f2) == csort(n) then return "("||f1||","||f2||")"
end
procedure csort(s) # Adapted from csort(s) in Icon IPL
every (s1 := "", c := !cset(s)) do every find(c, s) do s1 ||:= c
return s1
end |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Haskell | Haskell | class PrintAllType t where
process :: [String] -> t
instance PrintAllType (IO a) where
process args = do mapM_ putStrLn args
return undefined
instance (Show a, PrintAllType r) => PrintAllType (a -> r) where
process args = \a -> process (args ++ [show a])
printAll :: (PrintAllType t) => t
printAll = process []
main :: IO ()
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
printAll 4 3 5
printAll "Rosetta" "Code" "Is" "Awesome!" |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function
| #Icon_and_Unicon | Icon and Unicon | procedure main ()
varargs("some", "extra", "args")
write()
varargs ! ["a","b","c","d"]
end
procedure varargs(args[])
every write(!args)
end |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #REXX | REXX | /*REXX program demonstrates (see the penultimate statement) how to */
/* to find the size (length) of the value of a REXX variable. */
/*REXX doesn't reserve any storage for any variables, as all variables */
/*are stored as character strings, including boolean. Storage is */
/*obtained as necessary when REXX variables are assigned (or reassigned)*/
a = 456 /*length of A is 3 */
b = "heptathlon" /*length of B is 10 */
c = "heptathlon (7 events)" /*length of C is 21 */
d = '' /*length of D is 0 */
d = "" /*same as above. */
d = left('space junk' ,0) /*same as above. */
d = /*same as above. */
e = 99-9 /*length of E is 2 (e=90) */
f = copies(a,100) /*length of F is 300 (a=456)*/
g.1 = -1 /*length of G.1 is 2 */
g.2 = -1.0000 /*length of G.2 is 7 */
/*length of HHH is 3 */
/*Note that when a REXX variable */
/*isn't SET, then the value of it*/
/*is the uppercased name itself, */
/*so in this case (upper): HHH */
something = copies(a, random(100)) /*length is something, all right,*/
/*could be 3 to 300 bytes, by gum*/
thingLen = length(something) /*use LENGTH bif to find its len.*/
say 'length of SOMETHING =' thingLen /*display the length of SOMETHING*/
/*┌────────────────────────────────────────────────────────────────────┐
│ Note that the variable's data (value) isn't the true cost of the │
│ size of the variable's value. REXX also keeps the name of │
│ the (fully qualified) variable as well. │
│ │
│ Most REXX interpreters keep (at a miminum): │
│ │
│ ∙ a four-byte field which contains the length of the value │
│ ∙ a four-byte field which contains the length of the var name │
│ ∙ an N-byte field which contains the name of the variable │
│ ∙ an X-byte field which contains the variable's value │
│ ∙ a one-byte field which contains the status of the variable │
│ │
│ [Note that PC/REXX uses a two-byte field for the first two fields] │
│ │
│ │
│ Consider the following two DO loops assigning a million variables: │
│ │
│ do j=1 to 1000000 │
│ integer_numbers.j=j │
│ end │
│ ════════ and ════════ │
│ do k=1 to 1000000 │
│ #.k=k │
│ end │
│ │
│ The "j" loop uses 35,777,792 bytes for the compound variables, │
│ The "k" loop uses 21,777,792 bytes for the compound variables, │
│ (excluding the DO loop indices [j and k] themselves). │
└────────────────────────────────────────────────────────────────────┘*/ |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Ring | Ring |
list1 = list(2)
list2 = list(4)
list3 = list(6)
list4 = list(7)
list5 = list(5)
see "Size of list1 is : " + len(list1) + nl
see "Size of list2 is : " + len(list2) + nl
see "Size of list3 is : " + len(list3) + nl
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Ruby | Ruby |
require 'objspace'
p ObjectSpace.memsize_of("a"*23) #=> 0
p ObjectSpace.memsize_of("a"*24) #=> 25
p ObjectSpace.memsize_of("a"*1000) #=> 1001
|
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Phix | Phix | constant a = {5,7}, b = {2, 3}
?sq_add(a,b)
?sq_sub(a,b)
?sq_mul(a,11)
?sq_div(a,2)
|
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to be implemented are:
Vector + Vector addition
Vector - Vector subtraction
Vector * scalar multiplication
Vector / scalar division
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def add + enddef
def sub - enddef
def mul * enddef
def div / enddef
def opVect /# a b op -- a b c #/
var op
list? not if swap len rot swap repeat endif
len var lon
( lon 1 -1 ) for var i
i get rot i get rot op exec >ps swap
endfor
lon for drop
ps>
endfor
lon tolist
enddef
( 5 7 ) ( 2 3 )
getid add opVect ?
getid sub opVect ?
drop 2
getid mul opVect ?
getid div opVect ? |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a Vigenère cypher, both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Caesar cipher
Rot-13
Substitution Cipher
| #PowerShell | PowerShell | # Author: D. Cudnohufsky
function Get-VigenereCipher
{
Param
(
[Parameter(Mandatory=$true)]
[string] $Text,
[Parameter(Mandatory=$true)]
[string] $Key,
[switch] $Decode
)
begin
{
$map = [char]'A'..[char]'Z'
}
process
{
$Key = $Key -replace '[^a-zA-Z]',''
$Text = $Text -replace '[^a-zA-Z]',''
$keyChars = $Key.toUpper().ToCharArray()
$Chars = $Text.toUpper().ToCharArray()
function encode
{
param
(
$Char,
$keyChar,
$Alpha = [char]'A'..[char]'Z'
)
$charIndex = $Alpha.IndexOf([int]$Char)
$keyIndex = $Alpha.IndexOf([int]$keyChar)
$NewIndex = ($charIndex + $KeyIndex) - $Alpha.Length
$Alpha[$NewIndex]
}
function decode
{
param
(
$Char,
$keyChar,
$Alpha = [char]'A'..[char]'Z'
)
$charIndex = $Alpha.IndexOf([int]$Char)
$keyIndex = $Alpha.IndexOf([int]$keyChar)
$int = $charIndex - $keyIndex
if ($int -lt 0) { $NewIndex = $int + $Alpha.Length }
else { $NewIndex = $int }
$Alpha[$NewIndex]
}
while ( $keyChars.Length -lt $Chars.Length )
{
$keyChars = $keyChars + $keyChars
}
for ( $i = 0; $i -lt $Chars.Length; $i++ )
{
if ( [int]$Chars[$i] -in $map -and [int]$keyChars[$i] -in $map )
{
if ($Decode) {$Chars[$i] = decode $Chars[$i] $keyChars[$i] $map}
else {$Chars[$i] = encode $Chars[$i] $keyChars[$i] $map}
$Chars[$i] = [char]$Chars[$i]
[string]$OutText += $Chars[$i]
}
}
$OutText
$OutText = $null
}
} |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #UnixPipes | UnixPipes | find . -type f | egrep '\.txt$|\.TXT$' |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively (read a single directory).
| #Visual_Basic_.NET | Visual Basic .NET | Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String)
For Each file In directory.GetFiles(pattern)
Console.WriteLine(file.FullName)
Next
For Each subDir In directory.GetDirectories
walkTree(subDir, pattern)
Next
End Sub |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.