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/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
| #C | C | #include <stdio.h>
#include <stdarg.h>
Β
void varstrings(int count, ...) /* the ellipsis indicates variable arguments */
{
va_list args;
va_start(args, count);
while (count--)
puts(va_arg(args, const char *));
va_end(args);
}
Β
varstrings(5, "Mary", "had", "a", "little", "lamb"); |
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
| #C.23 | C# | using System;
Β
class Program {
static void Main(string[] args) {
PrintAll("test", "rosetta code", 123, 5.6);
}
Β
static void PrintAll(params object[] varargs) {
foreach (var i in varargs) {
Console.WriteLine(i);
}
}
} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #BASIC | BASIC | 10 REM this only works with strings
20 PRINT LEN(variable$) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #BASIC256 | BASIC256 | i = 1 #Integer
f = 1.0 #Float
s$ = "cad" #String
dim a(99) #Array
A = {1, 2, 3} #Anonymous array
m = {"key" -> 1} #Map
Β
print typeof(i) # 1
print typeof(f) # 2
print typeof(s$) # 3
print typeof(A) # 4
print typeof(m) # 6 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #BBC_BASIC | BBC BASIC | DIM bstruct{b&}
DIM istruct{i%}
DIM fstruct{f}
DIM dstruct{d#}
DIM sstruct{s$}
Β
PRINT "Size of b& is ";DIM(bstruct{})
PRINT "Size of i% is ";DIM(istruct{})
PRINT "Size of f is ";DIM(fstruct{})
PRINT "Size of d# is ";DIM(dstruct{})
PRINT "Size of s$ is ";DIM(sstruct{}) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #C | C | printf("An int containsΒ %u bytes.\n", sizeof(int)); |
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
| #Go | Go | package main
Β
import "fmt"
Β
type vector []float64
Β
func (v vector) add(v2 vector) vector {
r := make([]float64, len(v))
for i, vi := range v {
r[i] = vi + v2[i]
}
return r
}
Β
func (v vector) sub(v2 vector) vector {
r := make([]float64, len(v))
for i, vi := range v {
r[i] = vi - v2[i]
}
return r
}
Β
func (v vector) scalarMul(s float64) vector {
r := make([]float64, len(v))
for i, vi := range v {
r[i] = vi * s
}
return r
}
Β
func (v vector) scalarDiv(s float64) vector {
r := make([]float64, len(v))
for i, vi := range v {
r[i] = vi / s
}
return r
}
Β
func main() {
v1 := vector{5, 7}
v2 := vector{2, 3}
fmt.Println(v1.add(v2))
fmt.Println(v1.sub(v2))
fmt.Println(v1.scalarMul(11))
fmt.Println(v1.scalarDiv(2))
} |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Tcl | Tcl | % proc format_trace {fmt _var el op} {upvar 1 $_var v; set v [format $fmt $v]}
Β
% trace var foo w {format_trace %10s}
% puts "/[set foo bar]/"
/ bar/
Β
% trace var grill w {format_trace %-10s}
% puts "/[set grill bar]/"
/bar / |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #TXR | TXR | (make-buf 8 0 4096) |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Ursala | Ursala | p = mpfr..pi 200 # 200 bits of precision
Β
x = mpfr..grow(1.0E+0,1000) # 160 default precision, grown to 1160
Β
y = mpfr..shrink(1.0+0,40) # 160 default shrunk to 120
Β
z = mpfr..add(p,y) # inherits 200 bits of precision
Β
a = # 180 bits (not the default 160) because of more digits in the constant
Β
1.00000000000000000000000000000000000000000000000000000E0 |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Vlang | Vlang | fn main() {
bΒ := true
iΒ := 5 // default type is i32
rΒ := '5'
fΒ := 5.0 // default type is float64
println("b: ${sizeof(b)} bytes")
println("i: ${sizeof(i)} bytes")
println("r: ${sizeof(r)} bytes")
println("f: ${sizeof(f)} bytes")
i_minΒ := i8(5)
r_minΒ := `5`
f_minΒ := f32(5.0)
println("i_min: ${sizeof(i_min)} bytes")
println("r_min: ${sizeof(r_min)} bytes")
println("f_min: ${sizeof(f_min)} bytes")
} |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Wren | Wren | // create a list with 10 elements all initialized to zero
var l = List.filled(10, 0)
// give them different values and print them
for (i in 0..9) l[i] = i
System.print(l)
// add another element to the list dynamically and print it again
l.add(10)
System.print(l) |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
Β
def N = 15; \number of sites
int SiteX(N), SiteY(N), \coordinates of sites
Dist2, MinDist2, MinI, \distance squared, and minimums
X, Y, I;
[SetVid($13); \set 320x200x8 graphics
for I:= 0 to N-1 do \create a number of randomly placed sites
[SiteX(I):= Ran(160); SiteY(I):= Ran(100)];
for Y:= 0 to 100-1 do \generate Voronoi diagram
for X:= 0 to 160-1 do \for all points...
[MinDist2:= -1>>1; \find closest site
for I:= 0 to N-1 do
[Dist2:= sq(X-SiteX(I)) + sq(Y-SiteY(I));
if Dist2 < MinDist2 then
[MinDist2:= Dist2; MinI:= I];
];
if MinDist2 then Point(X, Y, MinI+1); \leave center black
];
I:= ChIn(1); \wait for keystroke
SetVid($03); \restore normal text screen
] |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #Yabasic | Yabasic | Β
clear screen
Β
sites = 200
xEdge = 600
yEdge = 400
Β
open window xEdge, yEdge
Β
dim townX(sites), townY(sites), col$(sites)
Β
for i =1 to sites
townX(i) =int(xEdge *ran(1))
townY(i) =int(yEdge *ran(1))
col$(i) = str$(int(256 * ran(1))) + ", " + str$(int(256 * ran(1))) + ", " + str$(int(256 * ran(1)))
color col$(i)
fill circle townX(i), townY(i), 2
next i
Β
dim nearestIndex(xEdge, yEdge)
dim dist(xEdge, yEdge)
Β
//fill distance table with distances from the first site
for x = 0 to xEdge - 1
for y = 0 to yEdge - 1
dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2
nearestIndex(x, y) = 1
next y
next x
Β
color 0,0,255
//for other towns
for i = 2 to sites
//display some progress
//print at(0,20) "computing: ", (i/sites*100) using "###.#", "Β %"
Β
//look left
for x = townX(i) to 0 step -1
if not(checkRow(i, x,0, yEdge - 1)) break
next x
//look right
for x = townX(i) + 1 to xEdge - 1
if not(checkRow(i, x, 0, yEdge - 1)) break
next x
next i
Β
for x = 0 to xEdge - 1
for y =0 to yEdge - 1
color col$(nearestIndex(x, y))
startY = y
nearest = nearestIndex(x, y)
for y = y + 1 to yEdge
if nearestIndex(x, y) <> nearest then y = y - 1Β : breakΒ : end if
next y
line x, startY, x, y + 1
next y
next x
Β
color 0,0,0
for i =1 to sites
fill circle townX( i), townY( i), 2
next i
print peek("millisrunning"), " ms"
Β
sub checkRow(site, x, startY, endY)
local dxSquared, y, check
Β
dxSquared = (townX(site) - x) ^ 2
for y = startY to endY
dSquared = (townY(site) - y) ^ 2 + dxSquared
if dSquared <= dist(x, y) then
dist(x, y) = dSquared
nearestIndex(x, y) = site
check = 1
end if
next y
return check
end sub |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #REXX | REXX | /*REXX program performs a chiβsquared test to verify a given distribution is uniform. */
numeric digits length( pi() ) - length(.) /*enough decimal digs for calculations.*/
@.=; @.1= 199809 200665 199607 200270 199649
@.2= 522573 244456 139979 71531 21461
do s=1 while @.s\==''; call uTest @.s /*invoke uTest with a data set of #'s.*/
end /*s*/
exit /*stick a fork in it, we're all done. */
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
!: procedure; parse arg x; p=1; do j=2 to x; p= p*j; end /*j*/; return p
chi2p: procedure; parse arg dof, distance; return gammaI( dof/2, distance/2 )
f: parse arg t; if t=0 then return 0; return t ** (a-1) * exp(-t)
e: e =2.718281828459045235360287471352662497757247093699959574966967627724; return e
pi: pi=3.141592653589793238462643383279502884197169399375105820974944592308; return pi
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
!!: procedure; parse arg x; if x<2 then return 1; p= x
do k=2+x//2 to x-1 by 2; p= p*k; end /*k*/; return p
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
chi2ud: procedure: parse arg ds; sum=0; expect= 0
do j=1 for words(ds); expect= expect + word(ds, j)
end /*j*/
expect = expect / words(ds)
do k=1 for words(ds)
sum= sum + (word(ds, k) - expect) **2
end /*k*/
return sum / expect
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
exp: procedure; parse arg x; ix= x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix
z=1; _=1; w=z; do j=1; _= _*x/j; z= (z + _)/1; if z==w then leave; w=z
end /*j*/; if z\==0 then z= z * e()**ix; return z
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
gamma: procedure; parse arg x; if datatype(x, 'W') then returnΒ !(x-1) /*Int? Use fact*/
n= trunc(x) /*at this point, X is pos and a multiple of 1/2.*/
d=Β !!(n+n - 1) /*compute the double factorial of: 2*n - 1. */
if n//2 then p= -1 /*if N is odd, then use a negative unity. */
else p= 1 /*if N is even, then use a positive unity. */
if x>0 then return p * d * sqrt(pi()) / (2**n)
return p * (2**n) * sqrt(pi()) / d
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
gammaI: procedure; parse arg a,x; y= a-1; do while f(y)*(x-y) > 2e-8 & y<x; y= y + .4
end /*while*/
y= min(x, y)
return 1 - simp38(0, y, y / 0.015 / gamma(a-1)Β % 1)
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
simp38: procedure; parse arg a, b, n; h= (b-a) / n; h1= h / 3
sum= f(a) + f(b)
do j=3*n-1 by -1 while j>0
if j//3 == 0 then sum= sum + 2 * f(a + h1*j)
else sum= sum + 3 * f(a + h1*j)
end /*j*/
return h * sum / 8
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h= d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .;g=g *.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g
/*ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
uTest: procedure; parse arg dset; sum= 0; pad= left('', 11); sigLev= 1/20 /*5%*/
say; say ' ' center(" Uniform distribution test ", 75, 'β')
#= words(dset); sigPC= sigLev*100/1
do j=1 for #; sum= sum + word(dset, j)
end /*j*/
say pad " dataset: " dset
say pad " samples: " sum
say pad " categories: " #
say pad " degrees of freedom: " # - 1
dist= chi2ud(dset)
P= chi2p(# - 1, dist)
sig = (abs(P) < dist * sigLev)
say pad "significant at " sigPC'% level? ' word('no yes', sig + 1)
say pad " is the dataset uniform? " word('no yes', (\(sig))+ 1)
return |
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
| #Julia | Julia | Β
β(a::Char, b::Char, Β± = +) = 'A'+((a-'A')Β±(b-'A')+26)%26
β(a::Char, b::Char) = β(a,b,-)
Β
cleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str)))
match_length(word, len) = repeat(word,len)[1:len]
Β
function β(message::String, codeword::String, β = β)
plaintext = cleanup(message)
key = match_length(cleanup(codeword),length(plaintext))
return String(plaintext .β key)
end
β(message::String, codeword::String) = β(message,codeword,β)
Β
cyphertext = "I want spearmint gum" β "Gimme!"
println(cyphertext)
println(cyphertext β "Gimme!")
Β |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Prolog | Prolog | % direction may be horizontal/vertical/list
display_tree(Direction) :-
sformat(A, 'Display tree ~w', [Direction]),
new(D, window(A)),
send(D, size, size(350,200)),
new(T, tree(text('Root'))),
send(T, neighbour_gap, 10),
new(S1, node(text('Child1'))),
new(S2, node(text('Child2'))),
send_list(T, son,[S1,S2]),
new(S11, node(text('Grandchild1'))),
new(S12, node(text('Grandchild2'))),
send_list(S1, son, [S11, S12]),
new(S21, node(text('Grandchild3'))),
new(S22, node(text('Grandchild4'))),
send_list(S2, son, [S21, S22]),
send(T, direction, Direction),
send(D, display, T),
send(D, open).
Β |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Visual_Basic_.NET | Visual Basic .NET | 'Using the OS pattern matching
For Each file In IO.Directory.GetFiles("\temp", "*.txt")
Console.WriteLine(file)
Next
Β
'Using VB's pattern matching and LINQ
For Each file In (From name In IO.Directory.GetFiles("\temp") Where name Like "*.txt")
Console.WriteLine(file)
Next
Β
'Using VB's pattern matching and dot-notation
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt")
Console.WriteLine(file)
Next |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Wren | Wren | import "io" for Directory
import "/pattern" for Pattern
Β
var walk = Fn.new { |dir, pattern|
if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.")
var files = Directory.list(dir)
return files.where { |f| pattern.isMatch(f) }
}
Β
// get all C header files beginning with 'a' or 'b'
var p = Pattern.new("[a|b]+0^..h", Pattern.whole)
for (f in walk.call("/usr/include", p)) System.print(f) |
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).
| #PHP | PHP | function findFiles($dir = '.', $pattern = '/./'){
$prefix = $dir . '/';
$dir = dir($dir);
while (false !== ($file = $dir->read())){
if ($file === '.' || $file === '..') continue;
$file = $prefix . $file;
if (is_dir($file)) findFiles($file, $pattern);
if (preg_match($pattern, $file)){
echo $file . "\n";
}
}
}
findFiles('./foo', '/\.bar$/'); |
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.
| #Racket | Racket | #lang racket/base
(require racket/match)
Β
(define (water-collected-between-towers towers)
(define (build-tallest-left/rev-list t mx/l rv)
(match t
[(list) rv]
[(cons a d)
(define new-mx/l (max a mx/l))
(build-tallest-left/rev-list d new-mx/l (cons mx/l rv))]))
Β
(define (collect-from-right t tallest/l mx/r rv)
(match t
[(list) rv]
[(cons a d)
(define new-mx/r (max a mx/r))
(define new-rv (+ rv (max (- (min new-mx/r (car tallest/l)) a) 0)))
(collect-from-right d (cdr tallest/l) new-mx/r new-rv)]))
Β
(define reversed-left-list (build-tallest-left/rev-list towers 0 null))
(collect-from-right (reverse towers) reversed-left-list 0 0))
Β
(module+ test
(require rackunit)
(check-equal?
(let ((towerss
'[[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]]))
(map water-collected-between-towers towerss))
(list 2 14 35 0 0 0 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
| #APL | APL | dot β +.Γ
cross β 1β½(β£Γ1β½β’)-β’Γ1β½β£ |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Run_BASIC | Run BASIC | s$ = "#########################"
dim num(100)
for i = 1 to 1000
n = (rnd(1) * 10) + 1
num(n) = num(n) + 1
next i
Β
for i = 1 to 10
print using("###",i);" "; using("#####",num(i));" ";left$(s$,num(i) / 5)
next i |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Scala | Scala | object DistrubCheck1 extends App {
Β
private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {
val counts = scala.collection.mutable.Map[Int, Int]()
Β
for (_ <- 0 until nRepeats)
counts.updateWith(f()) {
case Some(count) => Some(count + 1)
case None => Some(1)
}
Β
val target: Double = nRepeats.toDouble / counts.size
val deltaCount: Int = (delta / 100.0 * target).toInt
counts.foreach {
case (k, v) =>
if (math.abs(target - v) >= deltaCount)
println(f"distribution potentially skewed for $k%s: $v%d")
}
counts.toIndexedSeq.foreach(entry => println(f"${entry._1}%d ${entry._2}%d"))
}
Β
distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)
Β
} |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #AWK | AWK | Β
# syntax: GAWK -f VARIABLE_DECLARATION_RESET.AWK
BEGIN {
n = split("1,2,2,3,4,4,5",arr,",")
for (i=1; i<=n; i++) {
curr = arr[i]
if (i > 1 && prev == curr) {
printf("%s\n",i)
}
prev = curr
}
exit(0)
}
Β |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #C | C | #include <stdio.h>
Β
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
Β
/* There is no output as 'prev' is created anew each time
around the loop and set explicitly to zero. */
for (i = 0; i < 7; ++i) {
// for (int i = 0, prev; i < 7; ++i) { // as below, see note
int curr = s[i];
int prev = 0;
// int prev; // produces same output as second loop
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
Β
/* Now 'gprev' is used and reassigned
each time around the loop producing the desired output. */
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
Β
return 0;
} |
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
| #11l | 11l | Int a |
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.
| #11l | 11l | F van_eck(c)
[Int] r
V n = 0
V seen = [0]
V val = 0
L
r.append(val)
I r.len == c
R r
I val C seen[1..]
val = seen.index(val, 1)
E
val = 0
seen.insert(0, val)
n++
Β
print(βVan Eck: first 10 terms: βvan_eck(10))
print(βVan Eck: terms 991 - 1000: βvan_eck(1000)[(len)-10..]) |
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.
| #Julia | Julia | using Printf
Β
mutable struct VLQ
quant::Vector{UInt8}
end
Β
function VLQ(n::T) where T <: Integer
quant = UInt8.(digits(n, 128))
@inbounds for i in 2:length(quant) quant[i] |= 0x80 end
VLQ(reverse(quant))
end
Β
import Base.UInt64
function Base.UInt64(vlq::VLQ)
quant = reverse(vlq.quant)
n = shift!(quant)
p = one(UInt64)
for i in quant
p *= 0x80
n += p * ( i & 0x7f)
end
return n
end
Β
const test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f,
0x00000080, 0x00002000, 0x00003fff, 0x00004000,
0x08000000, 0x0fffffff]
Β
for i in test
vlq = VLQ(i)
j = UInt(vlq)
@printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * hex(r, 2) for r in vlq.quant), ", ") j
end |
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.
| #Kotlin | Kotlin | // version 1.0.6
Β
fun Int.toOctets(): ByteArray {
var s = Integer.toBinaryString(this)
val r = s.length % 7
var z = s.length / 7
if (r > 0) {
z++
s = s.padStart(z * 7, '0')
}
s = Array(z) { "1" + s.slice(it * 7 until (it + 1) * 7) }.joinToString("")
s = s.take(s.length - 8) + "0" + s.takeLast(7)
return ByteArray(z) { Integer.parseInt(s.slice(it * 8 until (it + 1) * 8), 2).toByte() }
}
Β
fun ByteArray.fromOctets(): Int {
var s = ""
for (b in this) s += Integer.toBinaryString(b.toInt()).padStart(7, '0').takeLast(7)
return Integer.parseInt(s, 2)
}
Β
fun main(args: Array<String>) {
val tests = intArrayOf(0x7f, 0x3fff, 0x200000, 0x1fffff)
for (test in tests) {
val ba = test.toOctets()
print("${"0x%x".format(test).padEnd(8)} -> ")
var s = ""
ba.forEach { s += "0x%02x ".format(it) }
println("${s.padEnd(20)} <- ${"0x%x".format(ba.fromOctets())}")
}
} |
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
| #C.2B.2B | C++ | #include <iostream>
Β
template<typename T>
void print(T const& t)
{
std::cout << t;
}
Β
template<typename First, typename ... Rest>
void print(First const& first, Rest const& ... rest)
{
std::cout << first;
print(rest ...);
}
Β
int main()
{
int i = 10;
std::string s = "Hello world";
print("i = ", i, " and s = \"", s, "\"\n");
} |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #C.23 | C# | Β
class Program
{
static void Main(string[] args)
{
int i = sizeof(int);
Console.WriteLine(i);
Console.ReadLine();
}
}
Β |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #C.2B.2B | C++ | #include <cstdlib>
std::size_t intsize = sizeof(int); |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #COBOL | COBOL | Β
identification division.
program-id. variable-size-get.
Β
environment division.
configuration section.
repository.
function all intrinsic.
Β
data division.
working-storage section.
01 bc-len constant as length of binary-char.
01 fd-34-len constant as length of float-decimal-34.
Β
77 fixed-character pic x(13).
77 fixed-national pic n(13).
77 fixed-nine pic s9(5).
77 fixed-separate pic s9(5) sign trailing separate.
77 computable-field pic s9(5) usage computational-5.
77 formatted-field pic +z(4),9.
Β
77 binary-field usage binary-double.
01 pointer-item usage pointer.
Β
01 group-item.
05 first-inner pic x occurs 0 to 3 times depending on odo.
05 second-inner pic x occurs 0 to 5 times depending on odo-2.
01 odo usage index value 2.
01 odo-2 usage index value 4.
Β
procedure division.
sample-main.
display "Size of:"
display "BINARY-CHAR Β : " bc-len
display " bc-len constant Β : " byte-length(bc-len)
display "FLOAT-DECIMAL-34 Β : " fd-34-len
display " fd-34-len constant Β : " byte-length(fd-34-len)
Β
display "PIC X(13) field Β : " length of fixed-character
display "PIC N(13) field Β : " length of fixed-national
Β
display "PIC S9(5) field Β : " length of fixed-nine
display "PIC S9(5) sign separateΒ : " length of fixed-separate
display "PIC S9(5) COMP-5 Β : " length of computable-field
Β
display "ALPHANUMERIC-EDITED Β : " length(formatted-field)
Β
display "BINARY-DOUBLE field Β : " byte-length(binary-field)
display "POINTER field Β : " length(pointer-item)
>>IF P64 IS SET
display " sizeof(char *) > 4"
>>ELSE
display " sizeof(char *) = 4"
>>END-IF
Β
display "Complex ODO at 2 and 4 Β : " length of group-item
set odo down by 1.
set odo-2 up by 1.
display "Complex ODO at 1 and 5 Β : " length(group-item)
Β
goback.
end program variable-size-get.
Β |
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
| #Groovy | Groovy | import groovy.transform.EqualsAndHashCode
Β
@EqualsAndHashCode
class Vector {
private List<Number> elements
Vector(List<Number> e ) {
if (!e) throw new IllegalArgumentException("A Vector must have at least one element.")
if (!e.every { it instanceof Number }) throw new IllegalArgumentException("Every element must be a number.")
elements = [] + e
}
Vector(Number... e) { this(e as List) }
Β
def order() { elements.size() }
def norm2() { elements.sum { it ** 2 } ** 0.5 }
Β
def plus(Vector that) {
if (this.order() != that.order()) throw new IllegalArgumentException("Vectors must be conformable for addition.")
[this.elements,that.elements].transpose()*.sum() as Vector
}
def minus(Vector that) { this + (-that) }
def multiply(Number that) { this.elements.collect { it * that } as Vector }
def div(Number that) { this * (1/that) }
def negative() { this * -1 }
Β
String toString() { "(${elements.join(',')})" }
}
Β
class VectorCategory {
static Vector plus (Number a, Vector b) { b + a }
static Vector minus (Number a, Vector b) { -b + a }
static Vector multiply (Number a, Vector b) { b * a }
} |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
char S,
A(1), \sets up an array containing one byte
B(0); \sets up an array containing no bytes
int I;
[S:= ""; \a zero-length (null) string
A:= Reserve(1); \sets up a 1-byte array at runtime
B:= Reserve(0); \sets up a 0-byte array at runtime
I:= IΒ ! 1<<3; \stores a single 1 bit into an integer
I:= I & ~(1<<29); \stores a 0 bit into bit 29 of the integer
IntOut(0, I>>3 & 1); \displays value of bit 3
] |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #Z80_Assembly | Z80 Assembly | MyByte:
byte 0 ;most assemblers will also accept DB or DFB
MyWord:
word 0 ;most assemblers will also accept DW or DFW
MyDouble:
dd 0 |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #zkl | zkl | 10 DIM a$(10): REM This array will be 10 characters long
20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific
30 LET c=5: REM this is a single numerical value of fixed size |
http://rosettacode.org/wiki/Variable_size/Set | Variable size/Set | Task
Demonstrate how to specify the minimum size of a variable or a data type.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM a$(10): REM This array will be 10 characters long
20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific
30 LET c=5: REM this is a single numerical value of fixed size |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #zkl | zkl | fcn generate_voronoi_diagram(width,height,num_cells){
image,imgx,imgy:=PPM(width,height),width,height;
nx:=num_cells.pump(List,(0).random.fp(imgx));
ny:=num_cells.pump(List,(0).random.fp(imgy));
nr:=num_cells.pump(List,(0).random.fp(256)); // red
ng:=num_cells.pump(List,(0).random.fp(256)); // blue
nb:=num_cells.pump(List,(0).random.fp(256)); // green
Β
foreach y,x in (imgy,imgx){
dmin:=(imgx-1).toFloat().hypot(imgy-1);
j:=-1;
foreach i in (num_cells){
d:=(nx[i] - x).toFloat().hypot(ny[i] - y);
if(d<dmin) dmin,j = d,i
}
image[x,y]=(nr[j]*0xff00 + ng[j])*0xff00 + nb[j];
}
image
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Ruby | Ruby | def gammaInc_Q(a, x)
a1, a2 = a-1, a-2
f0 = lambda {|t| t**a1 * Math.exp(-t)}
df0 = lambda {|t| (a1-t) * t**a2 * Math.exp(-t)}
Β
y = a1
y += 0.3 while f0[y]*(x-y) > 2.0e-8 and y < x
y = x if y > x
Β
h = 3.0e-4
n = (y/h).to_i
h = y/n
hh = 0.5 * h
sum = 0
(n-1).step(0, -1) do |j|
t = h * j
sum += f0[t] + hh * df0[t]
end
h * sum / gamma_spounge(a)
end
Β
A = 12
k1_factrl = 1.0
coef = [Math.sqrt(2.0*Math::PI)]
COEF = (1...A).each_with_object(coef) do |k,c|
c << Math.exp(A-k) * (A-k)**(k-0.5) / k1_factrl
k1_factrl *= -k
end
Β
def gamma_spounge(z)
accm = (1...A).inject(COEF[0]){|res,k| res += COEF[k] / (z+k)}
accm * Math.exp(-(z+A)) * (z+A)**(z+0.5) / z
end
Β
def chi2UniformDistance(dataSet)
expected = dataSet.inject(:+).to_f / dataSet.size
dataSet.map{|d|(d-expected)**2}.inject(:+) / expected
end
Β
def chi2Probability(dof, distance)
1.0 - gammaInc_Q(0.5*dof, 0.5*distance)
end
Β
def chi2IsUniform(dataSet, significance=0.05)
dof = dataSet.size - 1
dist = chi2UniformDistance(dataSet)
chi2Probability(dof, dist) > significance
end
Β
dsets = [ [ 199809, 200665, 199607, 200270, 199649 ],
[ 522573, 244456, 139979, 71531, 21461 ] ]
Β
for ds in dsets
puts "Data set:#{ds}"
dof = ds.size - 1
puts " degrees of freedom:Β %d" % dof
distance = chi2UniformDistance(ds)
puts " distance: Β %.4f" % distance
puts " probability: Β %.4f" % chi2Probability(dof, distance)
puts " uniform? Β %s" % (chi2IsUniform(ds)Β ? "Yes"Β : "No")
end |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Kotlin | Kotlin | // version 1.1.3
Β
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
val t = if (encrypt) text.toUpperCase() else text
val sb = StringBuilder()
var ki = 0
for (c in t) {
if (c !in 'A'..'Z') continue
val ci = if (encrypt)
(c.toInt() + key[ki].toInt() - 130) % 26
else
(c.toInt() - key[ki].toInt() + 26) % 26
sb.append((ci + 65).toChar())
ki = (ki + 1) % key.length
}
return sb.toString()
}
Β
fun main(args: Array<String>) {
val key = "VIGENERECIPHER"
val text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
val encoded = vigenere(text, key)
println(encoded)
val decoded = vigenere(encoded, key, false)
println(decoded)
} |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Python | Python | Python 3.2.3 (default, May 3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> help('pprint.pprint')
Help on function pprint in pprint:
Β
pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)
Pretty-print a Python object to a stream [default is sys.stdout].
Β
>>> from pprint import pprint
>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),
(1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),
((((1, 2), 3), 4), 5, 6, 7, 8) ]:
print("\nTreeΒ %r can be pprint'd as:"Β % (tree, ))
pprint(tree, indent=1, width=1)
Β
Β
Β
Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:
(1,
2,
3,
4,
5,
6,
7,
8)
Β
Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:
(1,
((2,
3),
(4,
(5,
((6,
7),
8)))))
Β
Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:
((((1,
2),
3),
4),
5,
6,
7,
8)
>>> |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #zkl | zkl | File.glob("*.zkl") //--> list of matches |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. Β These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Β Walk Directory Tree Β (read entire directory tree).
| #Zsh | Zsh | print -l -- *.c |
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).
| #PicoLisp | PicoLisp | (let Dir "."
(recur (Dir)
(for F (dir Dir)
(let Path (pack Dir "/" F)
(cond
((=T (car (info Path))) # Is a subdirectory?
(recurse Path) ) # Yes: Recurse
((match '`(chop "[email protected]") (chop F)) # Matches 's*.l'?
(println Path) ) ) ) ) ) ) # Yes: Print it |
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).
| #Pop11 | Pop11 | lvars repp, fil;
;;; create path repeater
sys_file_match('.../*.p', '', false, 0) -> repp;
;;; iterate over paths
while (repp() ->> fil) /= termin do
Β ;;; print the path
printf(fil, '%s\n');
endwhile; |
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.
| #Raku | Raku | sub max_l ( @a ) { [\max] @a }
sub max_r ( @a ) { ([\max] @a.reverse).reverse }
Β
sub water_collected ( @towers ) {
return 0 if @towers <= 2;
Β
my @levels = max_l(@towers) »min« max_r(@towers);
Β
return ( @levels »-« @towers ).grep( * > 0 ).sum;
}
Β
say map &water_collected,
[ 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 ],
; |
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
| #AppleScript | AppleScript | --------------------- VECTOR PRODUCTS ---------------------
Β
-- dotProductΒ :: Num a => [a] -> [a] -> Either String a
on dotProduct(xs, ys)
-- Dot product of two vectors of equal dimension.
Β
if length of xs = length of ys then
|Right|(sum(zipWith(my mul, xs, ys)))
else
|Left|("Dot product not defined for vectors of differing dimension.")
end if
end dotProduct
Β
Β
-- crossProductΒ :: Num a => (a, a, a) -> (a, a, a)
-- Either String -> (a, a, a)
on crossProduct(xs, ys)
-- The cross product of two 3D vectors.
Β
if 3 β length of xs or 3 β length of ys then
|Left|("Cross product is defined only for 3d vectors.")
else
set {x1, x2, x3} to xs
set {y1, y2, y3} to ys
|Right|({Β¬
x2 * y3 - x3 * y2, Β¬
x3 * y1 - x1 * y3, Β¬
x1 * y2 - x2 * y1})
end if
end crossProduct
Β
Β
-- scalarTripleΒ :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> a
on scalarTriple(q, r, s)
-- The scalar triple product.
Β
script go
on |Ξ»|(ys)
dotProduct(q, ys)
end |Ξ»|
end script
bindLR(crossProduct(r, s), go)
end scalarTriple
Β
Β
-- vectorTripleΒ :: Num a => (a, a, a) -> (a, a, a) -> (a, a a) ->
-- Either String -> (a, a, a)
on vectorTriple(q, r, s)
-- The vector triple product.
Β
script go
on |Ξ»|(ys)
crossProduct(q, ys)
end |Ξ»|
end script
bindLR(crossProduct(r, s), go)
end vectorTriple
Β
Β
-------------------------- TEST ---------------------------
on run
set a to {3, 4, 5}
set b to {4, 3, 5}
set c to {-5, -12, -13}
set d to {3, 4, 5, 6}
Β
Β
script test
on |Ξ»|(f)
either(my identity, my show, Β¬
mReturn(f)'s |Ξ»|(a, b, c, d))
end |Ξ»|
end script
Β
Β
tell test
unlines({Β¬
"a . b = " & |Ξ»|(dotProduct), Β¬
"a x b = " & |Ξ»|(crossProduct), Β¬
"a . (b x c) = " & |Ξ»|(scalarTriple), Β¬
"a x (b x c) = " & |Ξ»|(vectorTriple), Β¬
"a x d = " & either(my identity, my show, Β¬
dotProduct(a, d)), Β¬
"a . (b x d) = " & either(my identity, my show, Β¬
scalarTriple(a, b, d)) Β¬
})
end tell
end run
Β
Β
-------------------- GENERIC FUNCTIONS --------------------
Β
-- LeftΒ :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
Β
Β
-- RightΒ :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
Β
Β
-- bindLR (>>=)Β :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Left| of m then
m
else
mReturn(mf)'s |Ξ»|(|Right| of m)
end if
end bindLR
Β
Β
-- eitherΒ :: (a -> c) -> (b -> c) -> Either a b -> c
on either(lf, rf, e)
if missing value is |Left| of e then
tell mReturn(rf) to |Ξ»|(|Right| of e)
else
tell mReturn(lf) to |Ξ»|(|Left| of e)
end if
end either
Β
Β
-- foldlΒ :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |Ξ»|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
Β
Β
-- identityΒ :: a -> a
on identity(x)
-- The argument unchanged.
x
end identity
Β
Β
-- intercalateΒ :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to Β¬
{my text item delimiters, delim}
set str to xs as text
set my text item delimiters to dlm
str
end intercalate
Β
Β
-- mapΒ :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |Ξ»|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
Β
Β
-- minΒ :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
Β
Β
-- mulΒ :: Num aΒ :: a -> a -> a
on mul(x, y)
x * y
end mul
Β
Β
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturnΒ :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |Ξ»|Β : f
end script
end if
end mReturn
Β
Β
-- showΒ :: a -> String
on show(x)
if list is class of x then
showList(x)
else
str(x)
end if
end show
Β
Β
-- showListΒ :: [a] -> String
on showList(xs)
"[" & intercalate(", ", map(my str, xs)) & "]"
end showList
Β
Β
-- strΒ :: a -> String
on str(x)
x as string
end str
Β
Β
-- sumΒ :: [Number] -> Number
on sum(xs)
script add
on |Ξ»|(a, b)
a + b
end |Ξ»|
end script
Β
foldl(add, 0, xs)
end sum
Β
Β
-- unlinesΒ :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to Β¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
Β
Β
-- zipWithΒ :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |Ξ»|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Tcl | Tcl | proc distcheck {random times {delta 1}} {
for {set i 0} {$i<$times} {incr i} {incr vals([uplevel 1 $random])}
set target [expr {$times / [array size vals]}]
foreach {k v} [array get vals] {
if {abs($v - $target) > $times * $delta / 100.0} {
error "distribution potentially skewed for $k: expected around $target, got $v"
}
}
foreach k [lsort -integer [array names vals]] {lappend result $k $vals($k)}
return $result
} |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #C.2B.2B | C++ | #include <array>
#include <iostream>
Β
int main()
{
constexpr std::array s {1,2,2,3,4,4,5};
Β
if(!s.empty())
{
int previousValue = s[0];
Β
for(size_t i = 1; i < s.size(); ++i)
{
// in C++, variables in block scope are reset at each iteration
const int currentValue = s[i];
Β
if(i > 0 && previousValue == currentValue)
{
std::cout << i << "\n";
}
Β
previousValue = currentValue;
}
}
}
Β
Β |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #F.23 | F# | Β
// Variable declaration reset. Nigel Galloway: June 21st 2022
let s=[1;2;2;3;4;4;5]
// First let me write this in real F#, which rather avoids the whole issue
printfn "Real F#"
s|>List.pairwise|>List.iteri(fun i (n,g)->if n=g then printfn "%d" (i+1))
// Now let me take the opportunity to write some awful F# by translating the C++
printfn "C++ like awful F#"
let mutable previousValue = -1
for i in 0..s.Length-1 do
let currentValue=s.[i]
if previousValue = currentValue then printfn "%d" i
previousValue <- currentValue
Β |
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
| #360_Assembly | 360 Assembly | * value of F
L 2,F assigment r2=f
* reference (or address) of F
LA 3,F reference r3=@f
* referencing (or indexing) of reg3 (r3->f)
L 4,0(3) referencing r4=%r3=%@f=f |
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
| #6502_Assembly | 6502 Assembly | org $1200
SoundRam equ $1200 Β ;some assemblers require equ directives to not be indented.
SoundChannel_One equ $1200
SoundChannel_Two equ $1201
SoundChannel_Three equ $1202
LDA #$FFΒ ;this still gets assembled starting at $1200, since equ directives don't take up space! |
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.
| #8080_Assembly | 8080 Assembly | org 100h
lxi h,ecks ; Zero out 2000 bytes
lxi b,0
lxi d,2000
zero: mov m,b
inx h
dcx d
mov a,d
ora e
jnz zero
lxi b,-1 ; BC = Outer loop variable
outer: inx b
mvi a,3 ; Are we there yet? 1000 = 03E8h
cmp b ; Compare high byte
jnz go
mvi a,0E8h ; Compare low byte
cmp c
jz done
go: mov d,b ; DE = Inner loop variable
mov e,c
inner: dcx d
mov a,d ; <= 0?
ral
jc outer
push b ; Keep both pointers
push d
mov h,b ; Load BC = eck[BC]
mov l,c
call eck
mov c,m
inx h
mov b,m
xchg ; Load HL = -eck[DE]
call eck
xchg
ldax d
cma
mov l,a
inx d
ldax d
cma
mov h,a
inx h ; Two's complement
dad b ; -eck[DE] + eck[BC]
mov a,h ; Unfortunately this does not set flags
ora l ; Check zero
pop d ; Meanwhile, restore the pointers
pop b
jnz inner ; If no match, continue with inner loop
mov h,b ; If we _did_, then get &eck[BC + 1]
mov l,c
inx h
call eck
mov a,c ; Store BC - DE at that address
sub e
mov m,a
inx h
mov a,b
sbb d
mov m,a
jmp outer ; And continue the outer loop
done: lxi h,0 ; Print first 10 terms
call p10
lxi h,990 ; Print last 10 terms
p10: mvi b,10 ; Print 10 terms starting at term HL
call eck
ploop: mov e,m ; Load term into DE
inx h
mov d,m
inx h
push b ; Keep counter
push h ; Keep pointer
xchg ; Term in HL
call printn ; Print term
pop h ; Restore pointer and counter
pop b
dcr b
jnz ploop
lxi d,nl ; Print a newline afterwards
jmp prints
eck: push b ; Set HL = &eck[HL]
lxi b,ecks ; Base address
dad h ; Multiply by two
dad b ; Add base
pop b
ret
printn: lxi d,buf ; Print the number in HL
push d ; Buffer pointer on stack
lxi b,-10 ; Divisor
pdigit: lxi d,-1 ; Quotient
pdiv: inx d
dad b
jc pdiv
mvi a,'0'+10
add l ; Make ASCII digit
pop h
dcx h ; Store digit
mov m,a
push h
xchg
mov a,h ; Quotient nonzero?
ora l
jnz pdigit ; Then there are more digits
pop d ; Otherwise, print string using CP/M
prints: mvi c,9
jmp 5
nl: db 13,10,'$'
db '.....'
buf: db ' $'
ecks: equ $ |
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.
| #8086_Assembly | 8086 Assembly | LIMIT: equ 1000
cpu 8086
org 100h
section .text
mov di,eck ; Zero out the memory
xor ax,ax
mov cx,LIMIT
rep stosw
mov bx,eck ; Base address
mov cx,LIMIT ; Limit
xor ax,ax
mov si,-1 ; Outer loop index
outer: inc si
dec cx
jcxz done
mov di,si ; Inner loop index
inner: dec di
js outer
shl si,1 ; Shift the loop indices (each entry is 2 bytes)
shl di,1
mov ax,[si+bx] ; Find a match?
cmp ax,[di+bx]
je match
shr si,1 ; If not, shift SI and DI back and keep going
shr di,1
jmp inner
match: mov ax,si ; Calculate the new value
sub ax,di
shr ax,1 ; Compensate for shift
mov [si+bx+2],ax ; Store value
shr si,1 ; Shift SI back and calculate next value
jmp outer
done: xor si,si ; Print first 10 elements
call p10
mov si,LIMIT-10 ; Print last 10 elementsβ
p10: mov cx,10 ; Print 10 elements starting at SI
shl si,1 ; Items are 2 bytes wide
add si,eck
.item: lodsw ; Retrieve item
call printn ; Print it
loop .item
mov dx,nl ; Print a newline afterwards
jmp prints
printn: mov bx,buf ; Print AX
mov bp,10
.digit: xor dx,dx ; Extract digit
div bp
add dl,'0' ; ASCII digit
dec bx
mov [bx],dl ; Store in buffer
test ax,ax ; Any more digits?
jnz .digit
mov dx,bx
prints: mov ah,9 ; Print string in buffer
int 21h
ret
section .data
nl: db 13,10,'$'
db '.....'
buf: db ' $'
section .bss
eck: resw LIMIT |
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
| #11l | 11l | -V Pow10 = (0..18).map(n -> Int64(10) ^ n)
Β
F isOdd(n)
R (n [&] 1)Β != 0
Β
F fangs(n)
[(Int64, Int64)] r
Β
V nDigits = sorted(String(n))
I isOdd(nDigits.len)
R r
Β
V fangLen = nDigits.len I/ 2
V inf = Pow10[fangLen - 1]
L(d) inf .< inf * 10
I nΒ % dΒ != 0
L.continue
V q = n I/ d
I q < d
R r
V dDigits = String(d)
V qDigits = String(q)
I qDigits.len > fangLen
L.continue
I qDigits.len < fangLen
R r
I nDigitsΒ != sorted(dDigitsββqDigits)
L.continue
I dDigits.lastΒ != β0β | qDigits.lastΒ != β0β
r.append((d, q))
Β
R r
Β
print(βFirst 25 vampire numbers with their fangs:β)
V count = 0
V n = 10
V limit = 100
L countΒ != 25
V fangList = fangs(n)
IΒ !fangList.empty
count++
print((β#2: #6 =β.format(count, n))β βfangList.map(it -> β#3 x #3β.format(it[0], it[1])).join(β = β))
n++
I n == limit
n *= 10
limit *= 10
Β
print()
L(n) [16'758'243'290'880, 24'959'017'348'650, 14'593'825'548'650]
V fangList = fangs(n)
I fangList.empty
print(nβ is not vampiric.β)
E
print(nβ = βfangList.map(it -> β#. x #.β.format(it[0], it[1])).join(β = β)) |
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.
| #xTalk | xTalk | Β
on DecToVLQ
Ask "Enter base 10 value:" -- input dialog box
if it is not empty then
if it is a number then
put it into theString
if isWholeNumString(theString) is false then -- I think there is built in equivalent for this but I rolled my own!
answer "Only Whole Decimal Numbers Are Allowed!"
exit DecToVLQ
end if
if theString>4294967295 then
answer "This function fails with whole numbers over 4294967295!"&cr\
& "4294967295 is the maximum allowed value for 32bits (4 bytes)"
exit DecToVLQ
end if
if theString>268435455 then
answer "This function is not accurate with whole numbers over 268435455!"&cr\
& "268435455 is the maximum allowed value for 28bit (7bits per byte) MIDI delta-time VLQ"
end if
put "Original Whole Number="& theString & cr & \
"Original Whole Number in Hex="& baseConvert(theString,10,16) & cr & \ --- LC's built in baseConvert function
"Variable Length Quantity in Hex=" & wholeNumToVLQ(theString) into fld "Output"
else
answer "Only Whole Decimal Numbers Are Allowed!"
end if
end if
end DecToVLQ
Β
function wholeNumToVLQ theWholeNum
-- baseConvert(number,originalBase,destinationBase) -- there is also bitwise operations in LC but I took the long road
if theWholeNum < 127 then -- if it fits into a single 7bit byte value and theres no need to process it
put baseConvert(theWholeNum,10,16) into VQLinHex
if the number of chars in VQLinHex=1 then put "0" before VQLinHex
return VQLinHex
exit wholeNumToVLQ
end if
put baseConvert(theWholeNum,10,2) into theBits
put number of chars in theBits into x
put 0 into bitCounter
put empty into the7bitBytes
repeat
if char x of theBits is not empty then
put char x theBits before the7bitBytes
delete char x of theBits
if theBits is empty then exit repeat
put number of chars in theBits into x
add 1 to bitCounter
if bitCounter=7 then
put "," before the7bitBytes
put 0 into bitCounter
next repeat
end if
else
exit repeat
end if
end repeat
get the number of chars in item 1 of the7bitBytes
if it<7 then
put 7 - it into x
repeat x
put "0" before item 1 of the7bitBytes
end repeat
end if
put the number of items in the7bitBytes into y
repeat with x = 1 to y
if x is not y then
put "1" before item x of the7bitBytes
else
put "0" before item x of the7bitBytes
end if
put baseConvert(item x of the7bitBytes,2,16) into item x of the7bitBytes
if the number of chars in item x of the7bitBytes<2 then put "0" before item x of the7bitBytes
put item x of the7bitBytes after VQLinHex
end repeat
return VQLinHex
end wholeNumToVLQ
Β
function isWholeNumString theString
put the number of chars in theString into y
repeat with x = 1 to y
if char x of theString is not in "0123456789" then
return false
exit isWholeNumString
end if
end repeat
return true
end isWholeNumString
Β |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | toOctets[n_Integer]Β :=
StringJoin @@@
Partition[
PadLeft[Characters@IntegerString[n, 16],
2 Ceiling[Plus @@ DigitCount[n, 16]/2], {"0"}], 2]
fromOctets[octets_List]Β := FromDigits[StringJoin @@ octets, 16]
Grid[{#, toOctets@#, fromOctets[toOctets@#]} & /@ {16^^3ffffe, 16^^1fffff, 16^^200000}] |
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
| #Clojure | Clojure | (defn foo [& args]
(doseq [a args]
(println a)))
Β
(foo :bar :baz :quux)
(apply foo [:bar :baz :quux]) |
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
| #COBOL | COBOL | Β
program-id. dsp-str is external.
data division.
linkage section.
1 cnt comp-5 pic 9(4).
1 str pic x.
procedure division using by value cnt
by reference str delimited repeated 1 to 5.
end program dsp-str.
Β
program-id. variadic.
procedure division.
call "dsp-str" using 4 "The" "quick" "brown" "fox"
stop run
.
end program variadic.
Β
program-id. dsp-str.
data division.
working-storage section.
1 i comp-5 pic 9(4).
1 len comp-5 pic 9(4).
1 wk-string pic x(20).
linkage section.
1 cnt comp-5 pic 9(4).
1 str1 pic x(20).
1 str2 pic x(20).
1 str3 pic x(20).
1 str4 pic x(20).
1 str5 pic x(20).
procedure division using cnt str1 str2 str3 str4 str5.
if cnt < 1 or > 5
display "Invalid number of parameters"
stop run
end-if
perform varying i from 1 by 1
until i > cnt
evaluate i
when 1
unstring str1 delimited low-value
into wk-string count in len
when 2
unstring str2 delimited low-value
into wk-string count in len
when 3
unstring str3 delimited low-value
into wk-string count in len
when 4
unstring str4 delimited low-value
into wk-string count in len
when 5
unstring str5 delimited low-value
into wk-string count in len
end-evaluate
display wk-string (1:len)
end-perform
exit program
.
end program dsp-str.
Β |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Common_Lisp | Common Lisp | (let ((a (cons 1 2))
(b (make-array 10))
(c "a string"))
(list (hcl:find-object-size a)
(hcl:find-object-size b)
(hcl:find-object-size c))) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #D | D | int i ;
writefln(i.sizeof) ; // print 4
int[13] ints1 ; // static integer array of length 13
writefln(ints1.sizeof) ; // print 52
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
writefln(ints2.sizeof) ; // print 8, all dynamic array has this size
writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type |
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
| #Haskell | Haskell | Β
add (u,v) (x,y) = (u+x,v+y)
minus (u,v) (x,y) = (u-x,v-y)
multByScalar k (x,y) = (k*x,k*y)
divByScalar (x,y) k = (x/k,y/k)
Β
main = do
let vecA = (3.0,8.0) -- cartersian coordinates
let (r,theta) = (3,pi/12) :: (Double,Double)
let vecB = (r*(cos theta),r*(sin theta)) -- from polar coordinates to cartesian coordinates
putStrLn $ "vecA = " ++ (show vecA)
putStrLn $ "vecB = " ++ (show vecB)
putStrLn $ "vecA + vecB = " ++ (show.add vecA $ vecB)
putStrLn $ "vecA - vecB = " ++ (show.minus vecA $ vecB)
putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB)
putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Rust | Rust | Β
use statrs::function::gamma::gamma_li;
Β
fn chi_distance(dataset: &[u32]) -> f64 {
let expected = f64::from(dataset.iter().sum::<u32>()) / dataset.len() as f64;
dataset
.iter()
.fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.))
/ expected
}
Β
fn chi2_probability(dof: f64, distance: f64) -> f64 {
1. - gamma_li(dof * 0.5, distance * 0.5)
}
Β
fn chi2_uniform(dataset: &[u32], significance: f64) -> bool {
let d = chi_distance(&dataset);
chi2_probability(dataset.len() as f64 - 1., d) > significance
}
Β
fn main() {
let dsets = vec![
vec![199809, 200665, 199607, 200270, 199649],
vec![522573, 244456, 139979, 71531, 21461],
];
Β
for ds in dsets {
println!("Data set: {:?}", ds);
let d = chi_distance(&ds);
print!("Distance: {:.6} ", d);
print!(
"Chi2 probability: {:.6} ",
chi2_probability(ds.len() as f64 - 1., d)
);
print!("Uniform? {}\n", chi2_uniform(&ds, 0.05));
}
}
Β
Β |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Scala | Scala | import org.apache.commons.math3.special.Gamma.regularizedGammaQ
Β
object ChiSquare extends App {
private val dataSets: Seq[Seq[Double]] =
Seq(
Seq(199809, 200665, 199607, 200270, 199649),
Seq(522573, 244456, 139979, 71531, 21461)
)
Β
private def Ο2IsUniform(data: Seq[Double], significance: Double) =
Ο2Prob(data.size - 1.0, Ο2Dist(data)) > significance
Β
private def Ο2Dist(data: Seq[Double]) = {
val avg = data.sum / data.size
Β
data.reduce((a, b) => a + math.pow(b - avg, 2)) / avg
}
Β
private def Ο2Prob(dof: Double, distance: Double) =
regularizedGammaQ(dof / 2, distance / 2)
Β
printf("Β %4sΒ %10s Β %12sΒ %8s Β %s%n",
"d.f.", "ΟΒ²distance", "ΟΒ²probability", "Uniform?", "dataset")
dataSets.foreach { ds =>
val (dist, dof) = (Ο2Dist(ds), ds.size - 1)
Β
printf("%4dΒ %11.3f Β %13.8f Β %5s Β %6s%n",
dof, dist, Ο2Prob(dof.toDouble, dist), if (Ο2IsUniform(ds, 0.05)) "YES" else "NO", ds.mkString(", "))
}
} |
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
| #Lambdatalk | Lambdatalk | Β
{def vigenere
{def vigenere.map
{lambda {:codeΒ :keyΒ :txt}
{S.map
{{lambda {:codeΒ :txtΒ :keyΒ :i}
{W.code2char
{+ {% {+ {W.char2code {W.getΒ :iΒ :txt}}
{ifΒ :code
then {W.char2code {W.get {%Β :i {W.lengthΒ :key}}Β :key}}
else {- 26 {W.char2code {W.get {%Β :i {W.lengthΒ :key}}Β :key}}} }}
26}
65}} }Β :codeΒ :txtΒ :key}
{S.serie 0 {- {W.lengthΒ :txt} 1}}} }}
{lambda {:codeΒ :keyΒ :txt}
{S.replace \s by in {vigenere.mapΒ :codeΒ :key {S.replace \s by inΒ :txt}}} }}
-> vigenere
Β
1) encode: {vigenere true LEMON ATTACK AT DAWN}
-> LXFOPVEFRNHR
Β
2) decode: {vigenere false LEMON LXFOPVEFRNHR}
-> ATTACKATDAWN
Β
Β |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Racket | Racket | Β
#lang racket/base
Β
(define (visualize t0)
(let loop ([t t0] [last? #t] [indent '()])
(define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last]))
(for-each display (reverse indent))
(unless (eq? t t0) (printf "|\n"))
(for-each display (reverse indent))
(printf "~a~a\n" (I "\\-" "+-") (car t))
(for ([s (cdr t)] [n (in-range (- (length t) 2) -1 -1)])
(loop s (zero? n) (cons (I " " "| ") indent)))))
Β
(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))
Β |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #Raku | Raku | sub visualize-tree($tree, &label, &children,
:$indent = '',
:@mid = ('ββ', 'β '),
:@end = ('ββ', ' '),
) {
sub visit($node, *@pre) {
| gather {
take @pre[0] ~ label($node);
my @children := children($node);
my $end = @children.end;
for @children.kv -> $_, $child {
when $end { take visit($child, (@pre[1] X~ @end)) }
default { take visit($child, (@pre[1] X~ @mid)) }
}
}
}
visit($tree, $indent xx 2);
}
Β
# example tree built up of pairs
my $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];
Β
.map({.join("\n")}).join("\n").say for visualize-tree($tree, *.key, *.value.list); |
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).
| #PowerShell | PowerShell | Get-ChildItem -Recurse -Include *.mp3 |
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).
| #Prolog | Prolog | Β
% submitted by Aykayayciti (Earl Lamont Montgomery)
% altered from fsaenzperez April 2019
% (swi-prolog.discourse-group)
test_run :-
proc_dir('C:\\vvvv\\vvvv_beta_39_x64').
Β
proc_dir(Directory) :-
format('Directory: ~w~n',[Directory]),
directory_files(Directory,Files),!, %cut inserted
proc_files(Directory,Files).
Β
proc_files(Directory, [File|Files]) :-
proc_file(Directory, File),!, %cut inserted
proc_files(Directory, Files).
proc_files(_Directory, []).
Β
proc_file(Directory, File) :-
(
File = '.',
directory_file_path(Directory, File, Path),
exists_directory(Path),!,%cut inserted
format('Directory: ~w~n',[File])
;
File = '..',
directory_file_path(Directory, File, Path),
exists_directory(Path),!,%cut inserted
format('Directory: ~w~n',[File])
;
directory_file_path(Directory, File, Path),
exists_directory(Path),!,%cut inserted
proc_dir(Path)
;
directory_file_path(Directory, File, Path),
exists_file(Path),!,%cut inserted
format('File: ~w~n',[File])
;
format('Unknown: ~w~n',[File])
). |
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.
| #REXX | REXX | /* REXX */
Call bars '1 5 3 7 2'
Call bars '5 3 7 2 6 4 5 9 1 2'
Call bars '2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1'
Call bars '5 5 5 5'
Call bars '5 6 7 8'
Call bars '8 7 7 6'
Call bars '6 7 10 7 6'
Exit
bars:
Parse Arg bars
bar.0=words(bars)
high=0
box.=' '
Do i=1 To words(bars)
bar.i=word(bars,i)
high=max(high,bar.i)
Do j=1 To bar.i
box.i.j='x'
End
End
m=1
w=0
Do Forever
Do i=m+1 To bar.0
If bar.i>bar.m Then
Leave
End
If i>bar.0 Then Leave
n=i
Do i=m+1 To n-1
w=w+bar.m-bar.i
Do j=bar.i+1 To bar.m
box.i.j='*'
End
End
m=n
End
m=bar.0
Do Forever
Do i=bar.0 To 1 By -1
If bar.i>bar.m Then
Leave
End
If i<1 Then Leave
n=i
Do i=m-1 To n+1 By -1
w=w+bar.m-bar.i
Do j=bar.i+1 To bar.m
box.i.j='*'
End
End
m=n
End
Say bars '->' w
Call show
Return
show:
Do j=high To 1 By -1
ol=''
Do i=1 To bar.0
ol=ol box.i.j
End
Say ol
End
Return |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: Β (X, Y, Z).
If you imagine a graph with the Β x Β and Β y Β axis being at right angles to each other and having a third, Β z Β axis coming out of the page, then a triplet of numbers, Β (X, Y, Z) Β would represent a point in the region, Β and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product Β Β Β (a scalar quantity)
A β’ B = a1b1 Β + Β a2b2 Β + Β a3b3
The cross product Β Β Β (a vector quantity)
A x B = (a2b3Β - Β a3b2, Β Β a3b1 Β - Β a1b3, Β Β a1b2 Β - Β a2b1)
The scalar triple product Β Β Β (a scalar quantity)
A β’ (B x C)
The vector triple product Β Β Β (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a β’ b
Compute and display: a x b
Compute and display: a β’ (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
Β A starting page on Wolfram MathWorld is Β Vector Multiplication .
Β Wikipedia Β dot product.
Β Wikipedia Β cross product.
Β Wikipedia Β triple product.
Related tasks
Β Dot product
Β Quaternion type
| #Arturo | Arturo | ; dot product
dot: function [a b][
sum map couple a b => product
]
Β
; cross product
cross: function [a b][
A: (a\1 * b\2) - a\2 * b\1
B: (a\2 * b\0) - a\0 * b\2
C: (a\0 * b\1) - a\1 * b\0
@[A B C]
]
Β
; scalar triple product
stp: function [a b c][
dot a cross b c
]
Β
; vector triple product
vtp: function [a b c][
cross a cross b c
]
Β
; task
a: [3 4 5]
b: [4 3 5]
c: @[neg 5 neg 12 neg 13]
Β
print ["a β’ b =", dot a b]
print ["a x b =", cross a b]
print ["a β’ (b x c) =", stp a b c]
print ["a x (b x c) =", vtp a b c] |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #VBScript | VBScript | Option Explicit
Β
sub verifydistribution(calledfunction, samples, delta)
Dim i, n, maxdiff
'We could cheat via Dim d(7), but "7" wasn't mentioned in the Task. Heh.
Dim dΒ : Set d = CreateObject("Scripting.Dictionary")
wscript.echo "Running """ & calledfunction & """ " & samples & " times..."
for i = 1 to samples
Execute "n = " & calledfunction
d(n) = d(n) + 1
next
n = d.Count
maxdiff = 0
wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets."
for each i in d.Keys
dim diffΒ : diff = abs(1 - d(i) / (samples/n))
if diff > maxdiff then maxdiff = diff
wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _
& vbTab & " difference from expected=" & FormatPercent(diff, 2)
next
wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _
& ", desired limit is " & FormatPercent(delta, 2) & "."
if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!"
end sub |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Vlang | Vlang | import rand
import rand.seed
import math
// "given"
fn dice5() int {
return rand.intn(5) or {0} + 1
}
Β
// fntion specified by task "Seven-sided dice from five-sided dice"
fn dice7() int {
mut iΒ := 0
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
Β
// fntion specified by task "Verify distribution uniformity/Naive"
//
// Parameter "f" is expected to return a random integer in the range 1..n.
// (Values out of range will cause an unceremonious crash.)
// "Max" is returned as an "indication of distribution achieved."
// It is the maximum delta observed from the count representing a perfectly
// uniform distribution.
// Also returned is a boolean, true if "max" is less than threshold
// parameter "delta."
fn dist_check(f fn() int, n int,
repeats int, delta f64) (f64, bool) {
mut maxΒ := 0.0
mut countΒ := []int{len: n}
for _ in 0..repeats {
count[f()-1]++
}
expectedΒ := f64(repeats) / f64(n)
for c in count {
max = math.max(max, math.abs(f64(c)-expected))
}
return max, max < delta
}
Β
// Driver, produces output satisfying both tasks.
fn main() {
rand.seed(seed.time_seed_array(2))
callsΒ := 1000000
mut max, mut flat_enoughΒ := dist_check(dice7, 7, calls, 500)
println("Max delta: $max Flat enough: $flat_enough")
max, flat_enough = dist_check(dice7, 7, calls, 500)
println("Max delta: $max Flat enough: $flat_enough")
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive | Verify distribution uniformity/Naive | This task is an adjunct to Seven-sided dice from five-sided dice.
Task
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
The function should take as arguments:
The function (or object) producing random integers.
The number of times to call the integer generator.
A 'delta' value of some sort that indicates how close to a flat distribution is close enough.
The function should produce:
Some indication of the distribution achieved.
An 'error' if the distribution is not flat enough.
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).
See also:
Verify distribution uniformity/Chi-squared test
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
import "/sort" for Sort
Β
var r = Random.new()
Β
var dice5 = Fn.new { 1 + r.int(5) }
Β
var checkDist = Fn.new { |gen, nRepeats, tolerance|
var occurs = {}
for (i in 1..nRepeats) {
var d = gen.call()
occurs[d] = occurs.containsKey(d) ? occurs[d] + 1 : 1
}
var expected = (nRepeats/occurs.count).floor
var maxError = (expected*tolerance/100).floor
System.print("Repetitions =Β %(nRepeats), Expected =Β %(expected)")
System.print("Tolerance =Β %(tolerance)\%, Max Error =Β %(maxError)\n")
System.print("Integer Occurrences Error Acceptable")
var f = " $d $5d $5d $s"
var allAcceptable = true
occurs = occurs.toList
Sort.quick(occurs)
for (me in occurs) {
var error = (me.value - expected).abs
var acceptable = (error <= maxError) ? "Yes" : "No"
if (acceptable == "No") allAcceptable = false
Fmt.print(f, me.key, me.value, error, acceptable)
}
System.print("\nAcceptable overall:Β %(allAcceptableΒ ? "Yes"Β : "No")")
}
Β
checkDist.call(dice5, 1e6, 0.5)
System.print()
checkDist.call(dice5, 1e5, 0.5) |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #Factor | Factor | USING: kernel math prettyprint sequencesΒ ;
Β
[let
{ 1 2 2 3 4 4 5 }Β :> s
s length <iota> [| i |
i s nth -1Β :> ( curr prev! )
i 0 > curr prev = and
[ i . ] when
curr prev!
] each
] |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #FreeBASIC | FreeBASIC | Dim As Integer s(1 To 7) => {1,2,2,3,4,4,5}
For i As Integer = 1 To Ubound(s)
Dim As Integer curr = s(i), prev
If i > 1 And curr = prev Then Print i
prev = curr
Next i
Sleep |
http://rosettacode.org/wiki/Variable_declaration_reset | Variable declaration reset | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| #Go | Go | package main
Β
import "fmt"
Β
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
Β
// There is no output as 'prev' is created anew each time
// around the loop and set implicitly to zero.
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
Β
// Now 'prev' is created only once and reassigned
// each time around the loop producing the desired output.
var prev int
for i := 0; i < len(s); i++ {
curr := s[i]
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
} |
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
| #11l | 11l | F vdc(=n, base = 2)
V (vdc, denom) = (0.0, 1)
L nΒ != 0
denom *= base
(n, V remainder) = divmod(n, base)
vdc += Float(remainder) / denom
R vdc
Β
print((0.<10).map(i -> vdc(i)))
print((0.<10).map(i -> vdc(i, 3))) |
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
| #68000_Assembly | 68000 Assembly | MyVar:
DC.L 0 ;reserves 4 bytes of storage. The label MyVar represents the address of the four 0 bytes shown here.
Β
MyOtherVar:
DC.L $C0 ;reserves 8 bytes of storage. The first four bytes are initialized to 00 00 00 C0 and the second four to $00 $00 $01 $F4.
DC.L 500 ;MyOtherVar points to the first four bytes, you'll need pointer arithmetic to get to the second four. |
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.
| #AArch64_Assembly | AArch64 Assembly | Β
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program vanEckSerie64.s */
Β
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
Β
.equ MAXI, 1000
Β
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResultElement: .asciz " @ "
szCarriageReturn: .asciz "\n"
Β
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
TableVanEck: .skip 8 * MAXI
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x2,#0 // begin first element
mov x3,#0 // current counter
ldr x4,qAdrTableVanEck // table address
str x2,[x4,x3,lsl 3] // store first zΓ©ro
1: // begin loop
mov x5,x3 // init current indice
2:
sub x5,x5,1 // decrement
cmp x5,0 // end tableΒ ?
blt 3f
ldr x6,[x4,x5,lsl 3] // load element
cmp x6,x2 // and compare with the last element
bne 2b // not equal
sub x2,x3,x5 // else compute gap
b 4f
3:
mov x2,#0 // first, move zero to next element
4:
add x3,x3,#1 // increment counter
str x2,[x4,x3,lsl 3] // and store new element
cmp x3,MAXI
blt 1b
Β
mov x2,0
5: // loop display ten elements
ldr x0,[x4,x2,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10 // call dΓ©cimal conversion
ldr x0,qAdrsMessResultElement
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x1,0 // final zΓ©ro
strb w1,[x0,5] //
bl affichageMess // display message
add x2,x2,1 // increment indice
cmp x2,10 // endΒ ?
blt 5b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
Β
mov x2,MAXI - 10
6: // loop display ten elements 990-999
ldr x0,[x4,x2,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10 // call dΓ©cimal conversion
ldr x0,qAdrsMessResultElement
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x1,0 // final zΓ©ro
strb w1,[x0,5] //
bl affichageMess // display message
add x2,x2,1 // increment indice
cmp x2,MAXI // endΒ ?
blt 6b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
Β
100: // standard end of the program
mov x0, 0 // return code
mov x8, EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResultElement: .quad sMessResultElement
qAdrsZoneConv: .quad sZoneConv
qAdrTableVanEck: .quad TableVanEck
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Β |
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.
| #Action.21 | Action! | INT FUNC LastPos(INT ARRAY a INT count,value)
INT pos
Β
pos=count-1
WHILE pos>=0 AND a(pos)#value
DO
pos==-1
OD
RETURN (pos)
Β
PROC Main()
DEFINE MAX="1000"
INT ARRAY seq(MAX)
INT i,pos
Β
seq(0)=0
FOR i=1 TO MAX-1
DO
pos=LastPos(seq,i-1,seq(i-1))
IF pos>=0 THEN
seq(i)=i-1-pos
ELSE
seq(i)=0
FI
OD
Β
PrintE("Van Eck first 10 terms:")
FOR i=0 TO 9
DO
PrintI(seq(i)) Put(32)
OD
PutE() PutE()
Β
PrintE("Van Eck terms 991-1000:")
FOR i=990 TO 999
DO
PrintI(seq(i)) Put(32)
OD
RETURN |
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
| #AutoHotkey | AutoHotkey | SetBatchLines -1 ; used to improve performance
; (you can make it much faster by removing the informative tooltips)
Β
;********************
; CONFIG
;********************
StartingNumber := 10
NumberLimit := 126030
CounterLimit := 25 ; calculations stop when one of these limits is reached
AdditionalNumbers := "16758243290880,24959017348650,14593825548650"
;********************
Β
CurrentCounter := 0, CurrentNumber := StartingNumber
Β
Loop {
ifΒ !Mod(A_Index,75) ; informative tooltip (every 75 calculations, to avoid slowing down)
ToolTip,Β % "Checking numbers...`nNumber: " CurrentNumber
. "/" NumberLimit "`nFound: " CurrentCounter "/" CounterLimit
if ( CurrentCounter >= CounterLimit ) || ( CurrentNumber >= NumberLimit )
Break
if Mod(StrLen(CurrentNumber),2)
CurrentNumber *= 10
else if ( ( CurrentResult := GetFangs(CurrentNumber) ) <> "" )
Output .= "`n" CurrentNumber ":`t" CurrentResult, CurrentCounter++
CurrentNumber++
}
ToolTip ; hide informative tooltip
Β
MsgBoxΒ % SubStr(Output,2) ; show output (first part)
Β
Output := ""
Loop, Parse, AdditionalNumbers,Β % ","
{
ToolTip,Β % "Getting fangs for " A_LoopField " ..." ; informative tooltip
Output .= "`n" A_LoopField ":`n`t" GetFangs(A_LoopField) "`n"
}
ToolTip ; hide informative tooltip
Β
MsgBoxΒ % SubStr(Output,2) ; show output (second part - additional numbers)
ExitApp
Β
;----------------------------------------------------------------------------------
Β
CharSorter(Input) { ; required by GetFangs()
Loop, Parse, Input
Output .= A_LoopField "`n"
Sort, Output
StringReplace, Output, Output,Β % "`n",, All
Return Output
}
Β
;----------------------------------------------------------------------------------
Β
GetFangs(CurrentNumber) { ; requires CharSorter()
ResultIndex := 1
Length := StrLen(CurrentNumber)
Power := (Length//2)-1
if Mod(Length,2) ORΒ !Power
Return ""
NumberLimit := Floor(Sqrt(CurrentNumber))
Lower := 10 ** Power
Loop,Β % NumberLimit - Lower {
ifΒ !Mod(CurrentNumber,Lower) {
FactorTwo := CurrentNumber//Lower
if (Β !Mod(Lower,10) &&Β !Mod(FactorTwo,10) )
Return ""
Check := CharSorter( Lower . FactorTwo )
if (CharSorter(CurrentNumber) = Check) && (StrLen(Lower) = StrLen(FactorTwo))
Output .= "`n`t[" Lower "," FactorTwo "]"
}
Lower++
}
Return SubStr(Output,3) ; 3 = 1 + length of "`n`t"
} |
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.
| #Nim | Nim | import strformat
Β
proc toSeq(x: uint64): seq[uint8] =
var x = x
var f = 0u64
for i in countdown(9u64, 1):
if (x and 127'u64 shl (i * 7)) > 0:
f = i
break
for j in 0u64..f:
result.add uint8((x shr ((f - j) * 7)) and 127) or 128
Β
result[f] = result[f] xor 128'u8
Β
proc fromSeq(xs: openArray[uint8]): uint64 =
for x in xs:
result = (result shl 7) or (x and 127)
Β
for x in [0x7f'u64, 0x4000'u64, 0'u64, 0x3ffffe'u64, 0x1fffff'u64,
0x200000'u64, 0x3311a1234df31413'u64]:
let c = toSeq(x)
echo &"seq from {x}: {c} back: {fromSeq(c)}" |
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.
| #OCaml | OCaml | let to_vlq n =
let a, b = n lsr 7, n land 0x7F in
let rec aux n acc =
let x = (n land 0x7F) lor 0x80
and xs = n lsr 7 in
if xs > 0
then aux xs (x::acc)
else x::acc
in
aux a [b]
Β
let to_num = List.fold_left (fun n x -> n lsl 7 + (x land 0x7F)) 0
Β
let v_rep n =
Printf.printf "%d ->" n;
let seq = to_vlq n in
List.iter (Printf.printf " 0x%02X") seq;
let num = to_num seq in
Printf.printf "->Β %d\n%!" num;
assert (n = num)
Β
let _ =
v_rep 0x200000;
v_rep 0x1FFFFF
Β |
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
| #Common_Lisp | Common Lisp | (defun example (&rest args)
(dolist (arg args)
(print arg)))
Β
(example "Mary" "had" "a" "little" "lamb")
Β
(let ((args '("Mary" "had" "a" "little" "lamb")))
(apply #'example 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
| #Coq | Coq | Β
Fixpoint Arity (A B: Set) (n: nat): SetΒ := match n with
|O => B
|S n' => A -> (Arity A B n')
end.
Β |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Delphi | Delphi | i := sizeof({any variable or data type identifier}); |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Elixir | Elixir | list = [1,2,3]
IO.puts length(list) #=> 3
Β
tuple = {1,2,3,4}
IO.puts tuple_size(tuple) #=> 4
Β
string = "Elixir"
IO.puts String.length(string) #=> 6
IO.puts byte_size(string) #=> 6
IO.puts bit_size(string) #=> 48
Β
utf8 = "βΓβ³"
IO.puts String.length(utf8) #=> 3
IO.puts byte_size(utf8) #=> 8
IO.puts bit_size(utf8) #=> 64
Β
bitstring = <<3Β :: 2>>
IO.puts byte_size(bitstring) #=> 1
IO.puts bit_size(bitstring) #=> 2
Β
map = Map.new([{:b, 1}, {:a, 2}])
IO.puts map_size(map) #=> 2 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Erlang | Erlang | 24> erlang:tuple_size( {1,2,3} ).
3
25> erlang:length( [1,2,3] ).
3
29> erlang:bit_size( <<1:11>> ).
11
30> erlang:byte_size( <<1:11>> ).
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
| #J | J | 5 7+2 3
7 10
5 7-2 3
3 4
5 7*11
55 77
5 7%2
2.5 3.5 |
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
| #Java | Java | import java.util.Locale;
Β
public class Test {
Β
public static void main(String[] args) {
System.out.println(new Vec2(5, 7).add(new Vec2(2, 3)));
System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3)));
System.out.println(new Vec2(5, 7).mult(11));
System.out.println(new Vec2(5, 7).div(2));
}
}
Β
class Vec2 {
final double x, y;
Β
Vec2(double x, double y) {
this.x = x;
this.y = y;
}
Β
Vec2 add(Vec2 v) {
return new Vec2(x + v.x, y + v.y);
}
Β
Vec2 sub(Vec2 v) {
return new Vec2(x - v.x, y - v.y);
}
Β
Vec2 div(double val) {
return new Vec2(x / val, y / val);
}
Β
Vec2 mult(double val) {
return new Vec2(x * val, y * val);
}
Β
@Override
public String toString() {
return String.format(Locale.US, "[%s,Β %s]", x, y);
}
} |
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test | Verify distribution uniformity/Chi-squared test | Task
Write a function to verify that a given distribution of values is uniform by using the
Ο
2
{\displaystyle \chi ^{2}}
test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%).
The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.
Reference
Β an entry at the MathWorld website: Β chi-squared distribution.
| #Sidef | Sidef | # Confluent hypergeometric function of the first kind F_1(a;b;z)
func F1(a, b, z, limit=100) {
sum(0..limit, {|k|
rising_factorial(a, k) / rising_factorial(b, k) * z**k / k!
})
}
Β
func Ξ³(a,x) { # lower incomplete gamma function Ξ³(a,x)
#a**(-1) * x**a * F1(a, a+1, -x) # simpler formula
a**(-1) * x**a * exp(-x) * F1(1, a+1, x) # slightly better convergence
}
Β
func P(a,z) { # regularized gamma function P(a,z)
Ξ³(a,z) / Ξ(a)
}
Β
func chi_squared_cdf (k, x) {
var f = (k<20Β ? 20Β : 10)
given(x) {
when (0) { 0 }
case (. < (k + f*sqrt(k))) { P(k/2, x/2) }
else { 1 }
}
}
Β
func chi_squared_test(arr, significance = 0.05) {
var n = arr.len
var N = arr.sum
var expected = N/n
var Ο_squared = arr.sum_by {|v| (v-expected)**2 / expected }
var p_value = (1 - chi_squared_cdf(n-1, Ο_squared))
[Ο_squared, p_value, p_value > significance]
}
Β
[
%n< 199809 200665 199607 200270 199649 >,
%n< 522573 244456 139979 71531 21461 >,
].each {|dataset|
var r = chi_squared_test(dataset)
say "data: #{dataset}"
say "ΟΒ² = #{r[0]}, p-value = #{r[1].round(-4)}, uniform = #{r[2]}\n"
} |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher | Vigenère cipher | Task
Implement a  Vigenère cypher,  both encryption and decryption.
The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters.
(If your program handles non-alphabetic characters in another way,
make a note of it.)
Related tasks
Β Caesar cipher
Β Rot-13
Β Substitution Cipher
| #Liberty_BASIC | Liberty BASIC | Β
ori$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key$ = filter$("vigenerecipher")
print ori$
print key$
enc$ = encrypt$(ori$, key$)
print enc$
dec$ = decrypt$(enc$, key$)
print dec$
Β
end
Β
function encrypt$(text$, key$)
flt$ = filter$(text$)
encrypt$ = ""
j = 1
for i = 1 to len(flt$)
m$ = mid$(flt$, i, 1)
m = asc(m$)-asc("A")
k$ = mid$(key$, j, 1)
k = asc(k$)-asc("A")
j = (j mod len(key$)) + 1
c = (m + k) mod 26
c$=chr$(asc("A")+c)
encrypt$=encrypt$+c$
next
end function
Β
function decrypt$(flt$, key$)
decrypt$ = ""
j = 1
for i = 1 to len(flt$)
m$ = mid$(flt$, i, 1)
m = asc(m$)-asc("A")
k$ = mid$(key$, j, 1)
k = asc(k$)-asc("A")
j = (j mod len(key$)) + 1
c = (m - k + 26) mod 26
c$=chr$(asc("A")+c)
decrypt$=decrypt$+c$
next
end function
Β
function filter$(ori$)
'a..z A..Z go caps, other skipped
filter$=""
for i = 1 to len(ori$)
c$ = upper$(mid$(ori$,i,1))
if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c$) then filter$ = filter$ + c$
next
end function
Β |
http://rosettacode.org/wiki/Visualize_a_tree | Visualize a tree | A tree structure Β (i.e. a rooted, connected acyclic graph) Β is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
Β indented text Β (Γ la unix tree command)
Β nested HTML tables
Β hierarchical GUI widgets
Β 2D Β or Β 3D Β images
Β etc.
Task
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| #REXX | REXX | /* REXX ***************************************************************
* 10.05.2014 Walter Pachl using the tree and the output format of C
**********************************************************************/
Call mktree
Say node.1.0name
Call tt 1,''
Exit
Β
tt: Procedure Expose node.
/**********************************************************************
* show a subtree (recursively)
**********************************************************************/
Parse Arg k,st
Do i=1 To node.k.0
If i=node.k.0 Then
s='`--'
Else
s='|--'
c=node.k.i
If st<>'' Then
st=left(st,length(st)-2)' '
st=changestr('` ',st,' ')
Say st||s||node.c.0name
Call tt c,st||s
End
Return
Exit
Β
mktree: Procedure Expose node. root
/**********************************************************************
* build the tree according to the task
**********************************************************************/
node.=0
r=mknode('R');
a=mknode('A'); Call attchild a,r
b=mknode('B'); Call attchild b,a
c=mknode('C'); Call attchild c,a
d=mknode('D'); Call attchild d,b
e=mknode('E'); Call attchild e,b
f=mknode('F'); Call attchild f,b
g=mknode('G'); Call attchild g,b
h=mknode('H'); Call attchild h,d
i=mknode('I'); Call attchild i,h
j=mknode('J'); Call attchild j,i
k=mknode('K'); Call attchild k,j
l=mknode('L'); Call attchild l,j
m=mknode('M'); Call attchild m,e
n=mknode('N'); Call attchild n,e
Return
Β
mknode: Procedure Expose node.
/**********************************************************************
* create a new node
**********************************************************************/
Parse Arg name
z=node.0+1
node.z.0name=name
node.0=z
Return z /* number of the node just created */
Β
attchild: Procedure Expose node.
/**********************************************************************
* make a the next child of father
**********************************************************************/
Parse Arg a,father
node.a.0father=father
z=node.father.0+1
node.father.z=a
node.father.0=z
node.a.0level=node.father.0level+1
Return
Β |
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).
| #PureBasic | PureBasic | Procedure.s WalkRecursive(dir,path.s,Pattern.s="\.txt$")
Static RegularExpression
If Not RegularExpression
RegularExpression=CreateRegularExpression(#PB_Any,Pattern)
EndIf
Β
While NextDirectoryEntry(dir)
If DirectoryEntryType(dir)=#PB_DirectoryEntry_Directory
If DirectoryEntryName(dir)<>"." And DirectoryEntryName(dir)<>".."
If ExamineDirectory(dir+1,path+DirectoryEntryName(dir),"")
WalkRecursive(dir+1,path+DirectoryEntryName(dir)+"\",Pattern)
FinishDirectory(dir+1)
Else
Debug "Error in "+path+DirectoryEntryName(dir)
EndIf
EndIf
Else ; e.g. #PB_DirectoryEntry_File
If MatchRegularExpression(RegularExpression,DirectoryEntryName(dir))
Debug DirectoryEntryName(dir)
EndIf
EndIf
Wend
EndProcedure |
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.
| #Ruby | Ruby | Β
def a(array)
n=array.length
left={}
right={}
left[0]=array[0]
i=1
loop do
break if i >=n
left[i]=[left[i-1],array[i]].max
i += 1
end
right[n-1]=array[n-1]
i=n-2
loop do
break if i<0
right[i]=[right[i+1],array[i]].max
i-=1
end
i=0
water=0
loop do
break if i>=n
water+=[left[i],right[i]].min-array[i]
i+=1
end
puts water
end
Β
a([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ])
a([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ])
a([ 5, 5, 5, 5 ])
a([ 5, 6, 7, 8 ])
a([ 8, 7, 7, 6 ])
a([ 6, 7, 10, 7, 6 ])
return |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: Β (X, Y, Z).
If you imagine a graph with the Β x Β and Β y Β axis being at right angles to each other and having a third, Β z Β axis coming out of the page, then a triplet of numbers, Β (X, Y, Z) Β would represent a point in the region, Β and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
The dot product Β Β Β (a scalar quantity)
A β’ B = a1b1 Β + Β a2b2 Β + Β a3b3
The cross product Β Β Β (a vector quantity)
A x B = (a2b3Β - Β a3b2, Β Β a3b1 Β - Β a1b3, Β Β a1b2 Β - Β a2b1)
The scalar triple product Β Β Β (a scalar quantity)
A β’ (B x C)
The vector triple product Β Β Β (a vector quantity)
A x (B x C)
Task
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
Create a named function/subroutine/method to compute the dot product of two vectors.
Create a function to compute the cross product of two vectors.
Optionally create a function to compute the scalar triple product of three vectors.
Optionally create a function to compute the vector triple product of three vectors.
Compute and display: a β’ b
Compute and display: a x b
Compute and display: a β’ (b x c), the scalar triple product.
Compute and display: a x (b x c), the vector triple product.
References
Β A starting page on Wolfram MathWorld is Β Vector Multiplication .
Β Wikipedia Β dot product.
Β Wikipedia Β cross product.
Β Wikipedia Β triple product.
Related tasks
Β Dot product
Β Quaternion type
| #AutoHotkey | AutoHotkey | V := {a: [3, 4, 5], b: [4, 3, 5], c: [-5, -12, -13]}
Β
for key, val in V
Out .= key " = (" val[1] ", " val[2] ", " val[3] ")`n"
Β
CP := CrossProduct(V.a, V.b)
VTP := VectorTripleProduct(V.a, V.b, V.c)
Β
MsgBox,Β % Out "`na β’ b = " DotProduct(V.a, V.b) "`n"
. "a x b = (" CP[1] ", " CP[2] ", " CP[3] ")`n"
. "a β’ b x c = " ScalerTripleProduct(V.a, V.b, V.c) "`n"
. "a x b x c = (" VTP[1] ", " VTP[2] ", " VTP[3] ")"
Β
DotProduct(v1, v2) {
return, v1[1] * v2[1] + v1[2] * v2[2] + v1[3] * v2[3]
}
Β
CrossProduct(v1, v2) {
return, [v1[2] * v2[3] - v1[3] * v2[2]
, v1[3] * v2[1] - v1[1] * v2[3]
, v1[1] * v2[2] - v1[2] * v2[1]]
}
Β
ScalerTripleProduct(v1, v2, v3) {
return, DotProduct(v1, CrossProduct(v2, v3))
}
Β
VectorTripleProduct(v1, v2, v3) {
return, CrossProduct(v1, CrossProduct(v2, v3))
} |
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
| #11l | 11l | F check_isin(a)
I a.lenΒ != 12
R 0B
[Int] s
L(c) a
I c.is_digit()
I L.index < 2
R 0B
s.append(c.code - 48)
E I c.is_uppercase()
I L.index == 11
R 0B
V (d, m) = divmod(c.code - 55, 10)
s [+]= [d, m]
E
R 0B
V v = sum(s[((len)-1..).step(-2)])
L(=k) s[((len)-2..).step(-2)]
k = 2 * k
v += I k > 9 {k - 9} E k
R vΒ % 10 == 0
Β
print([βUS0378331005β, βUS0373831005β, βU50378331005β, βUS03378331005β,
βAU0000XVGZA3β, βAU0000VXGZA3β, βFR0000988040β].map(s -> check_isin(s))) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.