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/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...
#Factor
Factor
USING: arrays io locals math prettyprint sequences ;   : dot-product ( a b -- dp ) [ * ] 2map sum ;   :: cross-product ( a b -- cp ) a first :> a1 a second :> a2 a third :> a3 b first :> b1 b second :> b2 b third :> b3 a2 b3 * a3 b2 * - ! X a3 b1 * a1 b3 * - ! Y a1 b2 * a2 b1 * - ! Z 3array ;   ...
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...
#Perl
Perl
use strict; use English; use POSIX; use Test::Simple tests => 7;   ok( validate_isin('US0378331005'), 'Test 1'); ok( ! validate_isin('US0373831005'), 'Test 2'); ok( ! validate_isin('U50378331005'), 'Test 3'); ok( ! validate_isin('US03378331005'), 'Test 4'); ok( validate_isin('AU0000XVGZA3'), 'Test 5'); ok( ...
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...
#Julia
Julia
using Printf   vandercorput(num::Integer, base::Integer) = sum(d * Float64(base) ^ -ex for (ex, d) in enumerate(digits(num, base = base)))   for base in 2:9 @printf("%10s %i:", "Base", base) for num in 0:9 @printf("%7.3f", vandercorput(num, base)) end println(" [...]") end
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...
#Kotlin
Kotlin
// version 1.1.2   data class Rational(val num: Int, val denom: Int)   fun vdc(n: Int, base: Int): Rational { var p = 0 var q = 1 var nn = n while (nn != 0) { p = p * base + nn % base q *= base nn /= base } val num = p val denom = q while (p != 0) { nn = p...
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...
#Erlang
Erlang
34> http_uri: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...
#F.23
F#
open System   let decode uri = Uri.UnescapeDataString(uri)   [<EntryPoint>] let main argv = printfn "%s" (decode "http%3A%2F%2Ffoo%20bar%2F") 0
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...
#AWK
AWK
  # syntax: GAWK -f UPC.AWK BEGIN { ls_arr[" ## #"] = 0 ls_arr[" ## #"] = 1 ls_arr[" # ##"] = 2 ls_arr[" #### #"] = 3 ls_arr[" # ##"] = 4 ls_arr[" ## #"] = 5 ls_arr[" # ####"] = 6 ls_arr[" ### ##"] = 7 ls_arr[" ## ###"] = 8 ls_arr[" # ##"] = 9 for (i in ls_arr) { ...
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...
#Go
Go
package main   import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" )   // line represents a single line in the configuration file. type line struct { kind lineKind option string value string disabled bool }   // lineKind represents the different kinds of configuration line. type lineKind int ...
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
#Crystal
Crystal
puts "You entered: #{gets}"   begin puts "You entered: #{gets.not_nil!.chomp.to_i}" rescue ex puts ex end
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
#D
D
import std.stdio;   void main() { long number; write("Enter an integer: "); readf("%d", &number);   char[] str; write("Enter a string: "); readf(" %s\n", &str);   writeln("Read in '", number, "' and '", str, "'"); }
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
#Groovy
Groovy
import javax.swing.JOptionPane   def number = JOptionPane.showInputDialog ("Enter an Integer") as Integer def string = JOptionPane.showInputDialog ("Enter a String")   assert number instanceof Integer assert string instanceof String
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...
#Haskell
Haskell
module Main (main) where   import qualified Data.ByteString as ByteString (pack, unpack) import Data.Char (chr, ord) import Data.Foldable (for_) import Data.List (intercalate) import qualified Data.Text as Text (head, singleton) import qualified Data.Text.Encoding as Text (decodeUtf8, enco...
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...
#Racket
Racket
  typedef int strfun (char * Data, size_t * Length); strfun *Query = NULL;  
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...
#Raku
Raku
#!/usr/bin/env raku   sub MAIN (Int :l(:len(:$length))) { my Str $String = "Here am I"; $*OUT.print: $String if $String.codes ≤ $length }
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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   use URI;   for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret#nose urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ...
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...
#Groovy
Groovy
  def normal = "http://foo bar/" def encoded = URLEncoder.encode(normal, "utf-8") println 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...
#Haskell
Haskell
import qualified Data.Char as Char import Text.Printf   encode :: Char -> String encode c | c == ' ' = "+" | Char.isAlphaNum c || c `elem` "-._~" = [c] | otherwise = printf "%%%02X" c   urlEncode :: String -> String urlEncode = concatMap encode   main :: IO () main = putStrLn $ urlEncode "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
#Elena
Elena
import system'collections;   public program() { var c := nil; // declaring variable. var a := 3; // declaring and initializing variables var b := "my string".Length; long l := 200l; // declaring strongly typed variable auto lst := new List<int>(); ...
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
#Erlang
Erlang
  two() -> A_variable = 1, A_variable + 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 ...
#Kotlin
Kotlin
fun main() { println("First 10 terms of Van Eck's sequence:") vanEck(1, 10) println("") println("Terms 991 to 1000 of Van Eck's sequence:") vanEck(991, 1000) }   private fun vanEck(firstIndex: Int, lastIndex: Int) { val vanEckMap = mutableMapOf<Int, Int>() var last = 0 if (firstIndex == ...
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...
#Racket
Racket
#lang racket   ;; chock full of fun... including divisors (require math/number-theory)   ;; predicate to tell if n is a vampire number (define (sub-vampire?-and-fangs n) (define digit-count-n (add1 (order-of-magnitude n))) (define (string-sort-characters s) (sort (string->list s) char<?)) (define digits-in-order-...
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...
#Raku
Raku
sub is_vampire (Int $num) { my $digits = $num.comb.sort; my @fangs; (10**$num.sqrt.log(10).floor .. $num.sqrt.ceiling).map: -> $this { next if $num % $this; my $that = $num div $this; next if $this %% 10 && $that %% 10; @fangs.push("$this x $that") if ($this ~ $that).comb.sor...
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...
#Nim
Nim
proc print(xs: varargs[string, `$`]) = for x in xs: echo 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...
#Objective-C
Objective-C
#include <stdarg.h>   void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list { va_list args; va_start(args, firstObject); id obj; for (obj = firstObject; obj != nil; obj = va_arg(args, id)) NSLog(@"%@", obj); va_end(args); }   // This f...
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...
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream';   let vmath f v1 v2 => s.zip (a.stream v1) (a.stream v2) -> s.map (@ m v => let [v1 v2] => v; f (v1 { == s.end => 0 }) (v2 { == s.end => 0 }); ) -> s.collect  ;   let smath f scalar vector => a.stream vector -> s.map (f scalar) -> s....
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...
#Wren
Wren
class Vector2D { construct new(x, y) { _x = x _y = y }   static fromPolar(r, theta) { new(r * theta.cos, r * theta.sin) }   x { _x } y { _y }   +(v) { Vector2D.new(_x + v.x, _y + v.y) } -(v) { Vector2D.new(_x - v.x, _y - v.y) } *(s) { Vector2D.new(_x * s, _y * s) } ...
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 ...
#TXR
TXR
@(next :args) @(do (defun vig-op (plus-or-minus) (op + #\A [mod [plus-or-minus (- @1 #\A) (- @2 #\A)] 26]))   (defun vig (msg key encrypt) (mapcar (vig-op [if encrypt + -]) msg (repeat key)))) @(coll)@{key /[A-Za-z]/}@(end) @(coll)@{msg /[A-Za-z]/}@(end) @(cat key "") @(filter :upcase key) @(cat msg "")...
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 ...
#TypeScript
TypeScript
class Vigenere {   key: string   /** Create new cipher based on key */ constructor(key: string) { this.key = Vigenere.formatText(key) }   /** Enrypt a given text using key */ encrypt(plainText: string): string { return Array.prototype.map.call(Vigenere.formatText(plainText), (let...
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...
#Fantom
Fantom
class Main { Int dot_product (Int[] a, Int[] b) { a[0]*b[0] + a[1]*b[1] + a[2]*b[2] }   Int[] cross_product (Int[] a, Int[] b) { [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0]] }   Int scalar_triple_product (Int[] a, Int[] b, Int[] c) { dot_product (a, cross_product (b, c...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Phix
Phix
with javascript_semantics function Luhn(string st) integer s = 0, d st = reverse(st) for i=1 to length(st) do d = st[i]-'0' s += iff(mod(i,2)?d,d*2-(d>4)*9) end for return remainder(s,10)=0 end function function valid_ISIN(string st) -- returns 1 if valid, else 0/2/3/4. -- (feel fr...
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...
#Lua
Lua
function vdc(n, base) local digits = {} while n ~= 0 do local m = math.floor(n / base) table.insert(digits, n - m * base) n = m end m = 0 for p, d in pairs(digits) do m = m + math.pow(base, -p) * d end return m end
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...
#Maple
Maple
Halton:=proc(n,b) local i:=n,k:=1,s:=0,r; while i>0 do k/=b; i:=iquo(i,b,'r'); s+=k*r od; s end;   map(Halton,[$1..10],2); # [1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16, 5/16]   map(Halton,[$1..10],3); # [1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27, 10/27]   map(Halton,[$1..10],4); # [1/4, 1/2, ...
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...
#Factor
Factor
USING: io kernel urls.encoding ; IN: rosetta-code.url-decoding   "http%3A%2F%2Ffoo%20bar%2F" "google.com/search?q=%60Abdu%27l-Bah%C3%A1" [ url-decode print ] bi@
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...
#Free_Pascal
Free Pascal
function urlDecode(data: String): AnsiString; var ch: Char; pos, skip: Integer;   begin pos := 0; skip := 0; Result := '';   for ch in data do begin if skip = 0 then begin if (ch = '%') and (pos < data.length -2) then begin skip := 2; Result := Result + AnsiChar(Hex2Dec('$' + data[...
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...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   typedef char const *const string;   bool consume_sentinal(bool middle, string s, size_t *pos) { if (middle) { if (s[*pos] == ' ' && s[*pos + 1] == '#' && s[*pos + 2] == ' ' && s[*pos + 3] == '#' && s[*pos + 4] == ' ') { ...
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...
#Haskell
Haskell
import Data.Char (toUpper) import qualified System.IO.Strict as S
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
#Dart
Dart
import 'dart:io' show stdout, stdin;   main() { stdout.write('Enter a string: '); final string_input = stdin.readLineSync();   int number_input;   do { stdout.write('Enter the number 75000: '); var number_input_string = stdin.readLineSync();   try { number_input = int.parse(number_input_string); if (nu...
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
#Delphi
Delphi
program UserInputText;   {$APPTYPE CONSOLE}   uses SysUtils;   var s: string; lStringValue: string; lIntegerValue: Integer; begin WriteLn('Enter a string:'); Readln(lStringValue);   repeat WriteLn('Enter the number 75000'); Readln(s); lIntegerValue := StrToIntDef(s, 0); if lIntegerValue <> 7...
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
#Haskell
Haskell
import Graphics.UI.Gtk import Control.Monad   main = do initGUI   window <- windowNew set window [windowTitle := "Graphical user input", containerBorderWidth := 10]   vb <- vBoxNew False 0 containerAdd window vb   hb1 <- hBoxNew False 0 boxPackStart vb hb1 PackNatural 0 hb2 <- hBoxNew False 0 boxPackS...
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...
#J
J
utf8=: 8&u: NB. converts to UTF-8 from unicode or unicode codepoint integer ucp=: 9&u: NB. converts to unicode from UTF-8 or unicode codepoint integer ucp_hex=: hfd@(3 u: ucp) NB. converts to unicode codepoint hexadecimal from UTF-8, unicode or unicode codepoint integer
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...
#Java
Java
import java.nio.charset.StandardCharsets; import java.util.Formatter;   public class UTF8EncodeDecode {   public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); }   public static int utf8decode(byte[] bytes) { return n...
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...
#Ruby
Ruby
# query.rb require 'fiddle'   # Look for a C variable named QueryPointer. # Raise an error if it is missing. c_var = Fiddle.dlopen(nil)['QueryPointer']   int = Fiddle::TYPE_INT voidp = Fiddle::TYPE_VOIDP sz_voidp = Fiddle::SIZEOF_VOIDP   # Implement the C function # int Query(void *data, size_t *length) # in Ruby cod...
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...
#Rust
Rust
  //! In order to run this task, you will need to compile the C program locating in the task linked //! above. The C program will need to be linked with the library produced by this file. //! //! 1. Compile this library: //! //! ```bash //! $ cargo build --release //! ``` //! //! 2. Copy the C program into ...
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...
#Phix
Phix
with javascript_semantics include builtins/url.e procedure show_url_details(string uri) ?uri sequence r = parse_url(uri) for i=1 to length(r) do if r[i]!=0 then string desc = url_element_desc(i) printf(1,"%s : %v\n",{desc,r[i]}) end if end for puts(1,"\n") e...
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...
#Icon_and_Unicon
Icon and Unicon
link hexcvt   procedure main() write("text = ",image(u := "http://foo bar/")) write("encoded = ",image(ue := encodeURL(u))) end   procedure encodeURL(s) #: encode data for inclusion in a URL/URI static en initial { # build lookup table for everything ...
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
#F.23
F#
let x = 5 // Int let mutable y = "mutable" // Mutable string let recordType = { foo : 6; bar : 6 } // Record let intWidget = new Widget<int>() // Generic class let add2 x = 2 + x // Function value
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 ...
#Lua
Lua
-- Return a table of the first n values of the Van Eck sequence function vanEck (n) local seq, foundAt = {0} while #seq < n do foundAt = nil for pos = #seq - 1, 1, -1 do if seq[pos] == seq[#seq] then foundAt = pos break end end if foundAt then table.insert(seq, #seq...
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 ...
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION E(1000) E(0)=0 THROUGH L1, FOR I=0, 1, I.GE.1000 THROUGH L2, FOR J=I-1, -1, J.L.0 WHENEVER E(J).E.E(I) E(I+1) = I-J TRANSFER TO L1 END OF CONDITIONAL L2 CONTINUE ...
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...
#REXX
REXX
/*REXX program displays N vampire numbers, or verifies if a number is vampiric. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ !.0= 1260;  !.1= 11453481;  !.2= 115672;  !....
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...
#Oforth
Oforth
: sumNum(n) | i | 0 n loop: i [ + ] ;
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...
#Oz
Oz
declare class Demo from BaseObject meth test(...)=Msg {Record.forAll Msg Show} end end   D = {New Demo noop} Constructed = {List.toTuple test {List.number 1 10 1}} in {D test(1 2 3 4)} {D Constructed}
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...
#Yabasic
Yabasic
dim vect1(2) vect1(1) = 5 : vect1(2) = 7 dim vect2(2) vect2(1) = 2 : vect2(2) = 3 dim vect3(arraysize(vect1(),1))   for n = 1 to arraysize(vect1(),1) vect3(n) = vect1(n) + vect2(n) next n print "[", vect1(1), ", ", vect1(2), "] + [", vect2(1), ", ", vect2(2), "] = "; showarray(vect3)   for n = 1 to arraysize(vect1(...
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...
#zkl
zkl
class Vector{ var length,angle; // polar coordinates, radians fcn init(length,angle){ // angle in degrees self.length,self.angle = vm.arglist.apply("toFloat"); self.angle=self.angle.toRad(); } fcn toXY{ length.toRectangular(angle) } // math is done in place fcn __opAdd(vector){ x1,...
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 ...
#VBA
VBA
Option Explicit   Sub test() Dim Encryp As String Encryp = Vigenere("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher", True) Debug.Print "Encrypt:= """ & Encryp & """" Debug.Print "Decrypt:= """ & Vigenere(Encryp, "vigenerecipher", False) & """" End Sub   Private Func...
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...
#Forth
Forth
  : 3f! ( &v - ) ( f: x y z - ) dup float+ dup float+ f! f! f! ;   : Vector \ Compiletime: ( f: x y z - ) ( <name> - ) create here [ 3 floats ] literal allot 3f! ; \ Runtime: ( - &v )   : >fx@ ( &v - ) ( f: - n ) postpone f@ ; immediate : >fy@ ( &v - ) ( f: - n ) float+ f@ ; : >fz@ ( &v - ) ( f: - n ) fl...
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...
#PicoLisp
PicoLisp
(de isin (Str) (let Str (mapcar char (chop Str)) (and (= 12 (length Str)) (<= 65 (car Str) 90) (<= 65 (cadr Str) 90) (luhn (pack (mapcar '((N) (- N (if (<= 48 N 57) 48 55)) ) Str ) ) ) ) ) ) ...
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...
#PowerShell
PowerShell
  function Test-ISIN { [CmdletBinding()] [OutputType([bool])] Param ( [Parameter(Mandatory=$true, Position=0)] [ValidatePattern("[A-Z]{2}\w{9}\d")] [ValidateScript({$_.Length -eq 12})] [string] $Number )   function Split-Array { $array = @(), @...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
VanDerCorput[n_,base_:2]:=Table[ FromDigits[{Reverse[IntegerDigits[k,base]],0},base], {k,n}] VanDerCorput[10,2] VanDerCorput[10,3] VanDerCorput[10,4] VanDerCorput[10,5]  
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function x = corput (n) b = dec2bin(1:n)-'0'; % generate sequence of binary numbers from 1 to n l = size(b,2); % get number of binary digits w = (1:l)-l-1; % 2.^w are the weights x = b * ( 2.^w'); % matrix times vector multiplication for end;
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...
#FreeBASIC
FreeBASIC
  Const alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"   Function ToDecimal (cadena As String, base_ As Uinteger) As Uinteger Dim As Uinteger i, n, result = 0 Dim As Uinteger inlength = Len(cadena)   For i = 1 To inlength n = Instr(alphanum, Mid(Lcase(cadena),i,1)) - 1 n *= (base_^(inlen...
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...
#C.2B.2B
C++
#include <iostream> #include <locale> #include <map> #include <vector>   std::string trim(const std::string &str) { auto s = str;   //rtrim auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end());   //ltrim ...
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...
#J
J
require 'regex strings'   normalize=:3 :0 seen=. a: eol=. {:;y t=. '' for_line.<;._2;y do. lin=. deb line=.>line if. '#'={.line do. t=.t,line,eol elseif. ''-:lin do. t =. t,eol elseif. do. line=. 1 u:([-.-.)&(32+i.95)&.(3&u:) line base=. ('^ *;;* *';'') rxrplc line nm=. ;name=. {.;...
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
input s:  !print\ s  !decode!utf-8 !read-line!stdin local :astring input "Enter a string: " true while: try: to-num input "Enter the number 75000: " /= 75000 catch value-error: true
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
#EasyLang
EasyLang
write "Enter a string: " a$ = input print "" repeat write "Enter the number 75000: " h = number input print "" until h = 75000 . print a$ & " " & h
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
#HicEst
HicEst
CHARACTER string*100   DLG(Edit=string, Edit=num_value, Button='&OK', TItle='Enter 75000 for num_value') WRITE(Messagebox, Name) "You entered", string, num_value
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
#Icon_and_Unicon
Icon and Unicon
procedure main() WOpen("size=800,800") | stop("Unable to open window") WWrite("Enter a string:") s := WRead() WWrite("You entered ",image(s)) WWrite("Enter the integer 75000:") i := WRead() if i := integer(i) then WWrite("You entered: ",i) else WWrite(image(i)," isn't an integer") WDone() end   link graphics
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...
#JavaScript
JavaScript
  /***************************************************************************\ |* Pure UTF-8 handling without detailed error reporting functionality. *| |***************************************************************************| |* utf8encode *| |* ...
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...
#Scala
Scala
/* Query.scala */ object Query { def call(data: Array[Byte], length: Array[Int]): Boolean = { val message = "Here am I" val mb = message.getBytes("utf-8") if (length(0) >= mb.length) { length(0) = mb.length System.arraycopy(mb, 0, data, 0, mb.length) true } else false } }
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...
#Tcl
Tcl
int Query (char * Data, size_t * Length) { Tcl_Obj *arguments[2]; int code;   arguments[0] = Tcl_NewStringObj("Query", -1); /* -1 for "use up to zero byte" */ arguments[1] = Tcl_NewStringObj(Data, Length); Tcl_IncrRefCount(arguments[0]); Tcl_IncrRefCount(arguments[1]); if (Tcl_EvalObjv(inter...
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...
#PHP
PHP
<?php   $urls = array( '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=G...
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...
#J
J
require'strings convert' urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.)
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...
#Java
Java
import java.io.UnsupportedEncodingException; import java.net.URLEncoder;   public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String normal = "http://foo bar/"; String encoded = URLEncoder.encode(normal, "utf-8"); System.out.println(encoded);...
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
#Factor
Factor
SYMBOL: foo   : use-foo ( -- ) 1 foo set foo get 2 + foo set ! foo now = 3 foo get number>string print ;   :: named-param-example ( a b -- ) a b + number>string print ;   : local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ;
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
#Falcon
Falcon
  /* partially created by Aykayayciti Earl Lamont Montgomery April 9th, 2018 */   /* global and local scrope from the Falcon survival guide book */ // global scope sqr = 1.41   function square( x ) // local scope sqr = x * x return sqr end     number = square( 8 ) * sqr     a = [1, 2, 3] // array b = 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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  TakeList[Nest[If[MemberQ[#//Most, #//Last], Join[#, Length[#] - Last@Position[#//Most, #//Last]], Append[#, 0]]&, {0}, 999], {10, -10}] // Column
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 ...
#Modula-2
Modula-2
MODULE VanEck; FROM InOut IMPORT WriteCard, WriteLn;   VAR i, j: CARDINAL; eck: ARRAY [1..1000] OF CARDINAL;   BEGIN FOR i := 1 TO 1000 DO eck[i] := 0; END; FOR i := 1 TO 999 DO j := i-1; WHILE (j > 0) AND (eck[i] <> eck[j]) DO DEC(j); END; IF j <> 0 T...
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...
#Ring
Ring
  # Project : Vampire number   for p = 10 to 127000 vampire(p) next   func vampire(listnum) sum = 0 flag = 1 list = list(len(string(listnum))) total = newlist(len(list),2) for n = 1 to len(string(listnum)) liststr = string(listnum) list[n] = liststr[n]...
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...
#Ruby
Ruby
def factor_pairs n first = n / (10 ** (n.to_s.size / 2) - 1) (first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact end   def vampire_factors n return [] if n.to_s.size.odd? half = n.to_s.size / 2 factor_pairs(n).select do |a, b| a.to_s.size == half && b.to_s.size == half && [a, b].count {|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...
#PARI.2FGP
PARI/GP
f(a[..])=for(i=1,#a,print(a[i]))
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...
#Pascal
Pascal
sub print_all { foreach (@_) { print "$_\n"; } }
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 ...
#VBScript
VBScript
  Function Encrypt(text,key) text = OnlyCaps(text) key = OnlyCaps(key) j = 1 For i = 1 To Len(text) ms = Mid(text,i,1) m = Asc(ms) - Asc("A") ks = Mid(key,j,1) k = Asc(ks) - Asc("A") j = (j Mod Len(key)) + 1 c = (m + k) Mod 26 c = Chr(Asc("A")+c) Encrypt = Encrypt & c Next End Function   Function ...
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...
#Fortran
Fortran
program VectorProducts   real, dimension(3) :: a, b, c   a = (/ 3, 4, 5 /) b = (/ 4, 3, 5 /) c = (/ -5, -12, -13 /)   print *, dot_product(a, b) print *, cross_product(a, b) print *, s3_product(a, b, c) print *, v3_product(a, b, c)   contains   function cross_product(a, b) real, dimension(3) :: c...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#PureBasic
PureBasic
EnableExplicit   Procedure.b Check_ISIN(*c.Character) Define count.i=0, Idx.i=1, v.i=0, i.i Dim s.i(24)   If MemoryStringLength(*c) > 12 : ProcedureReturn #False : EndIf   While *c\c count+1 If *c\c>='0' And *c\c<='9' If count<=2 : ProcedureReturn #False : EndIf s(Idx)= *c\c - '0' ...
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...
#Maxima
Maxima
/* convert a decimal integer to a list of digits in base `base' */ dec2digits(d, base):= block([digits: []], while (d>0) do block([newdi: mod(d, base)], digits: cons(newdi, digits), d: round( (d - newdi) / base)), digits)$   dec2digits(123, 10); /* [1, 2, 3] */ dec2digits( 8, 2); /* [1, 0, 0, 0] */
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...
#Modula-2
Modula-2
MODULE Sequence; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE vc(n,base : INTEGER; VAR num,denom : INTEGER); VAR p,q : INTEGER; BEGIN p := 0; q := 1;   WHILE n#0 DO p := p * base + (n MOD base); q := q * base; n := n DIV base ...
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...
#Frink
Frink
URLDecode["google.com/search?q=%60Abdu%27l-Bah%C3%A1","UTF8"]
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...
#Go
Go
package main   import ( "fmt" "log" "net/url" )   func main() { for _, escaped := range []string{ "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", } { u, err := url.QueryUnescape(escaped) if err != nil { log.Println(err) continue } fmt.Println(u) } }
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...
#D
D
import std.algorithm : countUntil, each, map; import std.array : array; import std.conv : to; import std.range : empty, retro; import std.stdio : writeln; import std.string : strip; import std.typecons : tuple;   immutable LEFT_DIGITS = [ " ## #", " ## #", " # ##", " #### #", " # ##", " ...
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...
#Java
Java
import java.io.*; import java.util.*; import java.util.regex.*;   public class UpdateConfig {   public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required");   } else if (readConfig(args[0])) { enableOption("seedsremoved"); ...
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
#Elena
Elena
import extensions;   public program() { var num := new Integer(); console.write:"Enter an integer: ".loadLineTo:num;   var word := console.write:"Enter a String: ".readLine() }
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
#Elixir
Elixir
  a = IO.gets("Enter a string: ") |> String.strip b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer f = IO.gets("Enter a real number: ") |> String.strip |> String.to_float IO.puts "String = #{a}" IO.puts "Integer = #{b}" IO.puts "Float = #{f}"  
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
#J
J
SIMPLEGUI=: noun define pc simpleGui; cc IntegerLabel static;cn "Enter the integer 75000"; cc integer edit; cc TextLabel static;cn "Enter text"; cc text edit; cc accept button;cn "Accept"; pshow; )   simpleGui_run=: wd bind SIMPLEGUI simpleGui_close=: wd bind 'pclose' simpleGui_cancel=: simpleGui_close   simpleGui_acce...
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...
#jq
jq
# input: a decimal integer # output: the corresponding binary array, most significant bit first def binary_digits: if . == 0 then 0 else [recurse( if . == 0 then empty else ./2 | floor end ) % 2] | reverse | .[1:] # remove the leading 0 end ;   # Input: an array of binary digits, msb first. def binary_to_...
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...
#Julia
Julia
for t in ("A", "ö", "Ж", "€", "𝄞") enc = Vector{UInt8}(t) dec = String(enc) println(dec, " → ", enc) end
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...
#TXR
TXR
#include <stdio.h>   int query(int (*callback)(char *, size_t *)) { char buffer[1024]; size_t size = sizeof buffer;   if (callback(buffer, &size) == 0) { puts("query: callback failed"); } else { char *ptr = buffer;   while (size-- > 0) putchar (*ptr++); putchar('\n'); } }
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...
#Wren
Wren
/* query.wren */   class RCQuery { // Both arguments are lists as we need pass by reference here static query(Data, Length) { var s = "Here am I" var sc = s.count if (sc > Length[0]) return 0 // buffer too small for (i in 0...sc) Data[i] = s[i].bytes[0] Length[0] = sc ...
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...
#PowerShell
PowerShell
  function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject )   ...
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...
#JavaScript
JavaScript
var normal = 'http://foo/bar/'; var encoded = encodeURIComponent(normal);
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...
#jq
jq
"á" | @uri
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
#Forth
Forth
: hypot ( a b -- a^2 + b^2 ) LOCALS| b a | \ note: reverse order from the conventional stack comment b b * a a * + ;