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/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 ██ ...
#Sidef
Sidef
func max_l(Array a, m = a[0]) { gather { a.each {|e| take(m = max(m, e)) } } }   func max_r(Array a) { max_l(a.flip).flip }   func water_collected(Array towers) { var levels = (max_l(towers) »min« max_r(towers)) (levels »-« towers).grep{ _ > 0 }.sum }   [ [ 1, 5, 3, 7, 2 ], [ 5, 3, 7, 2, 6, 4,...
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...
#BQN
BQN
Dot ← +´∘× Cross ← 1⊸⌽⊸×{1⌽𝔽˜-𝔽} Triple ← {𝕊a‿b‿c: a Dot b Cross c} VTriple ← Cross´   a←3‿4‿5 b←4‿3‿5 c←¯5‿¯12‿¯13
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...
#C
C
#include <stdio.h>   int check_isin(char *a) { int i, j, k, v, s[24];   j = 0; for(i = 0; i < 12; i++) { k = a[i]; if(k >= '0' && k <= '9') { if(i < 2) return 0; s[j++] = k - '0'; } else if(k >= 'A' && k <= 'Z') { if(i == 11) return 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 ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local const array integer: s is [] (1, 2, 2, 3, 4, 4, 5); var integer: i is 0; var integer: curr is 0; var integer: prev is 0; begin for i range 1 to length(s) do curr := s[i]; if i > 1 and curr = prev then writeln(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 ...
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On Option Explicit On   Imports System.IO   Module vMain   Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then ...
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...
#BBC_BASIC
BBC BASIC
@% = &20509 FOR base% = 2 TO 5 PRINT "Base " ; STR$(base%) ":" FOR number% = 0 TO 9 PRINT FNvdc(number%, base%); NEXT PRINT NEXT END   DEF FNvdc(n%, b%) LOCAL v, s% s% = 1 WHILE n% s% *= b% v += (n% MOD b%) / s% ...
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...
#bc
bc
/* * Return the _n_th term of the van der Corput sequence. * Uses the current _ibase_. */ define v(n) { auto c, r, s   s = scale scale = 0 /* to use integer division */   /* * c = count digits of n * r = reverse the digits of n */ for (0; n != 0; n /= 10) { c += 1 r = (10 * r) + (n % 10) }   /* mov...
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
#Apex
Apex
  // If not initialized at class/member level, it will be set to null Integer x = 0; Integer y; // y is null here Integer p,q,r; // declare multiple variables Integer i=1,j=2,k=3; // declare and initialize   /* * Similar to Integer, below variables can be initialized together separated by ','. */ String s = 'a string'...
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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program vanEckSerie.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a f...
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...
#Common_Lisp
Common Lisp
(defun trailing-zerop (number) "Is the lowest digit of `number' a 0" (zerop (rem number 10)))   (defun integer-digits (integer) "Return the number of digits of the `integer'" (assert (integerp integer)) (length (write-to-string integer)))   (defun paired-factors (number) "Return a list of pairs that are fac...
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...
#REXX
REXX
/*REXX program displays (and also tests/verifies) some numbers as octets. */ nums = x2d(200000) x2d(1fffff) 2097172 2097151 #=words(nums) say ' number hex octet original' say '══════════ ══════════ ══════════ ══════════' ok=1 do j=1 for #; @.j= word(nums,j) ...
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...
#Emacs_Lisp
Emacs Lisp
(defun my-print-args (&rest arg-list) (message "there are %d argument(s)" (length arg-list)) (dolist (arg arg-list) (message "arg is %S" arg)))   (my-print-args 1 2 3)
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...
#Erlang
Erlang
  print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#IDL
IDL
arr = intarr(3,4) print,size(arr) ;=> prints this: 2 3 4 2 12
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#J
J
some_variable =: 42 7!:5<'some_variable'
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Julia
Julia
julia> sizeof(Int8) 1   julia> t = 1 1   julia> sizeof(t) 8
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { /* sizes for variables of the primitive types (except Boolean which is JVM dependent) */ println("A Byte variable occupies: ${java.lang.Byte.SIZE / 8} byte") println("A Short variable occupies: ${java.lang.Short.SIZE / 8} bytes") println("An Int v...
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...
#MiniScript
MiniScript
vplus = function(v1, v2) return [v1[0]+v2[0],v1[1]+v2[1]] end function   vminus = function (v1, v2) return [v1[0]-v2[0],v1[1]-v2[1]] end function   vmult = function(v1, scalar) return [v1[0]*scalar, v1[1]*scalar] end function   vdiv = function(v1, scalar) return [v1[0]/scalar, v1[1]/scalar] end function...
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...
#Modula-2
Modula-2
MODULE Vector; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Vector = RECORD x,y : REAL; END;   PROCEDURE Add(a,b : Vector) : Vector; BEGIN RETURN Vector{a.x+b.x, a.y+b.y} END Add;   PROCEDURE Sub(a,b : Vector) : Vecto...
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 ...
#OCaml
OCaml
let cipher src key crypt = let str = String.uppercase src in let key = String.uppercase key in   (* strip out non-letters *) let len = String.length str in let rec aux i j = if j >= len then String.sub str 0 i else if str.[j] >= 'A' && str.[j] <= 'Z' then (str.[i] <- str.[j]; aux (succ i) (succ j)...
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 ...
#Yabasic
Yabasic
clear screen   dim colore$(1)   maxCol = token("white yellow cyan green red", colore$())   showTree(0, "[1[2[3][4[5][6]][7]][8[9]]]") print "\n\n\n" showTree(0, "[1[2[3[4]]][5[6][7[8][9]]]]")   sub showTree(n, A$) local i, c$ static co   c$ = left$(A$, 1)   if c$ = "" return   switch c$ case "["...
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 ...
#zkl
zkl
:Vault.dir() ... Compiler Asm Compiler Dictionary Exception Test UnitTester foo bar ...
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   ...
#Red
Red
Red []   walk: func [ "Walk a directory tree recursively, setting WORD to each file and evaluating BODY."   'word "For each file, set with the absolute file path." directory [file!] "Starting directory." body [block!] "Block to evaluate for each file, during which WORD is set." /w...
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   ...
#REXX
REXX
/*REXX program shows all files in a directory tree that match a given search criteria.*/ parse arg xdir; if xdir='' then xdir='\' /*Any DIR specified? Then use default.*/ @.=0 /*default result in case ADDRESS fails.*/ dirCmd= 'DIR /b /s' ...
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 ██ ...
#Swift
Swift
// Based on this answer from Stack Overflow: // https://stackoverflow.com/a/42821623   func waterCollected(_ heights: [Int]) -> Int { guard heights.count > 0 else { return 0 } var water = 0 var left = 0, right = heights.count - 1 var maxLeft = heights[left], maxRight = heights[right]   w...
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...
#C
C
#include<stdio.h>   typedef struct{ float i,j,k; }Vector;   Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};   float dotProduct(Vector a, Vector b) { return a.i*b.i+a.j*b.j+a.k*b.k; }   Vector crossProduct(Vector a,Vector b) { Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};   return 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...
#C.23
C#
using System; using System.Linq; using System.Text.RegularExpressions;   namespace ValidateIsin { public static class IsinValidator { public static bool IsValidIsin(string isin) => IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));   private static readonly Regex IsinRegex = ...
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 ...
#Vlang
Vlang
fn main() { s := [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 < s.len; i++ { curr := s[i] mut prev := 0 if i > 0 && curr == prev { println(i) } prev = cur...
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 ...
#Wren
Wren
var s = [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 null. for (i in 0...s.count) { var curr = s[i] var prev if (i > 0 && curr == prev) System.print(i) prev = curr }   // Now 'prev' is created only once and reassigned // each ...
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...
#BCPL
BCPL
get "libhdr"   let corput(n, base, num, denom) be $( let p = 0 and q = 1 until n=0 $( p := p * base + n rem base q := q * base n := n / base $)    !num := p  !denom := q   until p=0 $( n := p p := q rem p q := n $)    !num := !num / q  !denom := !de...
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...
#C
C
#include <stdio.h>   void vc(int n, int base, int *num, int *denom) { int p = 0, q = 1;   while (n) { p = p * base + (n % base); q *= base; n /= base; }   *num = p; *denom = q;   while (p) { n = p; p = q % p; q = n; } ...
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
#AppleScript
AppleScript
set x to 1
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program variable.s */   /************************************/ /* Constantes Définition */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*************************...
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 ...
#Arturo
Arturo
Max: 1000 a: array.of: Max 0   loop 0..Max-2 'n [ if 0 =< n-1 [ loop (n-1)..0 'm [ if a\[m]=a\[n] [ a\[n+1]: n-m break ] ] ] ]   print "The first ten terms of the Van Eck sequence are:" print first.n:10 a   print "" print "Terms 991 to 1000...
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 ...
#AWK
AWK
  # syntax: GAWK -f VAN_ECK_SEQUENCE.AWK # converted from Go BEGIN { limit = 1000 for (i=0; i<limit; i++) { arr[i] = 0 } for (n=0; n<limit-1; n++) { for (m=n-1; m>=0; m--) { if (arr[m] == arr[n]) { arr[n+1] = n - m break } } } printf("terms 1...
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...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   auto fangs(in long n) pure nothrow @safe { auto pairs = iota(2, cast(int)(n ^^ 0.5)) // n.isqrt .filter!(x => !(n % x)).map!(x => [x, n / x]); enum dLen = (in long x) => x.text.length; immutable half = dLen(n) / 2; en...
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...
#Ruby
Ruby
[0x200000, 0x1fffff].each do |i| # Encode i => BER ber = [i].pack("w") hex = ber.unpack("C*").collect {|c| "%02x" % c}.join(":") printf "%s => %s\n", i, hex   # Decode BER => j j = ber.unpack("w").first i == j or fail "BER not preserve integer" end
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Scala
Scala
object VlqCode { def encode(x:Long)={ val result=scala.collection.mutable.Stack[Byte]() result push (x&0x7f).toByte var l = x >>> 7 while(l>0){ result push ((l&0x7f)|0x80).toByte l >>>= 7 } result.toArray }   def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f)   d...
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...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function allargs () ... $ loop 1 to argn(); $ args(#), $ end $endfunction >allargs(1,3,"Test",1:2) 1 3 Test [ 1 2 ] >function args test (x) := {x,x^2,x^3} >allargs(test(4)) 4 16 64  
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...
#Euphoria
Euphoria
procedure print_args(sequence args) for i = 1 to length(args) do puts(1,args[i]) puts(1,' ') end for end procedure   print_args({"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
#Lasso
Lasso
local( mystring = 'Hello World', myarray = array('one', 'two', 3), myinteger = 1234 )   // size of a string will be a character count #mystring -> size '<br />'   // size of an array or map will be a count of elements #myarray -> size '<br />'   // elements within an array can report size #myarray -> get(2) -> size...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Lua
Lua
> s = "hello" > print(#s) 5 > t = { 1,2,3,4,5 } > print(#t) 5
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ByteCount["somerandomstring"]
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Modula-3
Modula-3
MODULE Size EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Int;   BEGIN Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n"); Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n"); END Size.
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...
#Nanoquery
Nanoquery
class Vector declare x declare y   def Vector(x, y) this.x = float(x) this.y = float(y) end   def operator+(other) return new(Vector, this.x + other.x, this.y + other.y) end   def operator-(other) ret...
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...
#Nim
Nim
import strformat   type Vec2[T: SomeNumber] = tuple[x, y: T]   proc initVec2[T](x, y: T): Vec2[T] = (x, y)   func`+`[T](a, b: Vec2[T]): Vec2[T] = (a.x + b.x, a.y + b.y)   func `-`[T](a, b: Vec2[T]): Vec2[T] = (a.x - b.x, a.y - b.y)   func `*`[T](a: Vec2[T]; m: T): Vec2[T] = (a.x * m, a.y * m)   func `/`[T](a: Vec2[T]; ...
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 ...
#ooRexx
ooRexx
/* Rexx */ Do alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' key = 'LEMON'   pt = 'Attack at dawn!' Call test key, pt   key = 'N' Call test key, pt   key = 'B' Call test key, pt   pt = alpha key = 'A' Call test key, pt   pt = sampledata() key = 'Hamlet; Prince of Denmark' Call test key, pt   Retur...
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 ...
#PHP
PHP
  <?php   function printTree( array $tree , string $key = "." , string $stack = "" , $first = TRUE , $firstPadding = NULL ) { if ( gettype($tree) == "array" ) { if($firstPadding === NULL) $firstPadding = ( count($tree)>1 ) ? "│ " : " " ; echo $key . PHP_EOL ; foreach ($tree as $ke...
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   ...
#Ring
Ring
  see "Testing DIR() " + nl mylist = dir("C:\Ring") for x in mylist if x[2] see "Directory : " + x[1] + nl else see "File : " + x[1] + nl ok next see "Files count : " + len(mylist)  
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   ...
#Ruby
Ruby
require 'find'   Find.find('/your/path') do |f| # print file and path to screen if filename ends in ".mp3" puts f if f.match(/\.mp3\Z/) end
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 ██ ...
#Tailspin
Tailspin
  templates histogramWater $ -> \( @: 0"1"; [$... -> { leftMax: $ -> #, value: ($)"1" } ] ! when <$@..> do @: $; $ ! otherwise $@ ! \) -> \( @: { rightMax: 0"1", sum: 0"1" }; $(last..1:-1)... -> # $@.sum ! when <{ value: <$@.rightMax..> }> do @.rightMax: $.value; when <{ value: <$.leftMa...
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...
#C.23
C#
using System; using System.Windows.Media.Media3D;   class VectorProducts { static double ScalarTripleProduct(Vector3D a, Vector3D b, Vector3D c) { return Vector3D.DotProduct(a, Vector3D.CrossProduct(b, c)); }   static Vector3D VectorTripleProduct(Vector3D a, Vector3D b, Vector3D 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...
#C.2B.2B
C++
    #include <string> #include <regex> #include <algorithm> #include <numeric> #include <sstream>   bool CheckFormat(const std::string& isin) { std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); std::smatch match; return std::regex_match(isin, match, isinRegEpx); }   std::string CodeISIN(const std::string& isin) ...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace VanDerCorput { /// <summary> /// Computes the Van der Corput sequence for any number base. /// The numbers in the sequence vary from zero to one, including zero but excluding one. /// The sequence possess...
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
#Arturo
Arturo
num: 10 str: "hello world"   arrA: [1 2 3] arrB: ["one" "two" "three"] arrC: [1 "two" [3 4 5]] arrD: ["one" true [ print "something" ]]   dict: [ name: "john" surname: "doe" function: $[][ print "do sth" ] ]   inspect symbols
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 ...
#BASIC
BASIC
10 DEFINT A-Z 20 DIM E(1000) 30 FOR I=0 TO 999 40 FOR J=I-1 TO 0 STEP -1 50 IF E(J)=E(I) THEN E(I+1)=I-J: GOTO 80 60 NEXT J 70 E(I+1)=0 80 NEXT I 90 FOR I=0 TO 9: PRINT E(I);: NEXT 95 PRINT 100 FOR I=990 TO 999: PRINT E(I);: NEXT
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 ...
#BCPL
BCPL
get "libhdr"   let start() be $( let eck = vec 999   for i = 0 to 999 do eck!i := 0 for i = 0 to 998 do for j = i-1 to 0 by -1 do if eck!i = eck!j then $( eck!(i+1) := i-j break $)   for i = 0 to 9 do writed(eck!i, 4) wrch('*N') for i = 9...
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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   fang_check (original, fang1, fang2: INTEGER_64): BOOLEAN -- Are 'fang1' and 'fang2' correct fangs of the 'original' number? require original_positive: original > 0 fangs_positive: fang1 > 0 and fang2 > 0 local original_length: INTEGER fang, ori: STRING...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func string: toSequence (in var bigInteger: number) is func result var string: sequence is ""; begin sequence := str(chr(ord(number mod 128_))); number >>:= 7; while number <> 0_ do sequence := str(chr(ord(number mod 128_) + 128)) & seq...
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...
#Sidef
Sidef
func vlq_encode(num) { var t = (0x7F & num) var str = t.chr while (num >>= 7) { t = (0x7F & num) str += chr(0x80 | t) } str.reverse }   func vlq_decode(str) { var num = '' str.each_byte { |b| num += ('%07b' % (b & 0x7F)) } Num(num, 2) }   var tests = [0, 0xa, ...
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...
#Factor
Factor
MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;
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...
#Forth
Forth
: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ; 4 3 2 1 4 sum . \ 10
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Nim
Nim
echo "An int contains ", sizeof(int), " bytes."
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#NS-HUBASIC
NS-HUBASIC
10 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
#OCaml
OCaml
(** The result is the size given in word. The word size in octet can be found with (Sys.word_size / 8). (The size of all the datas in OCaml is at least one word, even chars and bools.) *) let sizeof v = let rec rec_size d r = if List.memq r d then (1, d) else if not(Obj.is_block r) then (1, r::d) else ...
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...
#Objeck
Objeck
class Test { function : Main(args : String[]) ~ Nil { Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Sub(Vec2->New(2, 3))->ToString()->PrintLine(); Vec2->New(5, 7)->Mult(11)->ToString()->PrintLine(); Vec2->New(5, 7)->Div(2)->ToString()->PrintLine(); } }   class Vec2...
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 ...
#Pascal
Pascal
  // The Vigenere cipher in reasonably standard Pascal // <no library functions: all conversions hand-coded> PROGRAM Vigenere;   // get a letter's alphabetic position (A=0) FUNCTION letternum(letter: CHAR): BYTE; BEGIN letternum := (ord(letter)-ord('A')); END;   // convert a character to uppercase FUNCTION uch(ch: ...
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   ...
#Rust
Rust
#![feature(fs_walk)]   use std::fs; use std::path::Path;   fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
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   ...
#Scala
Scala
import java.io.File   object `package` { def walkTree(file: File): Iterable[File] = { val children = new Iterable[File] { def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty } Seq(file) ++: children.flatMap(walkTree(_)) } }   object Test extends App { val dir = new ...
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 ██ ...
#Tcl
Tcl
namespace path {::tcl::mathfunc ::tcl::mathop}   proc flood {ground} { set lefts [ set d 0 lmap g $ground { set d [max $d $g] } ] set ground [lreverse $ground] set rights [ set d 0 lmap g $ground { set d [max $d $g] } ] set ...
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...
#C.2B.2B
C++
#include <iostream>   template< class T > class D3Vector {   template< class U > friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ;   public : D3Vector( T a , T b , T c ) { x = a ; y = b ; z = c ; }   T dotproduct ( const D3Vector & rhs ) { T scalar = x * rhs....
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...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Utils.Check [ Abstract ] {   ClassMethod ISIN(x As %String) As %Boolean { // https://en.wikipedia.org/wiki/International_Securities_Identification_Number IF x'?2U9UN1N QUIT 0 SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1) FOR i=1:1 { SET n=$EXTRACT(x,i) IF n="" QUIT IF n'=+n SET $EXTRACT(x,i)=$CASE(n,"*":36,"@...
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...
#Clojure
Clojure
(defn luhn? [cc] (let [sum (->> cc (map #(Character/digit ^char % 10)) reverse (map * (cycle [1 2])) (map #(+ (quot % 10) (mod % 10))) (reduce +))] (zero? (mod sum 10))))   (defn is-valid-isin? [isin] (and (re-matches #"^[A-Z]{...
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...
#C.2B.2B
C++
#include <cmath> #include <iostream>   double vdc(int n, double base = 2) { double vdc = 0, denom = 1; while (n) { vdc += fmod(n, base) / (denom *= base); n /= base; // note: conversion from 'double' to 'int' } return vdc; }   int main() { for (double base = 2; base < 6; ++base)...
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Ada
Ada
with Ada.Text_IO;   with AWS.URL; with AWS.Parameters; with AWS.Containers.Tables;   procedure URL_Parser is   procedure Parse (URL : in String) is   use AWS.URL, Ada.Text_IO; use AWS.Containers.Tables;   procedure Put_Cond (Item  : in String; Value  : in String; ...
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#11l
11l
F url_encode(s) V r = ‘’ V buf = ‘’   F flush_buf() // this function is needed because strings in 11l are UTF-16 encoded I @buf != ‘’ V bytes = @buf.encode(‘utf-8’) L(b) bytes @r ‘’= ‘%’hex(b).zfill(2) @buf = ‘’   L(c) s I c C (‘0’..‘9’, ‘a’..‘z’, ‘A’..‘Z’,...
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
#AutoHotkey
AutoHotkey
x = hello ; assign verbatim as a string z := 3 + 4 ; assign an expression if !y ; uninitialized variables are assumed to be 0 or "" (blank string) Msgbox %x% ; variable dereferencing is done by surrounding '%' signs fx() { local x ; variable default scope in a function is local anyways global y ; ...
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
#AWK
AWK
BEGIN { # Variables are dynamically typecast, and do not need declaration prior to use: fruit = "banana" # create a variable, and fill it with a string a = 1 # create a variable, and fill it with a numeric value a = "apple" # re-use the above variable for a string print a, fruit   # M...
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 ...
#BQN
BQN
EckStep ← ⊢∾(⊑⊑∘⌽∊1↓⌽)◶(0˙)‿((⊑1+⊑⊐˜ 1↓⊢)⌽) Eck ← {(EckStep⍟(𝕩-1))⥊0} (Eck 10)≍990↓Eck 1000
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 ...
#C
C
#include <stdlib.h> #include <stdio.h>   int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } }   printf("Th...
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...
#Elixir
Elixir
defmodule Vampire do def factor_pairs(n) do first = trunc(n / :math.pow(10, div(char_len(n), 2))) last = :math.sqrt(n) |> round for i <- first .. last, rem(n, i) == 0, do: {i, div(n, i)} end   def vampire_factors(n) do if rem(char_len(n), 2) == 1 do [] else half = div(length(to_ch...
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...
#Factor
Factor
USING: combinators.short-circuit fry io kernel lists lists.lazy math math.combinatorics math.functions math.primes.factors math.statistics math.text.utils prettyprint sequences sets ; IN: rosetta-code.vampire-number   : digits ( n -- m ) log10 floor >integer 1 + ;   : same-digits? ( n n1 n2 -- ? ) [ 1 digit-gro...
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...
#Tcl
Tcl
package require Tcl 8.5   proc vlqEncode number { if {$number < 0} {error "negative not supported"} while 1 { lappend digits [expr {$number & 0x7f}] if {[set number [expr {$number >> 7}]] == 0} break } set out [format %c [lindex $digits 0]] foreach digit [lrange $digits 1 end] { set out [format %...
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...
#Fortran
Fortran
program varargs   integer, dimension(:), allocatable :: va integer :: i   ! using an array (vector) static call v_func() call v_func( (/ 100 /) ) call v_func( (/ 90, 20, 30 /) )   ! dynamically creating an array of 5 elements allocate(va(5)) va = (/ (i,i=1,5) /) call v_func(va) deallocate(va)   co...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Ol
Ol
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#ooRexx
ooRexx
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PARI.2FGP
PARI/GP
sizebyte(x)
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Pascal
Pascal
use Devel::Size qw(size total_size);   my $var = 9384752; my @arr = (1, 2, 3, 4, 5, 6); print size($var); # 24 print total_size(\@arr); # 256
http://rosettacode.org/wiki/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...
#OCaml
OCaml
module Vector = struct type t = { x : float; y : float } let make x y = { x; y } let add a b = { x = a.x +. b.x; y = a.y +. b.y } let sub a b = { x = a.x -. b.x; y = a.y -. b.y } let mul a n = { x = a.x *. n; y = a.y *. n } let div a n = { x = a.x /. n; y = a.y /. n }   let to_string {x; y...
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 ...
#Perl
Perl
if( @ARGV != 3 ){ printHelp(); }   # translate to upper-case, remove anything else map( (tr/a-z/A-Z/, s/[^A-Z]//g), @ARGV );   my $cipher_decipher = $ARGV[ 0 ];   if( $cipher_decipher !~ /ENC|DEC/ ){ printHelp(); # user should say what to do }   print "Key: " . (my $key = $ARGV[ 2 ]) . "\n";   if( $cipher_deciph...
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   ...
#Scheme
Scheme
(use posix) (use files) (use srfi-13)   (define (walk FN PATH) (for-each (lambda (ENTRY) (cond ((not (null? ENTRY))   (let ((MYPATH (make-pathname PATH ENTRY)))   (cond ((directory-exists? MYPATH) (walk FN MYPATH) ))   (FN MYPATH) )))) (directory PATH #t) ))   (walk (lambda (X) (cond ((stri...
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   ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i";   const proc: walkDir (in string: dirName, in string: extension) is func local var string: fileName is ""; var string: path is ""; begin for fileName range readDir(dirName) do path := dirName & "/" & fileName; if endsWith(path, extension) th...
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 ██ ...
#Visual_Basic_.NET
Visual Basic .NET
' Convert tower block data into a string representation, then manipulate that. Module Module1 Sub Main(Args() As String) Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers. Dim wta As Integer()() = { ' Water tower array (input data). N...
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...
#Ceylon
Ceylon
shared void run() {   alias Vector => Float[3];   function dot(Vector a, Vector b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];   function cross(Vector a, Vector b) => [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];   function scalarTriple(Vector a, Vector b, Vector 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...
#COBOL
COBOL
>>SOURCE FORMAT FREE *> this is gnucobol 2.0 identification division. program-id. callISINtest. data division. working-storage section. 01 ISINtest-result binary-int. procedure division. start-callISINtest. display 'should be valid ' with no advancing call 'ISINtest' using 'US0378331005' ISINtest-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...
#Clojure
Clojure
(defn van-der-corput "Get the nth element of the van der Corput sequence." ([n] ;; Default base = 2 (van-der-corput n 2)) ([n base] (let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal. ;; We essentially want to reverse the digits of n and put them after the ;; decimal po...
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#ALGOL_68
ALGOL 68
PR read "uriParser.a68" PR   PROC test uri parser = ( STRING uri )VOID: BEGIN URI result := parse uri( uri ); print( ( uri, ":", newline ) ); IF NOT ok OF result THEN # the parse failed # print( ( " ", error OF result, newline ) ) ELSE ...
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Action.21
Action!
BYTE FUNC MustEncode(CHAR c CHAR ARRAY ex) BYTE i   IF c>='a AND c<='z OR c>='A AND c<='Z OR c>='0 AND c<='9 THEN RETURN (0) FI IF ex(0)>0 THEN FOR i=1 TO ex(0) DO IF ex(i)=c THEN RETURN (0) FI OD FI RETURN (1)   PROC Append(CHAR ARRAY s CHAR c) s(0)==+1 s(s(0))=c RETUR...
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Ada
Ada
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Encode is Normal : constant String := "http://foo bar/"; begin Put_Line (AWS.URL.Encode (Normal)); end Encode;
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
#Axe
Axe
1→A