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
#Fortran
Fortran
program test implicit none   integer :: i !scalar integer integer,dimension(10) :: ivec !integer vector real :: r !scalar real real,dimension(10) :: rvec !real vector character(len=:),allocatable :: char1, char2 !fortran 2003 allocatable strings   !assignments:   !-- scalars: i = 1 r = 3.14   !-- vectors: ...
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 ...
#Nim
Nim
const max = 1000 var a: array[max, int] for n in countup(0, max - 2): for m in countdown(n - 1, 0): if a[m] == a[n]: a[n + 1] = n - m break   echo "The first ten terms of the Van Eck sequence are:" echo a[..9] echo "\nTerms 991 to 1000 of the sequence are:" echo a[990..^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 ...
#Pascal
Pascal
program VanEck; { * 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 previousely.} uses sysutils; const MAXNUM = 32381775;//1000*1000...
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...
#Rust
Rust
use std::cmp::{max, min};   static TENS: [u64; 20] = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 100000...
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...
#Scala
Scala
import Stream._ import math._ import scala.collection.mutable.ListBuffer   object VampireNumbers extends App { val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}   val sexp = from(1, 2) // stream of integer: 1,3,5,7, ... val rs: Stream[Int] => Stream...
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...
#Perl
Perl
sub print_all { foreach (@_) { print "$_\n"; } }
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...
#Phix
Phix
procedure print_args(sequence args) for i=1 to length(args) do ?args[i] end for end procedure print_args({"Mary", "had", "a", "little", "lamb"})
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 ...
#Vedit_macro_language
Vedit macro language
Get_Input(10, "Key: ", STATLINE+NOCR) // @10 = key Reg_Copy_Block(11, Cur_Pos, EOL_Pos) // @11 = copy of original text EOL Ins_Newline Ins_Text("Key = ") Reg_Ins(10) Ins_Newline   // Prepare the key into numeric registers #130..: Buf_Switch(Buf_Free) Reg_Ins(10) Case_Upper_Block(0, Cur_Pos) BOF #2 = Reg_Size(10) /...
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...
#FreeBASIC
FreeBASIC
'Construct only required operators for this. Type V3 As double x,y,z declare operator cast() as string End Type #define dot * #define cross ^ #define Show(t1,t) ? #t1;tab(22);t   operator V3.cast() as string return "("+str(x)+","+str(y)+","+str(z)+")" end operator   Operator dot(v1 As v3,v2 As v3) As double ...
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...
#Python
Python
def check_isin(a): if len(a) != 12 or not all(c.isalpha() for c in a[:2]) or not all(c.isalnum() for c in a[2:]): return False s = "".join(str(int(c, 36)) for c in a) return 0 == (sum(sum(divmod(2 * (ord(c) - 48), 10)) for c in s[-2::-2]) + sum(ord(c) - 48 for c in s[::-2])) % 10   ...
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...
#Nim
Nim
import rationals, strutils, sugar   type Fract = Rational[int]   proc corput(n: int; base: Positive): Fract = result = 0.toRational var b = 1 // base var n = n while n != 0: result += n mod base * b n = n div base b /= base   for base in 2..5: let list = collect(newSeq, for n in 1..10: corput(n, b...
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...
#PARI.2FGP
PARI/GP
VdC(n)=n=binary(n);sum(i=1,#n,if(n[i],1.>>(#n+1-i))); VdC(n)=sum(i=1,#binary(n),if(bittest(n,i-1),1.>>i)); \\ Alternate approach vector(10,n,VdC(n))
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...
#Groovy
Groovy
assert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http://foo bar/'
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...
#Haskell
Haskell
import qualified Data.Char as Char   urlDecode :: String -> Maybe String urlDecode [] = Just [] urlDecode ('%':xs) = case xs of (a:b:xss) -> urlDecode xss >>= return . ((Char.chr . read $ "0x" ++ [a,b]) :) _ -> Nothing urlDecode ('+':xs) = urlDecode xs >>= return . (' ' :) urlDecode (x:xs) = urlDe...
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#Factor
Factor
USING: combinators combinators.short-circuit formatting grouping kernel locals math math.functions math.vectors sequences sequences.repeating unicode ;   CONSTANT: numbers { " ## #" " ## #" " # ##" " #### #" " # ##" " ## #" " # ####" " ### ##" " ## ###" " # ##" }   : ...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Julia
Julia
function cleansyntax(line) line = strip(line) if line == "" return "#=blank line=#" elseif line[1] == '#' return line elseif line[1] == ';' line = replace(line, r"^;[;]+" => ";") else # active option o, p = splitline(line) line = p == nothing ? uppercase(o) : ...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Kotlin
Kotlin
// version 1.2.0   import java.io.File   class ConfigData( val favouriteFruit: String, val needsPeeling: Boolean, val seedsRemoved: Boolean, val numberOfBananas: Int, val numberOfStrawberries: Int )   fun updateConfigFile(fileName: String, cData: ConfigData) { val inp = File(fileName) val li...
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
#Erlang
Erlang
{ok, [String]} = io:fread("Enter a string: ","~s"). {ok, [Number]} = io:fread("Enter a number: ","~d").
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
#Euphoria
Euphoria
include get.e   sequence s atom n   s = prompt_string("Enter a string:") puts(1, s & '\n') n = prompt_number("Enter a number:",{}) printf(1, "%d", n)
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Java
Java
import javax.swing.*;   public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#JavaScript
JavaScript
var str = prompt("Enter a string"); var value = 0; while (value != 75000) { value = parseInt( prompt("Enter the number 75000") ); }
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...
#Kotlin
Kotlin
// version 1.1.2   fun utf8Encode(codePoint: Int) = String(intArrayOf(codePoint), 0, 1).toByteArray(Charsets.UTF_8)   fun utf8Decode(bytes: ByteArray) = String(bytes, Charsets.UTF_8).codePointAt(0)   fun main(args: Array<String>) { val codePoints = intArrayOf(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E) println("Ch...
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...
#X86-64_Assembly
X86-64 Assembly
  option casemap:none     strlen proto :qword strncpy proto :qword, :qword, :dword   Query proto :qword, :qword   .data szstr db "Here am I",0   .code Query proc Data:qword, len:qword local d:qword, l:qword, s:dword   mov d, Data mov l, len invoke strlen, addr szstr .if rax <= l mov s, eax invo...
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...
#Zig
Zig
const std = @import("std");   export fn Query(Data: [*c]u8, Length: *usize) callconv(.C) c_int { const value = "Here I am";   if (Length.* >= value.len) { @memcpy(@ptrCast([*]u8, Data), value, value.len); Length.* = value.len; return 1; }   return 0; }
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...
#Python
Python
import urllib.parse as up # urlparse for Python v2   url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1#fragment')   print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path)...
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...
#Julia
Julia
  //version 1.0.1 import HTTP.URIs: escapeuri   dcd = "http://foo bar/" enc = escapeuri(dcd)   println(dcd, " => ", enc)  
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...
#Kotlin
Kotlin
// version 1.1.2   import java.net.URLEncoder   fun main(args: Array<String>) { val url = "http://foo bar/" println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20 }
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
#FreeBASIC
FreeBASIC
Dim [Shared] As DataType <i>vble1</i> [, <i>vble2</i>, ...]
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#GAP
GAP
# At top level, global variables are declared when they are assigned, so one only writes global_var := 1;   # In a function, local variables are declared like this func := function(n) local a; a := n*n; return n + a; end;   # One can test whether a variable is assigned IsBound(global_var); # true;   # And d...
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 ...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub van_eck { my($init,$max) = @_; my(%v,$k); my @V = my $i = $init; for (1..$max) { $k++; my $t = $v{$i} ? $k - $v{$i} : 0; $v{$i} = $k; push @V, $i = $t; } @V; }   for ( ['A181391', 0], ['A171911', 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...
#Sidef
Sidef
func is_vampire (n) { return [] if n.ilog10.is_even   var l1 = n.isqrt.ilog10.ipow10 var l2 = n.isqrt   var s = n.digits.sort.join   gather { n.divisors.each { |d|   d < l1 && next d > l2 && break   var t = n/d   next if (d%%10 && t%%10) ...
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...
#Phixmonti
Phixmonti
def varfunc 1 tolist flatten len for get print nl endfor enddef     "Mary" "had" "a" "little" "lamb" 5 tolist varfunc
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...
#PHP
PHP
<?php function printAll() { foreach (func_get_args() as $x) // first way echo "$x\n";   $numargs = func_num_args(); // second way for ($i = 0; $i < $numargs; $i++) echo func_get_arg($i), "\n"; } printAll(4, 3, 5, 6, 4, 3); printAll(4, 3, 5); printAll("Rosetta", "Code", "Is", "Awesome!"); ?>
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 ...
#Wren
Wren
import "/str" for Char, Str   var vigenere = Fn.new { |text, key, encrypt| var t = encrypt ? Str.upper(text) : text var sb = "" var ki = 0 for (c in t) { if (Char.isAsciiUpper(c)) { var ci = encrypt ? (c.bytes[0] + key[ki].bytes[0] - 130) % 26 : (c.byte...
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...
#FunL
FunL
A = (3, 4, 5) B = (4, 3, 5) C = (-5, -12, -13)   def dot( u, v ) = sum( u(i)v(i) | i <- 0:u.>length() ) def cross( u, v ) = (u(1)v(2) - u(2)v(1), u(2)v(0) - u(0)v(2), u(0)v(1) - u(1)v(0) ) def scalarTriple( u, v, w ) = dot( u, cross(v, w) ) def vectorTriple( u, v, w ) = cross( u, cross(v, w) )   println( "A\u00b7B = ${...
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...
#Quackery
Quackery
[ 2 split drop do char A char z 1+ within swap char A char z 1+ within and ] is 2chars ( $ --> b )   [ dup size 12 != iff [ drop false ] done dup 2chars not iff [ drop false ] done [] swap witheach [ 36 base put char->n base release...
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...
#Racket
Racket
  #lang racket   ;; convert a base36 character (#\0 - #\Z) to its equivalent ;; in base 10 as a string ("0" - "35") (define (base36-char->base10-string c) (let ([char-int (char->integer (char-upcase c))] [zero-int (char->integer #\0)] [nine-int (char->integer #\9)] [A-int (char->integer #\A)] ...
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...
#Pascal
Pascal
Program VanDerCorput; {$IFDEF FPC} {$MODE DELPHI} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}   type tvdrCallback = procedure (nom,denom: NativeInt);   { Base=2 function rev2(n,Pot:NativeUint):NativeUint; var r : Nativeint; begin r := 0; while Pot > 0 do Begin r := r shl 1 OR (n AND 1); n := n shr 1; ...
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...
#Icon_and_Unicon
Icon and Unicon
link hexcvt   procedure main() ue := "http%3A%2F%2Ffoo%20bar%2F" ud := decodeURL(ue) | stop("Improperly encoded string ",image(ue)) write("encoded = ",image(ue)) write("decoded = ",image(ue)) end   procedure decodeURL(s) #: decode URL/URI encoded data static de initial { # build ...
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...
#J
J
require'strings convert' urldecode=: rplc&(~.,/;"_1&a."2(,:tolower)'%',.toupper hfd i.#a.)
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#Go
Go
package main   import ( "fmt" "regexp" )   var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", }   var ( lhs = make(map...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Lasso
Lasso
#!/usr/bin/lasso9   define config => type {   data public configtxt, public path   public oncreate( path::string = 'testing/configuration.txt' ) => { .configtxt = file(#path) -> readstring .path = #path }   public get(term::string) => { .clean local( regexp = regexp(-find = `(?m)^` + #term + `($|\s*=\...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Nim
Nim
import os, re, strutils   let regex = re(r"^(;*)\s*([A-Z0-9]+)\s*([A-Z0-9]*)", {reIgnoreCase, reStudy})   type   EntryType {.pure.} = enum Empty, Enabled, Disabled, Comment, Ignore   Entry = object etype: EntryType name: string value: string   Config = object entries: seq[Entry] path: string  ...
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
#F.23
F#
open System   let ask_for_input s = printf "%s (End with Return): " s Console.ReadLine()   [<EntryPoint>] let main argv = ask_for_input "Input a string" |> ignore ask_for_input "Enter the number 75000" |> ignore 0
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
#Factor
Factor
"Enter a string: " write readln "Enter a number: " write readln string>number
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Julia
Julia
using Gtk   function twoentrywindow() txt = "Enter Text Here" txtchanged = false   win = GtkWindow("Keypress Test", 500, 100) |> (GtkFrame() |> (vbox = GtkBox(:v))) lab = GtkLabel("Enter some text in the first box and 7500 into the second box.") txtent = GtkEntry() set_gtk_property!(txtent,:text...
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Kotlin
Kotlin
// version 1.1   import javax.swing.JOptionPane   fun main(args: Array<String>) { do { val number = JOptionPane.showInputDialog("Enter 75000").toInt() } while (number != 75000) }
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...
#langur
langur
writeln "character Unicode UTF-8 encoding (hex)"   for .cp in "AöЖ€𝄞" { val .utf8 = s2b cp2s .cp val .cpstr = b2s .utf8 val .utf8rep = join " ", map f $"\.b:X02;", .utf8 writeln $"\.cpstr:-11; U+\.cp:X04:-8; \.utf8rep;" }
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...
#Lingo
Lingo
chars = ["A", "ö", "Ж", "€", "𝄞"] put "Character Unicode (int) UTF-8 (hex) Decoded" repeat with c in chars ba = bytearray(c) put col(c, 12) & col(charToNum(c), 16) & col(ba.toHexString(1, ba.length), 14) & ba.readRawString(ba.length) end repeat
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...
#zkl
zkl
// query.c // export zklRoot=/home/ZKL // clang query.c -I $zklRoot/VM -L $zklRoot/Lib -lzkl -pthread -lncurses -o query // LD_LIBRARY_PATH=$zklRoot/Lib ./query   #include <stdio.h> #include <string.h>   #include "zklObject.h" #include "zklImports.h" #include "zklClass.h" #include "zklFcn.h" #include "zklString.h"   in...
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...
#R
R
  library(urltools)   urls <- c("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", ...
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...
#Ksh
Ksh
  url_encode() { printf "%(url)q\n" "$*" }     url_encode "http://foo bar/" url_encode "https://ru.wikipedia.org/wiki/Транспайлер" url_encode "google.com/search?q=`Abdu'l-Bahá"  
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...
#langur
langur
val .urlEncode = f(.s) replace( .s, re/[^A-Za-z0-9]/, f(.s2) for .b in s2b(.s2) { _for ~= $"%\.b:X02;" }, )   val .original = "https://some website.com/"   writeln .original writeln .urlEncode(.original)
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
#GlovePIE
GlovePIE
if var.end=0 then // Without the code being in this if statement, the code would keep executing until it were to stop. var.end=1 // These variables, respectively, refer to an integer, a boolean, and a string. var.variable1=3 var.variable2=True var.variable3="Hi!" // var.example1 now refers to a string object instead. v...
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
#Go
Go
x := 3
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 ...
#Phix
Phix
constant lim = 1000 sequence van_eck = repeat(0,lim), pos_before = repeat(0,lim) for n=1 to lim-1 do integer vn = van_eck[n]+1, prev = pos_before[vn] if prev!=0 then van_eck[n+1] = n - prev end if pos_before[vn] = n end for printf(1,"The first ten terms of the Van Eck sequen...
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 ...
#Picat
Picat
main => Limit = 1000, A = new_array(Limit+1), bind_vars(A,0), foreach(N in 1..Limit-1) M = find_last_of(A[1..N],A[N+1]), if M > 0 then A[N+2] := N-M+1 end end, println(A[1..10]), println(A[991..1000]), nl.
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...
#Swift
Swift
import Foundation   func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger { let strN = String(n).sorted() let fangLength = strN.count / 2 let start = T(pow(10, Double(fangLength - 1))) let end = T(Double(n).squareRoot())   var fangs = [(T, T)]()   for i in start...end where n % 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...
#Tcl
Tcl
proc factorPairs {n {from 2}} { set result [list 1 $n] if {$from<=1} {set from 2} for {set i $from} {$i<=sqrt($n)} {incr i} { if {$n%$i} {} {lappend result $i [expr {$n/$i}]} } return $result }   proc vampireFactors {n} { if {[string length $n]%2} return set half [expr {[string length $n]/2...
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...
#PicoLisp
PicoLisp
(de varargs @ (while (args) (println (next)) ) )
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...
#PL.2FI
PL/I
/* PL/I permits optional arguments, but not an infinitely varying */ /* argument list: */ s: procedure (a, b, c, d); declare (a, b, c, d) float optional; if ^omitted(a) then put skip list (a); if ^omitted(b) then put skip list (b); if ^omitted(c) then put skip list (c); if ^omitted(d) then put skip list ...
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 ...
#XPL0
XPL0
code ChIn=7, ChOut=8; int Neg, C, Len, I, Key; char KeyWord(80); [Neg:= false; \skip to KEYWORD repeat C:= ChIn(8); if C=^- then Neg:= true; until C>=^A & C<=^Z; Len:= 0; \read in KEYWORD repeat KeyWord(Len):= C-^A; Len:= Len+1; C:= ChIn(8); ...
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 ...
#zkl
zkl
fcn encipher(src,key,is_encode){ upperCase:=["A".."Z"].pump(String); src=src.toUpper().inCommon(upperCase); // only uppercase key=key.toUpper().inCommon(upperCase).pump(List,"toAsc");   const A="A".toAsc(); klen:=Walker.cycle(key.len()); // 0,1,2,3,..,keyLen-1,0,1,2,3, ... src.pump(String,'wrap(c){ ...
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...
#GAP
GAP
DotProduct := function(u, v) return u*v; end;   CrossProduct := function(u, v) return [ u[2]*v[3] - u[3]*v[2], u[3]*v[1] - u[1]*v[3], u[1]*v[2] - u[2]*v[1] ]; end;   ScalarTripleProduct := function(u, v, w) return DotProduct(u, CrossProduct(v, w)); end;   VectorTripleProduct := function(u, v, w) return CrossP...
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...
#Raku
Raku
my $ISIN = / ^ <[A..Z]>**2 <[A..Z0..9]>**9 <[0..9]> $ <?{ luhn-test $/.comb.map({ :36($_) }).join }> /;   sub luhn-test ($number --> Bool) { my @digits = $number.comb.reverse; my $sum = @digits[0,2...*].sum + @digits[1,3...*].map({ |($_ * 2).comb }).sum; return $sum %% 10; }   # Testing:...
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...
#Perl
Perl
sub vdc { my @value = shift; my $base = shift // 2; use integer; push @value, $value[-1] / $base while $value[-1] > 0; my ($x, $sum) = (1, 0); no integer; $sum += ($_ % $base) / ($x *= $base) for @value; return $sum; }   for my $base ( 2 .. 5 ) { print "base $base: ", join ' ', map {...
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...
#Java
Java
import java.io.UnsupportedEncodingException; import java.net.URLDecoder;   public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String encoded = "http%3A%2F%2Ffoo%20bar%2F"; String normal = URLDecoder.decode(encoded, "utf-8"); System.out.printl...
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...
#JavaScript
JavaScript
decodeURIComponent("http%3A%2F%2Ffoo%20bar%2F")
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#J
J
upcdigit=:".;._2]0 :0 0 0 0 1 1 0 1 NB. 0 0 0 1 1 0 0 1 NB. 1 0 0 1 0 0 1 1 NB. 2 0 1 1 1 1 0 1 NB. 3 0 1 0 0 0 1 1 NB. 4 0 1 1 0 0 0 1 NB. 5 0 1 0 1 1 1 1 NB. 6 0 1 1 1 0 1 1 NB. 7 0 1 1 0 1 1 1 NB. 8 0 0 0 1 0 1 1 NB. 9 )   upc2dec=:3 :0 if. 95~: #code=. '#'=dtb dlb y do._ return.end. if. (11$...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Perl
Perl
use warnings; use strict;   my $needspeeling = 0; my $seedsremoved = 1; my $numberofstrawberries = 62000; my $numberofbananas = 1024; my $favouritefruit = 'bananas';   my @out;   sub config { my (@config) = <DATA>; push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n" u...
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
#Falcon
Falcon
printl("Enter a string:") str = input() printl("Enter a number:") n = int(input())
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
#FALSE
FALSE
[[^$' =~][,]#,]w: [0[^'0-$$9>0@>|~][\10*+]#%]d: w;! d;!.
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#LabVIEW
LabVIEW
' [RC] User input/graphical   ' Typical LB graphical input/output example.This shows how LB takes user input. ' You'd usually do more validating of input.     nomainwin ' No console window needed.   textbox#w.tb1, 100, 20, 200, 30 textbox#w.tb2, 100, 60, 200, 30 textbox#w.tb3, 100,160,...
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...
#Lua
Lua
  -- Accept an integer representing a codepoint. -- Return the values of the individual octets. function encode (codepoint) local codepoint_str = utf8.char(codepoint) local result = {}   for i = 1, #codepoint_str do result[#result + 1] = string.unpack("B", codepoint_str, i) end   return table.unpack(resul...
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...
#Racket
Racket
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) ...
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...
#Raku
Raku
use URI;   my @test-uris = < 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?objectCl...
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...
#Lasso
Lasso
bytes('http://foo bar/') -> encodeurl
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...
#Liberty_BASIC
Liberty BASIC
  dim lookUp$( 256)   for i =0 to 256 lookUp$( i) ="%" +dechex$( i) next i   string$ ="http://foo bar/"   print "Supplied string '"; string$; "'" print "As URL '"; url$( string$); "'"   end   function url$( i$) for j =1 to len( i$) c$ =mid$( i$, j, 1) if ...
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
#Haskell
Haskell
foobar = 15   f x = x + foobar where foobar = 15   f x = let foobar = 15 in x + foobar   f x = do let foobar = 15 return $ x + foobar
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
#HicEst
HicEst
! Strings and arrays must be declared. ! Everything else is 8-byte float, READ/WRITE converts CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/ REAL, PARAMETER :: named_constant = 3.1415 REAL :: n=2, cols=4, vec(cols), mtx(n, cols) DATA vec/2,3,4,5/, mtx/1,2,3.1415,4, 5,6,7,8/   named = ALIAS(alpha, beta, ga...
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 ...
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (7) BYTE INITIAL ('..... $'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = ...
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 ...
#Prolog
Prolog
van_eck_init(v(0, 0, _assoc)):- empty_assoc(_assoc).   van_eck_next(v(Index, Last_term, Last_pos), v(Index1, Next_term, Last_pos1)):- (get_assoc(Last_term, Last_pos, V) -> Next_term is Index - V ; Next_term = 0 ), Index1 is Index + 1, put_assoc(Last_term, Last_pos, Index, Las...
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...
#Vlang
Vlang
import math fn max(a u64, b u64) u64 { if a > b { return a } return b }   fn min(a u64, b u64) u64 { if a < b { return a } return b }   fn ndigits(xx u64) int { mut n:=0 mut x := xx for ; x > 0; x /= 10 { n++ } return n }   fn dtally(xx u64) u64 { ...
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...
#Wren
Wren
import "/fmt" for Fmt   var ndigits = Fn.new { |x| var n = 0 while (x > 0) { n = n + 1 x = (x/10).floor } return n }   var dtally = Fn.new { |x| var t = 0 while (x > 0) { t = t + 2.pow((x%10) * 6) x = (x/10).floor } return t }   var tens = List.filled(15, ...
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...
#PowerShell
PowerShell
function print_all { foreach ($x in $args) { Write-Host $x } }
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...
#Prolog
Prolog
?- write( (1) ), nl. 1 ?- write( (1,2,3) ), nl. 1,2,3
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...
#GLSL
GLSL
  vec3 a = vec3(3, 4, 5),b = vec3(4, 3, 5),c = vec3(-5, -12, -13);   float dotProduct(vec3 a, vec3 b) { return a.x*b.x+a.y*b.y+a.z*b.z; }   vec3 crossProduct(vec3 a,vec3 b) { vec3 c = vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y- a.y*b.x);   return c; }   float scalarTripleProduct(vec3 a,vec3 b,vec3 c) { retu...
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...
#REXX
REXX
/*REXX program validates the checksum digit for an International Securities ID number.*/ parse arg z /*obtain optional ISINs from the C.L.*/ if z='' then z= "US0378331005 US0373831005 U50378331005 US03378331005 AU0000XVGZA3" , 'AU0000VXGZA3 FR0000988040' /*...
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...
#Phix
Phix
enum BASE, FRAC, DECIMAL constant DESC = {"Base","Fraction","Decimal"} function vdc(integer n, atom base, integer flag) object res = "" atom num = 0, denom = 1, digit, g while n do denom *= base digit = remainder(n,base) n = floor(n/base) if flag=BASE then res &= digit+...
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...
#jq
jq
# Emit . and stop as soon as "condition" is true. def until(condition; next): def u: if condition then . else (next|u) end; u;   def url_decode: # The helper function converts the input string written in the given # "base" to an integer def to_i(base): explode | reverse | map(if 65 <= . and . <= 9...
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...
#Julia
Julia
  using URIParser   enc = "http%3A%2F%2Ffoo%20bar%2F"   dcd = unescape(enc)   println(enc, " => ", dcd)  
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#Java
Java
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors;   public class UPC { private static final int SEVEN = 7;   private static final Map<String, Integer> LEFT_DIGITS = Map.of( ...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Phix
Phix
integer fn = open("RCTEST.INI","r") sequence lines = get_text(fn,GT_LF_STRIPPED) close(fn) constant dini = new_dict() for i=1 to length(lines) do string li = trim(lines[i]) if length(li) and not find(li[1],"#;") then integer k = find(' ',li) if k!=0 then string rest = li[k+1..$] ...
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
#Fantom
Fantom
  class Main { public static Void main () { Env.cur.out.print ("Enter a string: ").flush str := Env.cur.in.readLine echo ("Entered :$str:") Env.cur.out.print ("Enter 75000: ").flush Int n try n = Env.cur.in.readLine.toInt catch (Err e) { echo ("You had to enter a number") ...
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
#Forth
Forth
: INPUT$ ( n -- addr n ) PAD SWAP ACCEPT PAD SWAP ;
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Liberty_BASIC
Liberty BASIC
' [RC] User input/graphical   ' Typical LB graphical input/output example.This shows how LB takes user input. ' You'd usually do more validating of input.     nomainwin ' No console window needed.   textbox#w.tb1, 100, 20, 200, 30 textbox#w.tb2, 100, 60, 200, 30 textbox#w.tb3, 100,160,...
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...
#M2000_Interpreter
M2000 Interpreter
  Module EncodeDecodeUTF8 { a$=string$("Hello" as UTF8enc) Print Len(A$)=2.5 ' 2.5 words=5 bytes b$=string$(a$ as UTF8dec) Print b$ Print Len(b$)=5 ' 5 words = 10 bytes   Print Len(string$("A" as UTF8enc))=.5 ' 1 byte Print Len(string$("ö" as UTF8enc))=1 ' 2 bytes ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
utf = ToCharacterCode[ToString["AöЖ€", CharacterEncoding -> "UTF8"]] ToCharacterCode[FromCharacterCode[utf, "UTF8"]]
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...
#Ruby
Ruby
require 'uri'   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?ob...
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...
#Rust
Rust
use url::Url;   fn print_fields(url: Url) -> () { println!("scheme: {}", url.scheme()); println!("username: {}", url.username());   if let Some(password) = url.password() { println!("password: {}", password); }   if let Some(domain) = url.domain() { println!("domain: {}", domain); ...