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/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 ... | #zkl | zkl | fcn rtest(N){
dist:=L(0,0,0,0,0,0,0,0,0,0);
do(N){n:=(0).random(10); dist[n]=dist[n]+1}
sum:=dist.sum();
dist=dist.apply('wrap(n){n.toFloat()/sum*100});
if (dist.filter((10.0).closeTo.fp1(0.1)).len() == 10)
{ "Good enough at %,d: %s".fmt(N,dist).println(); return(True); }
False
}
n:=10;
while... |
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 ... | #J | J | 1+I.(}:=}.) 1 2 2 3 4 4 5
2 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 ... | #Java | Java | public class VariableDeclarationReset {
public static void main(String[] args) {
int[] s = {1, 2, 2, 3, 4, 4, 5};
// There is no output as 'prev' is created anew each time
// around the loop and set to zero.
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
... |
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 ... | #JavaScript | JavaScript | <!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>variable declaration reset</title>
</head>
<body>
<script>
"use strict";
let s = [1, 2, 2, 3, 4, 4, 5];
for (let i=0; i<7; i+=1) {
let curr = s[i], prev;
if (i... |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #360_Assembly | 360 Assembly | * Van der Corput sequence 31/01/2017
VDCS CSECT
USING VDCS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) ... |
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... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Generate(INT value,base REAL POINTER res)
REAL denom,rbase,r1,r2
IntToReal(0,res)
IntToReal(1,denom)
IntToReal(base,rbase)
WHILE value#0
DO
RealMult(denom,rbase,r1)
RealAssign(r1,denom)
IntToReal(value MOD base,r1)
RealDiv(r1,denom,r2... |
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
| #8086_Assembly | 8086 Assembly | .data
MyVar word 0FFFFh ;the leading zero is just to help the assembler tell that this is a number, it's not actually part of the variable.
.code
mov ax, word ptr [ds:MyVar] |
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
| #8th | 8th |
\ declare a variable which is initialized to the number '0'
var x
\ declare a variable which is initialized to a string "cat"
"cat" var, y
\ Get the value in x, add 20 and store it:
x @ 20 n:+ x !
\ Change the cat to a dog:
"dog" y !
|
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 ... | #Ada | Ada | with Ada.Text_IO;
procedure Van_Eck_Sequence is
Sequence : array (Natural range 1 .. 1_000) of Natural;
procedure Calculate_Sequence is
begin
Sequence (Sequence'First) := 0;
for Index in Sequence'First .. Sequence'Last - 1 loop
Sequence (Index + 1) := 0;
for I in reverse Seq... |
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... | #Bracmat | Bracmat | ( ( vampire
= N len R fangsList
. !arg:@(?N:? [?len)
& 1/2*!len:~/:?len
& ( R
= len numpart left right allowed fangs rdigits
, tried digit untried head tail found
. !arg:(?len.?left.?numpart.?allowed)
& :?found
& ( !len:>0
... |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactl... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
typedef uint64_t xint;
typedef unsigned long long ull;
xint tens[20];
inline xint max(xint a, xint b) { return a > b ? a : b; }
inline xint min(xint a, xint b) { return a < b ? a : b; }
inline int ndigits(xint x)
{
int n = 0;
while (x)... |
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... | #PARI.2FGP | PARI/GP | hex(s)=my(a=10,b=11,c=12,d=13,e=14,f=15);subst(Pol(eval(Vec(s))),'x,16);
n1=hex("200000");n2=hex("1fffff");
v1=digits(n1,256)
v2=digits(n2,256)
subst(Pol(v1),'x,256)==n1
subst(Pol(v2),'x,256)==n2 |
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... | #Perl | Perl |
use warnings;
use strict;
for my $testcase (
0, 0xa, 123, 254, 255, 256,
257, 65534, 65535, 65536, 65537, 0x1fffff,
0x200000
)
{
my @vlq = vlq_encode($testcase);
printf "%8s %12s %8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq);
}
sub vlq_encode {
my @vlq;
my $binary... |
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... | #D | D | import std.stdio, std.algorithm;
void printAll(TyArgs...)(TyArgs args) {
foreach (el; args)
el.writeln;
}
// Typesafe variadic function for dynamic array
void showSum1(int[] items...) {
items.sum.writeln;
}
// Typesafe variadic function for fixed size array
void showSum2(int[4] items...) {
ite... |
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... | #Delphi | Delphi | func printAll(args...) {
for i in args {
print(i)
}
}
printAll("test", "rosetta code", 123, 5.6) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Factor | Factor | USING: layouts memory prettyprint ;
! Show size in bytes
{ 1 2 3 } size . ! 48
1231298302914891021239102 size . ! 48
! Doesn't work on fixnums and other immediate objects
10 size . ! 0
! Show number of bits in a fixnum
fixnum-bits . ! 60 |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Forth | Forth | : .CELLSIZE ( -- ) CR 1 CELLS . ." Bytes" ;
VARIABLE X ( creates a variable 1 cell wide) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Fortran | Fortran | INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2)
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
INTEGER, PARAMETER :: i64 = SELECTED_INT_KIND(16)
INTEGER(i8) :: onebyte = 0
INTEGER(i16) :: twobytes = 0
INTEGER(i32) :: fourbytes = 0
INTEGER(i64) :: eightbytes = 0
WRI... |
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... | #jq | jq | def polar(r; angle):
[ r*(angle|cos), r*(angle|sin) ];
# If your jq allows multi-arity functions, you may wish to uncomment the following line:
# def polar(r): [r, 0];
def polar2vector: polar(.[0]; .[1]);
def vector(x; y):
if (x|type) == "number" and (y|type) == "number" then [x,y]
else error("TypeError")
... |
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... | #Julia | Julia | module SpatialVectors
export SpatialVector
struct SpatialVector{N, T}
coord::NTuple{N, T}
end
SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} =
SpatialVector{N, T}(e .- s)
function SpatialVector(∠::T, val::T) where T
θ = atan(∠)
x = val * cos(θ)
y = val * sin(θ)
return SpatialVec... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require math::statistics
proc isUniform {distribution {significance 0.05}} {
set count [tcl::mathop::+ {*}[dict values $distribution]]
set expected [expr {double($count) / [dict size $distribution]}]
set X2 0.0
foreach value [dict values $distribution] {
set X2 [expr {... |
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 ... | #Lua | Lua | function Encrypt( _msg, _key )
local msg = { _msg:upper():byte( 1, -1 ) }
local key = { _key:upper():byte( 1, -1 ) }
local enc = {}
local j, k = 1, 1
for i = 1, #msg do
if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then
enc[k] = ( msg[i] + key[j] - 2*... |
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 ... | #Ruby | Ruby |
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
|
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 ... | #Rust | Rust |
extern crate rustc_serialize;
extern crate term_painter;
use rustc_serialize::json;
use std::fmt::{Debug, Display, Formatter, Result};
use term_painter::ToStyle;
use term_painter::Color::*;
type NodePtr = Option<usize>;
#[derive(Debug, PartialEq, Clone, Copy)]
enum Side {
Left,
Right,
Up,
}
#[deri... |
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_2 | 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 ██ ... | #Rust | Rust |
use std::cmp::min;
fn getfill(pattern: &[usize]) -> usize {
let mut total = 0;
for (idx, val) in pattern.iter().enumerate() {
let l_peak = pattern[..idx].iter().max();
let r_peak = pattern[idx + 1..].iter().max();
if l_peak.is_some() && r_peak.is_some() {
let peak = min(l... |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
a[1] = 3; a[2]= 4; a[3] = 5;
b[1] = 4; b[2]= 3; b[3] = 5;
c[1] = -5; c[2]= -12; c[3] = -13;
print "a = ",printVec(a);
print "b = ",printVec(b);
print "c = ",printVec(c);
print "a.b = ",dot(a,b);
## upper case variables are used as temporary or inte... |
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... | #360_Assembly | 360 Assembly | * Validate ISIN 08/03/2019
VALISIN CSECT
USING VALISIN,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST... |
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... | #Ada | Ada | procedure ISIN is
-- Luhn_Test copied from other Task
function Luhn_Test (Number: String) return Boolean is
Sum : Natural := 0;
Odd : Boolean := True;
Digit: Natural range 0 .. 9;
begin
for p in reverse Number'Range loop
Digit := Integer'Value (Number (p..p));
if Odd... |
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 ... | #jq | jq | [1,2,2,3,4,4,5]
| . as $array
| range(1;length)
| select( $array[.] == $array[.-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 ... | #Julia | Julia |
s = [1, 2, 2, 3, 4, 4, 5]
for i in eachindex(s)
curr = s[i]
i > 1 && curr == prev && println(i)
prev = curr
end
|
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 ... | #Perl | Perl | @s = <1 2 2 3 4 4 5>;
for ($i = 0; $i < 7; $i++) {
$curr = $s[$i];
if ($i > 1 and $curr == $prev) { print "$i\n" }
$prev = $curr;
} |
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 ... | #Phix | Phix | with javascript_semantics
sequence s = {1,2,2,3,4,4,5}
for i=1 to length(s) do
integer curr = s[i], prev
if i>1 and curr=prev then
?i
end if
prev = curr
end for
|
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #ActionScript | ActionScript |
package {
import flash.display.Sprite;
import flash.events.Event;
public class VanDerCorput extends Sprite {
public function VanDerCorput():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event =... |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program variable64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM... |
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 ... | #ALGOL_68 | ALGOL 68 | BEGIN # find elements of the Van Eck Sequence - first term is 0, following #
# terms are 0 if the previous was the first appearance of the element #
# or how far back in the sequence the last element appeared #
# returns the first n elements of the Van Eck sequence #
OP V... |
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... | #C.23 | C# | using System;
namespace RosettaVampireNumber
{
class Program
{
static void Main(string[] args)
{
int i, j, n;
ulong x;
var f = new ulong[16];
var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 };
ulong[] ... |
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... | #Phix | Phix | function vlq_encode(sequence s)
sequence res = {}
for i=length(s) to 1 by -1 do
integer n = s[i], msb = 0
if n<0 then crash("unsigned integers only!") end if
while 1 do
res = prepend(res,msb+and_bits(n,#7F))
n = floor(n/#80)
if n=0 then exit end if
... |
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... | #Dyalect | Dyalect | func printAll(args...) {
for i in args {
print(i)
}
}
printAll("test", "rosetta code", 123, 5.6) |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | show-all(:
while /= ) dup:
!.
drop
show-all( :foo "Hello" 42 [ true ] ) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Free_Pascal | Free Pascal | ' FB 1.05.0 Win64
Dim i As Integer
Dim l As Long
Dim s As Short
Dim b As Byte
Print "An integer occupies "; SizeOf(i); " bytes"
Print "A long occupies "; SizeOf(l); " bytes"
Print "A short occupies "; SizeOf(s); " bytes"
Print "A byte occupies "; SizeOf(b); " byte"
' or use type directly rather than a va... |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim i As Integer
Dim l As Long
Dim s As Short
Dim b As Byte
Print "An integer occupies "; SizeOf(i); " bytes"
Print "A long occupies "; SizeOf(l); " bytes"
Print "A short occupies "; SizeOf(s); " bytes"
Print "A byte occupies "; SizeOf(b); " byte"
' or use type directly rather than a va... |
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... | #Kotlin | Kotlin | // version 1.1.2
class Vector2D(val x: Double, val y: Double) {
operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y)
operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y)
operator fun times(s: Double) = Vector2D(s * x, s * y)
operator fun div(s: Double) = Vector2D(x / s, y / s)
... |
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... | #VBA | VBA | Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level.
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, Degr... |
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... | #Vlang | Vlang | import math
type Ifctn = fn(f64) f64
fn simpson38(f Ifctn, a f64, b f64, n int) f64 {
h := (b - a) / f64(n)
h1 := h / 3
mut sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*f64(j))
} else {
sum += 3 * f(a+h1*f64(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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | encode[text_String, key_String] :=
Module[{textCode, keyCode},
textCode =
Cases[ToCharacterCode[
ToUpperCase@
text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
keyCode =
Cases[ToCharacterCode[
ToUpperCase@
key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
keyCode... |
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 ... | #Sidef | Sidef | func visualize_tree(tree, label, children,
indent = '',
mids = ['├─', '│ '],
ends = ['└─', ' '],
) {
func visit(node, pre) {
gather {
take(pre[0] + label(node))
var chldn = children(node)
var end = chldn.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 ... | #Python | Python |
from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #R | R | dir("/bar/foo", "mp3",recursive=T) |
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 ██ ... | #Scala | Scala | import scala.collection.parallel.CollectionConverters.VectorIsParallelizable
// Program to find maximum amount of water
// that can be trapped within given set of bars.
object TrappedWater extends App {
private val barLines = List(
Vector(1, 5, 3, 7, 2),
Vector(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),
Vector(2, 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 repr... | #BASIC256 | BASIC256 |
a={3,4,5}:b={4,3,5}:c={-5,-12,-13}
print "A.B = "+dot_product(ref(a),ref(b))
call cross_product(ref(a),ref(b),ref(y))
Print "AxB = ("+y[0]+","+y[1]+","+y[2]+")"
print "A.(BxC) = "+s_tri(ref(a),ref(b),ref(c))
call v_tri(ref(a),ref(b),ref(c),ref(x),ref(y))
Print "A x (BxC) = ("+y[0]+","+y[1]+","+y[2]+")"
function ... |
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... | #ALGOL_W | ALGOL W | begin
% external procedure that returns true if ccNumber passes the Luhn test, false otherwise %
logical procedure LuhnTest ( string(32) value ccNumber
; integer value ccLength
) ; algol "LUHN" ;
% returns true if isin is a valid ISIN, false... |
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... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on ISINTest(ISIN)
-- Check that the input is both text and 12 characters long …
if not ((ISIN's class is text) and ((count ISIN) is 12)) then return false
-- … and that it has the required format.
set ISIN to cu... |
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 ... | #PL.2FM | PL/M | 100H:
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END;
/* CONSOLE OUTPUT ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Main is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is
Value : Natural := N;
Result : Float := 0.0;
Exponent : Positive := 1;
begin
while Value > 0 loop
Res... |
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... | #AutoHotkey | AutoHotkey | SetFormat, FloatFast, 0.5
for i, v in [2, 3, 4, 5, 6] {
seq .= "Base " v ": "
Loop, 10
seq .= VanDerCorput(A_Index - 1, v) (A_Index = 10 ? "`n" : ", ")
}
MsgBox, % seq
VanDerCorput(n, b, r=0) {
while n
r += Mod(n, b) * b ** -A_Index, n := n // b
return, r
} |
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
| #Ada | Ada | Name: declare -- a local declaration block has an optional name
A : constant Integer := 42; -- Create a constant
X : String := "Hello"; -- Create and initialize a local variable
Y : Integer; -- Create an uninitialized variable
Z : Integer renames Y: -- Rename Y (creates a view)
function F (X... |
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 ... | #ALGOL-M | ALGOL-M | begin
integer array eck[1:1000];
integer i, j;
for i := 1 step 1 until 1000 do
eck[i] := 0;
for i := 1 step 1 until 999 do
begin
j := i - 1;
while j > 0 and eck[i] <> eck[j] do
j := j - 1;
if j <> 0 then
eck[i+1] := i - j;
end;
for i := 1 step 1 until 10 do
writeon(eck[i]);
wr... |
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 ... | #ALGOL_W | ALGOL W | begin % find elements of the Van Eck Sequence - first term is 0, following %
% terms are 0 if the previous was the first appearance of the element %
% or how far back in the sequence the last element appeared %
% sets s to the first n elements of the Van Eck sequence %
proc... |
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... | #C.2B.2B | C++ | #include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) {
std::ostringstream numberstream ;
numberstream << number ;
std::string numberstring( 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... | #PicoLisp | PicoLisp | (de numToVlq (Num)
(let Res (cons (& Num 127))
(while (gt0 (setq Num (>> 7 Num)))
(push 'Res (| 128 (& Num 127))) )
Res ) )
(de vlqToNum (Vlq)
(let Res 0
(for N Vlq
(setq Res (| (>> -7 Res) (& N 127))) ) ) )
(for Num (0 15 16 127 128 255 2097151 2097152)
(let Vlq (numToV... |
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... | #PL.2FI | PL/I |
test: procedure options(main);
declare s character (20) varying;
declare c character (1);
declare v fixed binary (31);
declare (i, k) fixed binary;
get edit (s) (L);
s = trim (s);
v = 0;
do i = 1 to length(s);
c = substr(s, i, 1);
k = index('0123456789abcdef', c);
if k > 0 ... |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (209... | #Python | Python | def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
... |
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... | #E | E | def example {
match [`run`, args] {
for x in args {
println(x)
}
}
}
example("Mary", "had", "a", "little", "lamb")
E.call(example, "run", ["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... | #Egel | Egel |
[ X Y -> "two" | X -> "one" | -> "zero" ]
|
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Gambas | Gambas | Public Sub Main()
Print "Boolean =\t " & SizeOf(gb.Boolean)
Print "Byte =\t\t " & SizeOf(gb.Byte)
Print "Short =\t\t " & SizeOf(gb.Short)
Print "Integer =\t " & SizeOf(gb.Integer)
Print "Single =\t " & SizeOf(gb.Single)
Print "Long =\t\t " & SizeOf(gb.Long)
Print "Float =\t\t " & SizeOf(gb.Float)
Print "Date =\t\t " ... |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Go | Go | import "unsafe"
unsafe.Sizeof(x) |
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... | #Lua | Lua | vector = {mt = {}}
function vector.new (x, y)
local new = {x = x or 0, y = y or 0}
setmetatable(new, vector.mt)
return new
end
function vector.mt.__add (v1, v2)
return vector.new(v1.x + v2.x, v1.y + v2.y)
end
function vector.mt.__sub (v1, v2)
return vector.new(v1.x - v2.x, v1.y - v2.y)
end
... |
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... | #Wren | Wren | import "/math" for Math, Nums
import "/fmt" for Fmt
var integrate = Fn.new { |a, b, n, f|
var h = (b - a) / n
var sum = 0
for (i in 0...n) {
var x = a + i*h
sum = sum + (f.call(x) + 4 * f.call(x + h/2) + f.call(x + h)) / 6
}
return sum * h
}
var gammaIncomplete = Fn.new { |a, x... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
pt = 'Attack at dawn!'
key = 'LEMON'
test(key, pt)
key = 'N' -- rot-13
test(key, pt)
key = 'B' -- Caesar
test(key, pt)
pt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'A'
test(key, pt)
pt = sampledata()
key = 'Hamlet; Prince of Denm... |
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 ... | #Tcl | Tcl | package require struct::tree
proc visualize_tree {tree {nameattr name}} {
set path {}
$tree walk [$tree rootname] -order both {mode node} {
if {$mode eq "enter"} {
set s ""
foreach p $path {
append s [expr {[$tree next $p] eq "" ? " " : "\u2502 "}]
}
lappend path $node
append s [e... |
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 ... | #Racket | Racket |
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f))
(displayln f))
... *.rkt files including in nested directories ...
|
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 ... | #Raku | Raku | use File::Find;
.say for find dir => '.', name => /'.txt' $/; |
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 ██ ... | #Scheme | Scheme | (import (scheme base)
(scheme write))
(define (total-collected chart)
(define (highest-left vals curr)
(if (null? vals)
(list curr)
(cons curr
(highest-left (cdr vals) (max (car vals) curr)))))
(define (highest-right vals curr)
(reverse (highest-left (reverse vals) curr)))
... |
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... | #BBC_BASIC | BBC BASIC | DIM a(2), b(2), c(2), d(2)
a() = 3, 4, 5
b() = 4, 3, 5
c() = -5, -12, -13
PRINT "a . b = "; FNdot(a(),b())
PROCcross(a(),b(),d())
PRINT "a x b = (";d(0)", ";d(1)", ";d(2)")"
PRINT "a . (b x c) = "; FNscalartriple(a(),b(),c())
PROCvectortriple(a(),b(),c(),d())
... |
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... | #AWK | AWK |
# syntax: GAWK -f VALIDATE_INTERNATIONAL_SECURITIES_IDENTIFICATION_NUMBER.AWK
# converted from Fortran
BEGIN {
for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value
n = split("US0378331005,US0373831005,U50378331005,US03378331005,AU0000XVGZA3,AU0000VXGZA3,FR0000988040",... |
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 ... | #Python | Python |
s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
|
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 ... | #Raku | Raku | my @s = 1, 2, 2, 3, 4, 4, 5;
loop (my $i = 0; $i < 7; $i += 1) {
my $curr = @s[$i];
my $prev;
if $i > 1 and $curr == $prev {
say $i;
}
$prev = $curr;
} |
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 ... | #Red | Red | Red[]
s: [1 2 2 3 4 4 5]
repeat i length? s [
curr: s/:i
if all [i > 1 curr = prev][
print 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 o... | #AWK | AWK |
# syntax: GAWK -f VAN_DER_CORPUT_SEQUENCE.AWK
# converted from BBC BASIC
BEGIN {
printf("base")
for (i=0; i<=9; i++) {
printf(" %7d",i)
}
printf("\n")
for (base=2; base<=5; base++) {
printf("%-4s",base)
for (i=0; i<=9; i++) {
printf(" %7.5f",vdc(i,base))
}
pri... |
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... | #BASIC | BASIC | 10 DEFINT A-Z
20 FOR B=2 TO 5
30 PRINT USING "BASE #:";B;
40 FOR I=0 TO 9
50 P=0: Q=1: N=I
60 IF N=0 GOTO 110
70 P=P*B+N MOD B
80 Q=Q*B
90 N=N\B
100 GOTO 60
110 X=P: Y=Q
120 IF P=0 GOTO 150
130 N=P: P=Q MOD P: Q=N
140 GOTO 120
150 X=X\Q
160 Y=Y\Q
170 IF X=0 THEN PRINT " 0"; ELSE PRINT USING " ##/##";X;Y;
180 NEXT I
... |
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
| #ALGOL_68 | ALGOL 68 | int j; |
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
| #ALGOL_W | ALGOL W | % declare some variables %
integer a1, a2; real b; long real c; complex d; long complex f;
logical g; bits h; string(32) j;
% assign "initial values" %
f := d := c := b := a2 := a1 := 0; % multiple assignment %
g := false; h := #a0; j := "Hello, World!";
|
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 ... | #APL | APL | (10∘↑,[.5]¯10∘↑)(⊢,(⊃∘⌽∊¯1∘↓)∧(1↓⌽)⍳⊃∘⌽)⍣999⊢,0 |
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 ... | #AppleScript | AppleScript | use AppleScript version "2.4"
use scripting additions
-- vanEck :: Int -> [Int]
on vanEck(n)
-- First n terms of the vanEck sequence.
script go
on |λ|(xns, i)
set {x, ns} to xns
set prev to item (1 + x) of ns
if 0 ≠ prev then
set v to i - prev
... |
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... | #Clojure | Clojure | (defn factor-pairs [n]
(for [x (range 2 (Math/sqrt n))
:when (zero? (mod n x))]
[x (quot n x)]))
(defn fangs [n]
(let [dlen (comp count str)
half (/ (dlen n) 2)
halves? #(apply = (cons half (map dlen %)))
digits #(sort (apply str %))]
(filter #(and (halves? %)
... |
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... | #Racket | Racket |
#lang racket
(define (try n)
(printf "Original number: ~s (0x~x)\n" n n)
(define 4octets (integer->integer-bytes n 4 #f))
(printf "Octets: ~a (byte-string: ~s)\n"
(string-join (map (λ(o) (~r o #:base 16))
(bytes->list 4octets))
":")
4octet... |
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... | #Raku | Raku | sub vlq_encode ($number is copy) {
my $string = '';
my $t = 0x7F +& $number;
$number +>= 7;
$string = $t.chr ~ $string;
while ($number) {
$t = 0x7F +& $number;
$string = (0x80 +| $t).chr ~ $string;
$number +>= 7;
}
return $string;
}
sub vlq_decode ($string is copy) {
... |
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... | #Elena | Elena | import system'routines;
import extensions;
extension variadicOp
{
printAll(params object[] list)
{
for(int i := 0, i < list.Length, i+=1)
{
self.printLine(list[i])
}
}
}
public program()
{
console.printAll("test", "rosetta code", 123, 5.6r)
} |
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... | #Elixir | Elixir | defmodule RC do
def print_each( arguments ) do
Enum.each(arguments, fn x -> IO.inspect x end)
end
end
RC.print_each([1,2,3])
RC.print_each(["Mary", "had", "a", "little", "lamb"]) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Haskell | Haskell | import Foreign
sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine) |
http://rosettacode.org/wiki/Variable_size/Get | Variable size/Get | Demonstrate how to get the size of a variable.
See also: Host introspection
| #Icon_and_Unicon | Icon and Unicon | record rec0()
record rec4(a,b,c,d)
procedure main() # get size
every i := seq(1) do {
a0 := &allocated
x := case i of {
1 : "ABCDEFGH"
2 : reverse(x)
10 : &digits
11 : x--x
20 : []
21 : [1,2]
22 : [1,2,3]
... |
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... | #Maple | Maple | module MyVector()
option object;
local value := Vector();
export ModuleApply::static := proc( )
Object( MyVector, _passed );
end proc;
export ModuleCopy::static := proc( mv::MyVector, proto::MyVector, v::Vector, $ )
mv:-value := v;
end proc;
export ModulePrint::static := proc(mv::... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[vector,PrintVector]
vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}]
vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]
a_ vector[x_,y_]^:=vector[a x,a y]
vector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z]
PrintVector[vector[x_,y_]]:=Print["vector has first component: ",x," And second component: ",y]
vector[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... | #zkl | zkl | /* Numerical integration method */
fcn Simpson3_8(f,a,b,N){ // fcn,double,double,Int --> double
h,h1:=(b - a)/N, h/3.0;
h*[1..3*N - 1].reduce('wrap(sum,j){
l1:=(if(j%3) 3.0 else 2.0);
sum + l1*f(a + h1*j);
},f(a) + f(b))/8.0;
}
const A=12;
fcn Gamma_Spouge(z){ // double --> double
var coefs=... |
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 ... | #Nim | Nim | import strutils
proc encrypt(msg, key: string): string =
var pos = 0
for c in msg:
if c in Letters:
result.add chr(((ord(key[pos]) + ord(c.toUpperAscii)) mod 26) + ord('A'))
pos = (pos + 1) mod key.len
proc decrypt(msg, key: string): string =
var pos = 0
for c in msg:
result.add chr(((26... |
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 ... | #Objeck | Objeck |
bundle Default {
class VigenereCipher {
function : Main(args : String[]) ~ Nil {
key := "VIGENERECIPHER";
ori := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
enc := encrypt(ori, key);
IO.Console->Print("encrypt: ")->PrintLine(enc);
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 ... | #Wren | Wren | import "/dynamic" for Struct
import "random" for Random
var Stem = Struct.create("Stem", ["str", "next"])
var SDOWN = " |"
var SLAST = " `"
var SNONE = " "
var rand = Random.new()
var tree // recursive
tree = Fn.new { |root, head|
var col = Stem.new(null, null)
var tail = head
while (tail) {
... |
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 ... | #Rascal | Rascal | //usage example: To list just Rascal source files, Walk(|home:///workspace/|, ".rsc");
module Walk
import String;
import IO;
public void Walk(loc a, str pattern){
for (entry <- listEntries(a))
if (endsWith(entry, pattern))
println(entry);
elseif (isDirectory(a+entry))
Walk(a+entry, pattern);
} |
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 ... | #REALbasic | REALbasic | Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.