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(... |
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... | #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... |
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 t... |
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... |
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-... |
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)))
... |
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 distribut... | #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= 52257... |
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 ... | #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(c... |
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 ... | #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]),
ne... |
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.
... | #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-nota... |
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.
... | #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 = Patt... |
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 ... | #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 $f... |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ... | #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-... |
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 repr... | #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 ... | #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 ... | #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)
}
... |
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 ... | #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 ... | #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... |
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 ... | #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 - 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 (209... | #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 = shi... |
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 (209... | #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) ... |
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... |
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... |
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... | #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("... |
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); ... |
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
... |
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 distribut... | #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
... |
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 ... | #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() -... |
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 ... | #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 [d... |
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.
... | #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.
... | #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 ... | #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 "s@.l") (chop F)) # Matches 's*.l'?
... |
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 ... | #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 ██ ... | #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... |
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 repr... | #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 n... |
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 ... | #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: ... |
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 ... | #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 ... |
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 ... | #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 transl... |
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 ... | #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 l... |
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 ... | #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 ; Shif... |
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 exactl... | #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... |
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 (209... | #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 Number... |
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 (209... | #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 divisi... |
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(in... |
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... | #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 cartes... |
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 distribut... | #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, di... |
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 distribut... | #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: Doubl... |
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 ... | #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.g... |
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 ... | #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 "\\-" "+-") (c... |
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 ... | #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 ... |
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 ... | #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 ... | #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_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 ██ ... | #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)
... |
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 repr... | #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... |
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 ... | #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
... |
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 ... | #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 / ... |
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 ... | #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] + ... |
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 ... | #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 ... | #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 ... | #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 {
fm... |
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 o... | #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... |
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 ... | #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 "../includeConstante... |
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 ... | #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
... |
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 exactl... | #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 := "167582432... |
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 (209... | #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: openArra... |
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 (209... | #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;
l... |
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.leng... |
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... | #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... | #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... |
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 distribut... | #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... |
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 ... | #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... |
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 ... | #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.
/*******************************... |
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 ... | #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 D... |
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 ██ ... | #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
... |
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 repr... | #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 ... |
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 c... | #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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.