task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#BASIC
BASIC
10 LET A=1.3 20 LET B%=1.3: REM The sigil indicates an integer, so this will be rounded down 30 LET C$="0121": REM The sigil indicates a string data type. the leading zero is not truncated 40 DIM D(10): REM Create an array of 10 digits 50 DIM E$(5.10): REM Create an array of 5 strings, with a maximu...
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.23
C#
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(st...
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...
#FreeBASIC
FreeBASIC
'Vampire numbers. 'FreeBASIC version 24. Windows 'Vampire.bas Function WithinString(n As Ulongint,f As Ulongint) As Integer var m=Str(n),p=Str(f) For z As Integer=0 To Len(p)-1 var i=Instr(m,Chr(p[z])) If i Then m=Mid(m,1,i-1)+Mid(m,i+1) Else Return 0 End ...
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...
#TXR
TXR
1> (carray-num #x200000) #<carray 3 #<ffi-type uchar>> 2> (carray-get *1) #(32 0 0) 3> (carray-num #x1FFFFF) #<carray 3 #<ffi-type uchar>> 4> (carray-get *3) #(31 255 255) 5> (num-carray *1) 2097152 6> (num-carray *3) 2097151
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function   Function FromVlq(v As ULong) As ULong ...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Free_Pascal
Free Pascal
program variadicRoutinesDemo(input, output, stdErr); {$mode objFPC}   // array of const is only supported in $mode objFPC or $mode Delphi procedure writeLines(const arguments: array of const); var argument: TVarRec; begin // inside the body `array of const` is equivalent to `array of TVarRec` for argument in argumen...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#F.C5.8Drmul.C3.A6
Fōrmulæ
void local fn Function1( count as long, ... ) va_list ap long value   va_start( ap, count ) while ( count ) value = fn va_argLong( ap ) printf @"%ld",value count-- wend   va_end( ap ) end fn   void local fn Function2( obj as CFTypeRef, ... ) va_list ap   va_start( ap, obj ) while ( obj ) ...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Perl
Perl
use Devel::Size qw(size total_size);   my $var = 9384752; my @arr = (1, 2, 3, 4, 5, 6); print size($var); # 24 print total_size(\@arr); # 256
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Phix
Phix
printf(1,"An integer contains %d bytes.\n", machine_word())
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PicoLisp
PicoLisp
  put skip list (SIZE(x)); /* gives the number of bytes occupied by X */ /* whatever data type or structure it is. */   put skip list (CURRENTSIZE(x)); /* gives the current number of bytes of X */ /* actually used by such things as a */ ...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PL.2FI
PL/I
  put skip list (SIZE(x)); /* gives the number of bytes occupied by X */ /* whatever data type or structure it is. */   put skip list (CURRENTSIZE(x)); /* gives the current number of bytes of X */ /* actually used by such things as a */ ...
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...
#Ol
Ol
  (define :+ +) (define (+ a b) (if (vector? a) (if (vector? b) (vector-map :+ a b) (error "error:" "not applicable (+ vector non-vector)")) (if (vector? b) (error "error:" "not applicable (+ non-vector vector)") (:+ a b))))   (define :- -) (define (- a b) (if (vect...
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 ...
#Phix
Phix
with javascript_semantics constant ENCRYPT = +1, DECRYPT = -1 function Vigenere(string s, key, integer mode) string res = "" integer k = 1, ch s = upper(s) for i=1 to length(s) do ch = s[i] if ch>='A' and ch<='Z' then res &= 'A'+mod(ch+mode*(key[k]+26),26) ...
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   ...
#Sidef
Sidef
func traverse(Block callback, Dir dir) { dir.open(\var dir_h) || return nil   dir_h.entries.each { |entry| if (entry.is_a(Dir)) { traverse(callback, entry) } else { callback(entry) } } }   var dir = Dir.cwd var pattern = /foo/ # display files that contain 'f...
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Smalltalk
Smalltalk
Directory extend [ wholeContent: aPattern do: twoBlock [ self wholeContent: aPattern withLevel: 0 do: twoBlock. ] wholeContent: aPattern withLevel: l do: twoBlock [ |cont| cont := (self contents) asSortedCollection. cont remove: '.'; remove: '..'. cont do: [ :n | |fn ps| ps := (Dire...
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 ██ ...
#Wren
Wren
import "/math" for Math, Nums import "/fmt" for Fmt   var waterCollected = Fn.new { |tower| var n = tower.count var highLeft = [0] + (1...n).map { |i| Nums.max(tower[0...i]) }.toList var highRight = (1...n).map { |i| Nums.max(tower[i...n]) }.toList + [0] var t = (0...n).map { |i| Math.max(Math.min(highL...
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...
#Clojure
Clojure
(defrecord Vector [x y z])   (defn dot [U V] (+ (* (:x U) (:x V)) (* (:y U) (:y V)) (* (:z U) (:z V))))   (defn cross [U V] (new Vector (- (* (:y U) (:z V)) (* (:z U) (:y V))) (- (* (:z U) (:x V)) (* (:x U) (:z V))) (- (* (:x U) (:y V)) (* (:y U) (:x V)))))   (let [a (new Vector 3...
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...
#Common_Lisp
Common Lisp
(defun alphap (char) (char<= #\A char #\Z))   (defun alpha-digit-char-p (char) (or (alphap char) (digit-char-p char)))   (defun valid-isin-format-p (isin) (and (= (length isin) 12) (alphap (char isin 0)) (alphap (char isin 1)) (loop for i from 2 to 10 always (alpha-digit-char-p (...
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...
#CLU
CLU
vc = proc (n, base: int) returns (int, int) p: int := 0 q: int := 1 while n ~= 0 do p := p * base + n // base q := q * base n := n / base end num: int := p denom: int := q while p ~= 0 do p, q := q // p, p end return(num/q, denom/q) end vc   print_fra...
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...
#Common_Lisp
Common Lisp
(defun van-der-Corput (n base) (loop for d = 1 then (* d base) while (<= d n) finally (return (/ (parse-integer (reverse (write-to-string n :base base)) :radix base) d))))   (loop for base from 2 to 5 do (format t "Base ~a: ~{~6a~^~}~%" base (loop for i to 10 collect (van-der-Corput ...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#11l
11l
F url_decode(s) V r = ‘’ V i = 0 L i < s.len I s[i] == ‘%’ [Byte] b L i < s.len & s[i] == ‘%’ i++ b.append(Int(s[i.+2], radix' 16)) i += 2 r ‘’= b.decode(‘utf-8’) E r ‘’= s[i] i++ R r   print(url_decode(‘http%3A%2F%...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#11l
11l
V string = input(‘Input a string: ’) V number = Float(input(‘Input a number: ’))
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation"   on parseURLString(URLString) set output to {URLString} set indent to tab & "• " set componentsObject to current application's class "NSURLComponents"'s componentsWithString:(URLString) repeat with thisKey in {"s...
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...
#ALGOL_68
ALGOL 68
BEGIN # encodes the specified url - 0-9, A-Z and a-z are unchanged, # # everything else is converted to %xx where xx are hex-digits # PROC encode url = ( STRING url )STRING: IF url = "" THEN "" # empty string # ELSE # non-e...
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Batch_File
Batch File
  @echo off ::setting variables in defferent ways set myInt1=5 set myString1=Rosetta Code set "myInt2=5" set "myString2=Rosetta Code" ::Arithmetic set /a myInt1=%myInt1%+1 set /a myInt2+=1 set /a myInt3=myInt2+ 5   set myInt set myString pause>nul  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#BBC_BASIC
BBC BASIC
REM BBC BASIC (for Windows) has the following scalar variable types; REM the type is explicitly indicated by means of a suffix character. REM Variable names must start with A-Z, a-z, _ or `, and may contain REM any of those characters plus 0-9 and @; they are case-sensitive.   A& = 123 ...
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.2B.2B
C++
#include <iostream> #include <map>   class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; +...
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...
#Go
Go
package main   import ( "fmt" "math" )   func max(a, b uint64) uint64 { if a > b { return a } return b }   func min(a, b uint64) uint64 { if a < b { return a } return b }   func ndigits(x uint64) (n int) { for ; x > 0; x /= 10 { n++ } return }   f...
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...
#Wren
Wren
import "/fmt" for Fmt, Conv import "/str" for Str   var toOctets = Fn.new { |n| var s = Conv.itoa(n, 2) var le = s.count var r = le % 7 var d = (le/7).floor if (r > 0) { d = d + 1 s = Fmt.zfill(7 * d, s) } var chunks = Str.chunks(s, 7) var last = "0" + chunks[-1] s = ...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#FutureBasic
FutureBasic
void local fn Function1( count as long, ... ) va_list ap long value   va_start( ap, count ) while ( count ) value = fn va_argLong( ap ) printf @"%ld",value count-- wend   va_end( ap ) end fn   void local fn Function2( obj as CFTypeRef, ... ) va_list ap   va_start( ap, obj ) while ( obj ) ...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Go
Go
func printAll(things ... string) { // it's as if you declared "things" as a []string, containing all the arguments for _, x := range things { fmt.Println(x) } }
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Pop11
Pop11
;;; Prints 0 because small integers need no heap storage datasize(12) => ;;; Prints 3: 3 character fits into single machine word, 1 word ;;; for tag, 1 for length datasize('str') => ;;; 3 element vector takes 5 words: 3 for values, 1 for tag, 1 for ;;; length datasize({1 2 3}) => ;;; Prints 3 because only first node co...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#PureBasic
PureBasic
Define a Debug SizeOf(a) ; This also works for structured variables
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Python
Python
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a, '\tSize =', a.buffer_info()[1] * a.itemsize del a     array('l') Size = 0 array(...
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...
#ooRexx
ooRexx
v=.vector~new(12,-3); Say "v=.vector~new(12,-3) =>" v~print v~ab(1,1,6,4); Say "v~ab(1,1,6,4) =>" v~print v~al(45,2); Say "v~al(45,2) =>" v~print w=v~'+'(v); Say "w=v~'+'(v) =>" w~print x=v~'-'(w); Say "x=v~'-'(w) =>" x~print y=x~'*'(3); ...
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 ...
#PHP
PHP
<?php   $str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; $key = "VIGENERECIPHER";   printf("Text: %s\n", $str); printf("key: %s\n", $key);   $cod = encipher($str, $key, true); printf("Code: %s\n", $cod); $dec = encipher($cod, $key, false); printf("Back: %s\n", $dec);   function enciph...
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   ...
#Swift
Swift
import Foundation   let fileSystem = FileManager.default let rootPath = "/"   // Enumerate the directory tree (which likely recurses internally)...   if let fsTree = fileSystem.enumerator(atPath: rootPath) {   while let fsNodeName = fsTree.nextObject() as? NSString {   let fullPath = "\(rootPath)/\(fsNodeNa...
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   ...
#Tcl
Tcl
  package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}...
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 ██ ...
#XPL0
XPL0
func WaterCollected(Array, Width); \Return amount of water collected int Array, Width, Height, I, Row, Col, Left, Right, Water; [Water:= 0; Height:= 0; for I:= 0 to Width-1 do \find max height if Array(I) > Height then Height:= Array(I); for Row:= 2 to Height do for Col:= 1 to Wid...
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...
#CLU
CLU
vector = cluster [T: type] is make, dot_product, cross_product, equal, power, mul, unparse where T has add: proctype (T,T) returns (T) signals (overflow), sub: proctype (T,T) returns (T) signals (overflow), mul: proctype (T,T) returns (T)...
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...
#D
D
import std.stdio;   void main() { auto isins = [ "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040", ]; foreach (isin; isins) { writeln(isin, " is ", ISINvalidate(isin) ? "valid" : "n...
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...
#Cowgol
Cowgol
include "cowgol.coh";   sub vc(n: uint16, base: uint16): (num: uint16, denom: uint16) is var p: uint16 := 0; var q: uint16 := 1;   while n != 0 loop p := p * base + n % base; q := q * base; n := n / base; end loop;   num := p; denom := q;   while p != 0 loop n...
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...
#D
D
double vdc(int n, in double base=2.0) pure nothrow @safe @nogc { double vdc = 0.0, denom = 1.0; while (n) { denom *= base; vdc += (n % base) / denom; n /= base; } return vdc; }   void main() { import std.stdio, std.algorithm, std.range;   foreach (immutable b; 2 .. 6) ...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#ABAP
ABAP
REPORT Z_DECODE_URL.   DATA: lv_encoded_url TYPE string VALUE 'http%3A%2F%2Ffoo%20bar%2F', lv_decoded_url TYPE string.   CALL METHOD CL_HTTP_UTILITY=>UNESCAPE_URL EXPORTING ESCAPED = lv_encoded_url RECEIVING UNESCAPED = lv_decoded_url.   WRITE: 'Encoded URL: ', lv_encoded_url, /, 'Decoded URL: ', lv...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Action.21
Action!
PROC Append(CHAR ARRAY s CHAR c) s(0)==+1 s(s(0))=c RETURN   CHAR FUNC GetCharFromHex(CHAR c1,c2) CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F] BYTE i,res   res=0 FOR i=0 TO 15 DO IF c1=hex(i) THEN res==+i LSH 4 FI IF c2=hex(i) THEN res==+i FI OD RETURN (res)   PROC Decode(CHA...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#AArch64_Assembly
AArch64 Assembly
  //Consts .equ BUFFERSIZE, 100 .equ STDIN, 0 // linux input console .equ STDOUT, 1 // linux output console .equ READ, 63 .equ WRITE, 64 .equ EXIT, 93   .data enterText: .asciz "Enter text: " carriageReturn: .asciz "\n"   //Read Buffer .bss buffer: .skip BUFFERSIZE   ....
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   PROC Main() CHAR ARRAY sUser(255) REAL r75000,rUser   Put(125) PutE() ;clear the screen ValR("75000",r75000)   Print("Please enter a text: ") InputS(sUser)   DO Print("Please enter number ") PrintR(r75000) Print(": ") InputR(rUser) UNTIL RealEqual(rUser,r75000) ...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#11l
11l
F unicode_code(ch) R ‘U+’hex(ch.code).zfill(4)   F utf8hex(ch) R ch.encode(‘utf-8’).map(c -> hex(c)).join(‘ ’)   print(‘#<11 #<15 #<15’.format(‘Character’, ‘Unicode’, ‘UTF-8 encoding (hex)’)) V chars = [‘A’, ‘ö’, ‘Ж’, ‘€’] L(char) chars print(‘#<11 #<15 #<15’.format(char, unicode_code(char), utf8hex(char)))
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Ada
Ada
with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings;   package Exported is function Query (Data : chars_ptr; Size : access size_t) return int; pragma Export (C, Query, "Query"); end Exported;
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#C.23
C#
using System;   namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: ...
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...
#Apex
Apex
EncodingUtil.urlEncode('http://foo bar/', 'UTF-8')
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#AppleScript
AppleScript
AST URL encode "http://foo bar/"
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Boo
Boo
a ← 10
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#BQN
BQN
a ← 10
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Clojure
Clojure
(defn van-eck ([] (van-eck 0 0 {})) ([val n seen] (lazy-seq (cons val (let [next (- n (get seen val n))] (van-eck next (inc n) (assoc seen val n)))))))   (println "First 10 terms:" (take 10 (van-eck))) (println "Terms 991 to 1000 terms:" (take 1...
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 ...
#CLU
CLU
% Generate the first N elements of the Van Eck sequence eck = proc (n: int) returns (array[int]) ai = array[int] e: ai := ai$fill(0, n, 0)   for i: int in int$from_to(ai$low(e), ai$high(e)-1) do for j: int in int$from_to_by(i-1, ai$low(e), -1) do if e[i] = e[j] then e[i+...
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...
#Haskell
Haskell
import Data.List (sort) import Control.Arrow ((&&&))   -- VAMPIRE NUMBERS ------------------------------------------------------------ vampires :: [Int] vampires = filter (not . null . fangs) [1 ..]   fangs :: Int -> [(Int, Int)] fangs n | odd w = [] | otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors ...
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...
#XPL0
XPL0
func OctIn(Dev); \Input from device value of sequence of octets int Dev, N, Oct; [N:= 0; repeat Oct:= HexIn(Dev); N:= N<<7 + (Oct&$7F); until (Oct&$80) = 0; return N; ];   proc OctOut(Dev, Num, Lev); \Output value to device as sequence of octets int Dev, Num, Lev, Rem; [Rem:= Num & $7F; ...
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...
#zkl
zkl
fcn to_seq(x){ //--> list of ints z:=(x.log2()/7); (0).pump(z+1,List,'wrap(j){ x.shiftRight((z-j)*7).bitAnd(0x7f).bitOr((j!=z) and 0x80 or 0) }); }   fcn from_seq(in){ in.reduce(fcn(p,n){ p.shiftLeft(7).bitOr(n.bitAnd(0x7f)) },0) }
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Golo
Golo
#!/usr/bin/env golosh ---- This module demonstrates variadic functions. ---- module Variadic   import gololang.Functions   ---- Varargs have the three dots after them just like Java. ---- function varargsFunc = |args...| { foreach arg in args { println(arg) } }   function main = |args| {   varargsFunc(1, 2, 3...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Groovy
Groovy
def printAll( Object[] args) { args.each{ arg -> println arg } }   printAll(1, 2, "three", ["3", "4"])
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#R
R
# Results are system dependent num <- c(1, 3, 6, 10) object.size(num) # e.g. 56 bytes   #Allocating vectors using ':' results in less memory being (reportedly) used num2 <- 1:4 object.size(num2) # e.g. 40 bytes   #Memory shared by objects isn't always counted l <- list(a=c(1, 3, 6, 10), b=1:4) object.size(l) # e.g....
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Racket
Racket
  #lang racket (require ffi/unsafe) (define-syntax-rule (sizes t ...) (begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...)) (sizes _byte _short _int _long _llong _float _double)  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Raku
Raku
# Textual strings are measured in characters (graphemes) my $string = "abc";   # Arrays are measured in elements. say $string.chars; # 3 my @array = 1..5; say @array.elems; # 5   # Buffers may be viewed either as a byte-string or as an array of elements. my $buffer = '#56997; means "four dragons".'.encode('utf...
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...
#Perl
Perl
package Vector; use Moose; use feature 'say';   use overload '+' => \&add, '-' => \&sub, '*' => \&mul, '/' => \&div, '""' => \&stringify;   has 'x' => (is =>'rw', isa => 'Num', required => 1); has 'y' => (is =>'rw', isa => 'Num', required => 1);   sub add { my($a, $...
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 ...
#PicoLisp
PicoLisp
(de vigenereKey (Str) (extract '((C) (when (>= "Z" (uppc C) "A") (- (char (uppc C)) 65) ) ) (chop Str) ) )   (de vigenereEncrypt (Str Key) (pack (mapcar '((C K) (char (+ 65 (% (+ C K) 26))) ) (vigenereKey Str) (apply circ (vigenereKey K...
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 ...
#PL.2FI
PL/I
  cypher: procedure options (main); /* 21 September 2012 */ declare t(26) character (26); declare (i, j, k, L) fixed binary; declare (original, encoded, coder) character (1000) varying initial (''); declare cypher character (30) varying; declare (co, ct, cc) character (1);   /* Set up cypher tabl...
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   ...
#TXR
TXR
(build (ftw "." (lambda (path type stat level base) (if (ends-with ".tl" path) (add path)))))
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#UNIX_Shell
UNIX Shell
find . -name '*.txt' -type f
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ...
#Yabasic
Yabasic
data 7 data "1,5,3,7,2", "5,3,7,2,6,4,5,9,1,2", "2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1" data "5,5,5,5", "5,6,7,8", "8,7,7,6", "6,7,10,7,6"   read n   for i = 1 to n read n$ wcbt(n$) next i   sub wcbt(s$) local tower$(1), hr(1), hl(1), n, i, ans, k   n = token(s$, tower$(), ",")   redim hr(n) redim hl(n) for i = n to 1...
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...
#Common_Lisp
Common Lisp
(defclass 3d-vector () ((x :type number :initarg :x) (y :type number :initarg :y) (z :type number :initarg :z)))   (defmethod print-object ((object 3d-vector) stream) (print-unreadable-object (object stream :type t) (with-slots (x y z) object (format stream "~a ~a ~a" x y z))))   (defun make-3d-vect...
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...
#Elixir
Elixir
isin? = fn str -> if str =~ ~r/\A[A-Z]{2}[A-Z0-9]{9}\d\z/ do String.codepoints(str) |> Enum.map_join(&String.to_integer(&1, 36)) |> Luhn.valid? else false end end   IO.puts " ISIN Valid?" ~w(US0378331005 US0373831005 U...
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...
#Factor
Factor
USING: combinators.short-circuit.smart formatting kernel luhn math math.parser qw sequences strings unicode ; IN: rosetta-code.isin   CONSTANT: test-cases qw{ US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 FR0000988040 }   : valid-length? ( str -- ? ) length 12 = ;   : valid-coun...
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...
#EasyLang
EasyLang
func vdc b n . v . s = 1 v = 0 while n > 0 s *= b m = n mod b v += m / s n = n div b . . for b = 2 to 5 write "base " & b & ":" for n range 10 call vdc b n v write " " & v . print "" .
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#EDSAC_order_code
EDSAC order code
  [Van der Corput sequence for Rosetta Code. EDSAC solution, Initial Orders 2.]   [Library subroutine M3 - prints header at load time and is then overwritten. Here, the last character sets the teleprinter to figures.] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF *VAN!DER!CORPUT!SEQUENCE@&#17A*BIT!!!#35A*BIT...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Ada
Ada
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Decode is Encoded : constant String := "http%3A%2F%2Ffoo%20bar%2F"; begin Put_Line (AWS.URL.Decode (Encoded)); end Decode;  
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#ALGOL_68
ALGOL 68
# returns c decoded as a hex digit # PROC hex value = ( CHAR c )INT: IF c >= "0" AND c <= "9" THEN ABS c - ABS "0" ELIF c >= "A" AND c <= "F" THEN 10 + ( ABS c - ABS "A" ) ELSE 10 + ( ABS c - ABS "a" ) ...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Ada
Ada
function Get_String return String is Line : String (1 .. 1_000); Last : Natural; begin Get_Line (Line, Last); return Line (1 .. Last); end Get_String;   function Get_Integer return Integer is S : constant String := Get_String; begin return Integer'Value (S); -- may raise exception Constraint_Error if val...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#ALGOL_68
ALGOL 68
print("Enter a string: "); STRING s := read string; print("Enter a number: "); INT i := read int; ~
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#8th
8th
  hex \ so bytes print nicely   [ "\u0041", "\u00F6", "\u0416", "\u20AC" ] \ add the 0x1D11E one; the '\u' string notation requires four hex digits "" 1D11E s:+ a:push   \ for each test, print it out and its bytes: ( dup . space b:new ( . space drop ) b:each cr ) a:each! drop   cr \ now the invers...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Action.21
Action!
TYPE Unicode=[BYTE bc1,bc2,bc3] BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]   BYTE FUNC DecodeHex(CHAR c) BYTE i   FOR i=0 TO 15 DO IF c=hex(i) THEN RETURN (i) FI OD Break() RETURN (255)   BYTE FUNC DecodeHex2(CHAR c1,c2) BYTE h1,h2,res   h1=DecodeHex(c1) h2=DecodeHex(...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#AutoHotkey
AutoHotkey
; Example: The following is a working script that displays a summary of all top-level windows.   ; For performance and memory conservation, call RegisterCallback() only once for a given callback: if not EnumAddress ; Fast-mode is okay because it will be called only from this thread: EnumAddress := RegisterCallback...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#C
C
#if 0 I rewrote the driver according to good sense, my style, and discussion.   This is file main.c on Autumn 2011 ubuntu linux release. The emacs compile command output:   -*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Mon Mar 12 20:25:27   make -k CFLAGS=-Wall main.o cc -Wall -c -o mai...
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...
#Crystal
Crystal
require "uri"   examples = ["foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header...
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...
#Elixir
Elixir
test_cases = [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&ob...
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...
#Arturo
Arturo
encoded: encode.url.slashes "http://foo bar/" print encoded
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#AutoHotkey
AutoHotkey
MsgBox, % UriEncode("http://foo bar/")   ; Modified from http://goo.gl/0a0iJq UriEncode(Uri) { VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0) StrPut(Uri, &Var, "UTF-8") f := A_FormatInteger SetFormat, IntegerFast, H While Code := NumGet(Var, A_Index - 1, "UChar") If (Code >= 0x30 && Code <= 0x39 ; 0-9 || Code >...
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Bracmat
Bracmat
(myfunc=i j.!arg:(?i.?j)&!i+!j)
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. VAN-ECK.   DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATION. 02 ECK PIC 999 OCCURS 1000 TIMES. 02 I PIC 9999. 02 J PIC 9999. 01 OUTPUT-FORMAT. 02 ITEM PIC ZZ9...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() write("First 25 vampire numbers and their fangs:") every fangs := vampire(n := seq())\25 do write(right(n,20),":",fangs) write("\nOther numbers:") every n := 16758243290880 | 24959017348650 | 14593825548650 do write(right(n,20),": ",vampire(n)|"toothless") end   procedure vampir...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Haskell
Haskell
class PrintAllType t where process :: [String] -> t   instance PrintAllType (IO a) where process args = do mapM_ putStrLn args return undefined   instance (Show a, PrintAllType r) => PrintAllType (a -> r) where process args = \a -> process (args ++ [show a])   printAll :: (PrintAllType...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Icon_and_Unicon
Icon and Unicon
procedure main () varargs("some", "extra", "args") write() varargs ! ["a","b","c","d"] end   procedure varargs(args[]) every write(!args) end
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#REXX
REXX
/*REXX program demonstrates (see the penultimate statement) how to */ /* to find the size (length) of the value of a REXX variable. */   /*REXX doesn't reserve any storage for any variables, as all variables */ /*are stored as character strings, including boolean. Storage is */ /*obtained as nece...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Ring
Ring
  list1 = list(2) list2 = list(4) list3 = list(6) list4 = list(7) list5 = list(5)   see "Size of list1 is : " + len(list1) + nl see "Size of list2 is : " + len(list2) + nl see "Size of list3 is : " + len(list3) + nl see "Size of list4 is : " + len(list4) + nl see "Size of list5 is : " + len(list5) + nl  
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Ruby
Ruby
  require 'objspace'   p ObjectSpace.memsize_of("a"*23) #=> 0 p ObjectSpace.memsize_of("a"*24) #=> 25 p ObjectSpace.memsize_of("a"*1000) #=> 1001  
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Phix
Phix
constant a = {5,7}, b = {2, 3} ?sq_add(a,b) ?sq_sub(a,b) ?sq_mul(a,11) ?sq_div(a,2)
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def add + enddef def sub - enddef def mul * enddef def div / enddef   def opVect /# a b op -- a b c #/ var op list? not if swap len rot swap repeat endif len var lon   ( lon 1 -1 ) for var i i get rot i get rot op exec >ps swap endfor   lon for drop ps>...
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 ...
#PowerShell
PowerShell
# Author: D. Cudnohufsky function Get-VigenereCipher { Param ( [Parameter(Mandatory=$true)] [string] $Text,   [Parameter(Mandatory=$true)] [string] $Key,   [switch] $Decode )   begin { $map = [char]'A'..[char]'Z' }   process { $...
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   ...
#UnixPipes
UnixPipes
find . -type f | egrep '\.txt$|\.TXT$'
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Visual_Basic_.NET
Visual Basic .NET
Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String) For Each file In directory.GetFiles(pattern) Console.WriteLine(file.FullName) Next For Each subDir In directory.GetDirectories walkTree(subDir, pattern) Next End Sub