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/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... | #REXX | REXX | /*REXX program converts an integer (or a range) ──► a Van der Corput number in base 2.*/
numeric digits 1000 /*handle almost anything the user wants*/
parse arg a b . /*obtain the optional arguments from CL*/
if a=='' then parse value 0 10 with a b... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Function decodeUrl$(a$) {
DIM a$()
a$()=Piece$(a$, "%")
if len(a$())=1 then =str$(a$):exit
k=each(a$(),2)
\\ convert to one byte per character using str$(string)
acc$=str$(a$(0))
While k {
... |
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... | #Maple | Maple | StringTools:-Decode("http%3A%2F%2Ffoo%20bar%2F", encoding=percent); |
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... | #Nim | Nim | import algorithm, sequtils, strutils
const
LeftDigits = [" ## #",
" ## #",
" # ##",
" #### #",
" # ##",
" ## #",
" # ####",
" ### ##",
" ## ###",
" # ##"]
... |
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... | #Racket | Racket |
#lang racket
(require "options.rkt")
(read-options "options-file")
(define-options needspeeling seedsremoved numberofbananas numberofstrawberries)
;; Disable the needspeeling option (using a semicolon prefix)
(set! needspeeling #f)
;; Enable the seedsremoved option by removing the semicolon and any
;; leading... |
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... | #Raku | Raku | conf-update --/needspeeling --seedsremoved --numberofbananas=1024 --numberofstrawberries=62000 test.cfg |
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
| #Icon_and_Unicon | Icon and Unicon |
procedure main ()
writes ("Enter something: ")
s := read ()
write ("You entered: " || s)
writes ("Enter 75000: ")
if (i := integer (read ())) then
write (if (i = 75000) then "correct" else "incorrect")
else write ("you must enter a number")
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
| #Io | Io | string := File clone standardInput readLine("Enter a string: ")
integer := File clone standardInput readLine("Enter 75000: ") asNumber |
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
| #Perl | Perl | use Wx;
package MyApp;
use base 'Wx::App';
use Wx qw(wxHORIZONTAL wxVERTICAL wxALL wxALIGN_CENTER);
use Wx::Event 'EVT_BUTTON';
our ($frame, $text_input, $integer_input);
sub OnInit
{$frame = new Wx::Frame
(undef, -1, 'Input window', [-1, -1], [250, 150]);
my $panel = new Wx::Panel($frame, -1);
... |
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... | #Python | Python |
#!/usr/bin/env python3
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'U... |
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... | #Racket | Racket | #lang racket
(define char-map
'((LATIN-CAPITAL-LETTER-A . #\U0041)
(LATIN-SMALL-LETTER-O-WITH-DIAERESIS . #\U00F6)
(CYRILLIC-CAPITAL-LETTER-ZHE . #\U0416)
(EURO-SIGN . #\U20AC)
(MUSICAL-SYMBOL-G-CLEF . #\U1D11E)))
(for ((name.char (... |
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... | #Oberon-2 | Oberon-2 |
MODULE URLEncoding;
IMPORT
Out := NPCT:Console,
ADT:StringBuffer,
URI := URI:String;
VAR
encodedUrl: StringBuffer.StringBuffer;
BEGIN
encodedUrl := NEW(StringBuffer.StringBuffer,512);
URI.AppendEscaped("http://foo bar/","",encodedUrl);
Out.String(encodedUrl.ToString());Out.Ln
END URLEncoding.
|
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... | #Objeck | Objeck |
use FastCgi;
bundle Default {
class UrlEncode {
function : Main(args : String[]) ~ Nil {
url := "http://foo bar/";
UrlUtility->Encode(url)->PrintLine();
}
}
}
|
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
| #Lambdatalk | Lambdatalk |
1) working in a global scope
{def A 3}
-> A // A is in the global scope
{def B 4}
-> B // B is in the global scopel
{def MUL {lambda {:x :y} {* :x :y}}}
-> MUL // MUL is a global function
{MUL {A} {B}} ... |
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 ... | #SNOBOL4 | SNOBOL4 | define('eck(n)i,j') :(eck_end)
eck eck = array(n,0)
i = 0
eouter i = lt(i,n - 1) i + 1 :f(return)
j = i
einner j = gt(j,0) j - 1 :f(eouter)
eck<i + 1> = eq(eck<i>,eck<j>) i - j :s(eouter)f(einner)
eck_end
defi... |
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 ... | #Sidef | Sidef | func van_eck(n) {
var seen = Hash()
var seq = [0]
var prev = seq[-1]
for k in (1 ..^ n) {
seq << (seen.has(prev) ? (k - seen{prev}) : 0)
seen{prev} = k
prev = seq[-1]
}
seq
}
say van_eck(10)
say van_eck(1000).slice(991-1, 1000-1) |
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... | #Ring | Ring |
# Project : Variadic function
sum([1,2])
sum([1,2,3])
nums = [1,2,3,4]
sum(nums)
func sum(nums)
total = 0
for num = 1 to len(nums)
total = total + num
next
showarray(nums)
see " " + total + nl
func showarray(vect)
see "["
svect = ""
for n = 1 to... |
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... | #Ruby | Ruby | def print_all(*things)
puts things
end |
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... | #Rust | Rust | // 20220106 Rust programming solution
macro_rules! print_all {
($($args:expr),*) => { $( println!("{}", $args); )* }
}
fn main() {
print_all!("Rosetta", "Code", "Is", "Awesome!");
} |
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... | #Java | Java | public class VectorProds{
public static class Vector3D<T extends Number>{
private T a, b, c;
public Vector3D(T a, T b, T c){
this.a = a;
this.b = b;
this.c = c;
}
public double dot(Vector3D<?> vec){
return (a.doubleValue() * vec.a.d... |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | Validate International Securities Identification Number | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Task
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, and the embedded c... | #VBScript | VBScript | ' Validate International Securities Identification Number - 03/03/2019
buf=buf&test("US0378331005")&vbCrLf
buf=buf&test("US0373831005")&vbCrLf
buf=buf&test("U50378331005")&vbCrLf
buf=buf&test("US03378331005")&vbCrLf
buf=buf&test("AU0000XVGZA3")&vbCrLf
buf=buf&test("AU0000VXGZA3")&vbCrLf
buf=buf&test("FR0000988040")&vb... |
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... | #Visual_Basic | Visual Basic | Function IsValidISIN(ByVal ISIN As String) As Boolean
Dim s As String, c As String
Dim i As Long
If Len(ISIN) = 12 Then
For i = 1 To Len(ISIN)
c = UCase$(Mid(ISIN, i, 1))
Select Case c
Case "A" To "Z"
If i = 12 Then Exit Function
s = s & CStr(Asc(c) - 55)
Case "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... | #Ring | Ring |
decimals(4)
for base = 2 to 5
see "base " + string(base) + " : "
for number = 0 to 9
see "" + corput(number, base) + " "
next
see nl
next
func corput n, b
vdc = 0
denom = 1
while n
denom *= b
rem = n % b
n = floor(n/b)
vdc += rem /... |
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... | #Ruby | Ruby | def vdc(n, base=2)
str = n.to_s(base).reverse
str.to_i(base).quo(base ** str.length)
end
(2..5).each do |base|
puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ")
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | URLDecoding[url_] :=
StringReplace[url, "%" ~~ x_ ~~ y_ :> FromDigits[x ~~ y, 16]] //.
StringExpression[x___, Longest[n__Integer], y___] :>
StringExpression[x, FromCharacterCode[{n}, "UTF8"], y] |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function u = urldecoding(s)
u = '';
k = 1;
while k<=length(s)
if s(k) == '%' && k+2 <= length(s)
u = sprintf('%s%c', u, char(hex2dec(s((k+1):(k+2)))));
k = k + 3;
else
u = sprintf('%s%c', u, s(k));
k = k + 1;
end
end
end |
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub decode_UPC {
my($line) = @_;
my(%pattern_to_digit_1,%pattern_to_digit_2,@patterns1,@patterns2,@digits,$sum);
for my $p (' ## #', ' ## #', ' # ##', ' #### #', ' # ##', ' ## #', ' # ####', ' ### ##', ' ## ###', ' # ##') {
push @patterns1... |
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... | #REXX | REXX | /*REXX program demonstrates how to update a configuration file (four specific tasks).*/
parse arg iFID oFID . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID= 'UPDATECF.TXT' /*Not given? Then use default.*/
if oFID=='' | oFID=="," then oFID='\TEMP\UPDAT... |
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
| #J | J | require 'misc' NB. load system script
prompt 'Enter string: '
0".prompt 'Enter an integer: ' |
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
| #Java | Java |
import java.util.Scanner;
public class GetInput {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
System.out.print("Enter an integer: ");
int i = Integer.parseIn... |
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
| #Phix | Phix | -- demo\rosetta\User_Input_Graphical.exw
include pGUI.e
Ihandle dlg, label1, input1, label2, input2, OK, Cancel
function ok_cb(Ihandle self)
if self=OK then
string in1 = IupGetAttribute(input1,"VALUE")
integer in2 = IupGetInt(input2,"VALUE")
string msg = sprintf(`"%s" and %d`,{in1,in2})
... |
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... | #Raku | Raku | say sprintf("%-18s %-36s|%8s| %7s |%14s | %s\n", 'Character|', 'Name', 'Ordinal', 'Unicode', 'UTF-8 encoded', 'decoded'), '-' x 100;
for < A ö Ж € 𝄞 😜 👨👩👧👦> -> $char {
printf " %-5s | %-43s | %6s | %-7s | %12s |%4s\n", $char, $char.uninames.join(','), $char.ords.join(' '),
('U+' X~ $char.ords».b... |
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... | #Objective-C | Objective-C | NSString *normal = @"http://foo bar/";
NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", 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... | #OCaml | OCaml | $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F" |
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
| #Lasso | Lasso | // declare thread variable, default type null
var(x)
$x->type // null
// declare local variable, default type null
local(x)
#x->type // null
// declare thread variable, initialize with a type, in this case integer
var(x = integer)
// declare local variable, initialize with a type, in this case integer
local(x = 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
| #Liberty_BASIC | Liberty BASIC |
'In Liberty BASIC variables are either string or numeric.
'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname).
'There is no practical limit to the length of a variable name... up to ~2M characters.
'The variable names are case sensitiv... |
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 ... | #Swift | Swift | struct VanEckSequence: Sequence, IteratorProtocol {
private var index = 0
private var lastTerm = 0
private var lastPos = Dictionary<Int, Int>()
mutating func next() -> Int? {
let result = lastTerm
var nextTerm = 0
if let v = lastPos[lastTerm] {
nextTerm = index - v
... |
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 ... | #Tcl | Tcl | ## Mathematically, the first term has index "0", not "1". We do that, also.
set ::vE 0
proc vanEck {n} {
global vE vEocc
while {$n >= [set k [expr {[llength $vE] - 1}]]} {
set kv [lindex $vE $k]
## value $kv @ $k is not yet stuffed into vEocc()
lappend vE [expr {[info exists vEocc($... |
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... | #Scala | Scala | def printAll(args: Any*) = args foreach println |
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... | #Scheme | Scheme | (define (print-all . things)
(for-each
(lambda (x) (display x) (newline))
things)) |
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... | #Sidef | Sidef | func print_all(*things) {
things.each { |x| say x };
} |
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... | #JavaScript | JavaScript | function dotProduct() {
var len = arguments[0] && arguments[0].length;
var argsLen = arguments.length;
var i, j = len;
var prod, sum = 0;
// If no arguments supplied, return undefined
if (!len) {
return;
}
// If all vectors not same length, return undefined
i = argsLen;
while (i--) {
i... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Option Strict On
Imports System.Text.RegularExpressions
Module Module1
ReadOnly IsinRegex As New Regex("^[A-Z]{2}[A-Z0-9]{9}\d$", RegexOptions.Compiled)
Function DigitValue(c As Char) As Integer
Dim temp As Integer
If Asc(c) >= Asc("0"c) AndAlso Asc(c) <= Asc("9"c) Then
temp = As... |
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... | #Rust | Rust |
/// Van der Corput sequence for any base, based on C languange example from Wikipedia.
pub fn corput(nth: usize, base: usize) -> f64 {
let mut n = nth;
let mut q: f64 = 0.0;
let mut bk: f64 = 1.0 / (base as f64);
while n > 0_usize {
q += ((n % base) as f64)*bk;
n /= base;
bk /= bas... |
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... | #Scala | Scala | object VanDerCorput extends App {
def compute(n: Int, base: Int = 2) =
Iterator.from(0).
scanLeft(1)((a, _) => a * base).
map(b => (n - 1) / b -> b).
takeWhile(_._1 != 0).
foldLeft(0d)((a, b) => a + (b._1 % base).toDouble / b._2 / base)
val n = scala.io.... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
url = [ -
'http%3A%2F%2Ffoo%20bar%2F', -
'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E', -
'%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' -
... |
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... | #Phix | Phix | with javascript_semantics
constant numbers = {" ## #", -- 0
" ## #", -- 1
" # ##", -- 2
" #### #", -- 3
" # ##", -- 4
" ## #", -- 5
" # ####", -- 6
" ### ##", -- 7
... |
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... | #Ruby | Ruby | require 'stringio'
class ConfigFile
# create a ConfigFile object from a file
def self.file(filename)
fh = File.open(filename)
obj = self.new(fh)
obj.filename = filename
fh.close
obj
end
# create a ConfigFile object from a string
def self.data(string)
fh = StringIO.new(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
| #JavaScript | JavaScript | WScript.Echo("Enter a string");
var str = WScript.StdIn.ReadLine();
var val = 0;
while (val != 75000) {
WScript.Echo("Enter the integer 75000");
val = parseInt( WScript.StdIn.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
| #Joy | Joy |
"Enter a string: " putchars
stdin fgets
"Enter a number: " putchars
stdin fgets 10 strtol.
|
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
| #PicoLisp | PicoLisp | (and
(call 'sh "-c"
(pack
"dialog \
--inputbox 'Input a string' 8 60 \
--inputbox 'Input a number' 8 20 \
2>"
(tmp "dlg") ) )
(split (in (tmp "dlg") (line)) "^I")
(cons (pack (car @)) (format (cadr @))) ) |
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
| #PowerBASIC | PowerBASIC | FUNCTION PBMAIN () AS LONG
result$ = INPUTBOX$("Enter a string.")
MSGBOX result$
DO
'This assumes that 75000 is the ONLY valid input.
result$ = INPUTBOX$("Enter the number 75000.")
IF VAL(result$) <> 75000 THEN
MSGBOX "You need to enter 75000!"
ELSE
MS... |
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... | #Ruby | Ruby |
character_arr = ["A","ö","Ж","€","𝄞"]
for c in character_arr do
puts "Character: " + c.encode("utf-8")
puts "Code-Point: #{c.encode("utf-8").ord.to_s(16).upcase}"
puts "Code-Units: " + c.each_byte.map { |n| '%02X ' % (n & 0xFF) }.join
puts ""
end
|
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... | #Rust | Rust | fn main() {
let chars = vec!('A', 'ö', 'Ж', '€', '𝄞');
chars.iter().for_each(|c| {
let mut encoded = vec![0; c.len_utf8()];
c.encode_utf8(&mut encoded);
let decoded = String::from_utf8(encoded.to_vec()).unwrap();
let encoded_string = encoded.iter().fold(String::new(), |acc, val|... |
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... | #ooRexx | ooRexx | sub urlencode {
my $s = shift;
$s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg;
$s =~ tr/ /+/;
return $s;
}
print urlencode('http://foo bar/')."\n";
|
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... | #Perl | Perl | sub urlencode {
my $s = shift;
$s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg;
$s =~ tr/ /+/;
return $s;
}
print urlencode('http://foo bar/')."\n";
|
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Lingo | Lingo | x = 23
y = "Hello world!"
z = TRUE -- same effect as z = 1 |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Logo | Logo | make "g1 0
name 2 "g2 ; same as make with parameters reversed
global "g3 ; no initial value
to func :x
make "g4 4 ; still global
localmake "L1 6
local ["L2 "L3] ; local variables, collection syntax
func2 :g4
print :L2 ; 9, modified by func2
print :L3 ; L3 has no value, was not modifie... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Linq
Module Module1
Dim h() As Integer
Sub sho(i As Integer)
Console.WriteLine(String.Join(" ", h.Skip(i).Take(10)))
End Sub
Sub Main()
Dim a, b, c, d, f, g As Integer : g = 1000
h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g
f = h(b) : For d = a... |
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 ... | #Vlang | Vlang | fn main() {
max := 1000
mut a := []int{len: max} // all zero by default
for n in 0..max-1 {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
println("The first ten terms of the Van Eck sequence are... |
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... | #Slate | Slate | define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].
printAll applyTo: #(4 3 5 6 4 3).
printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!'). |
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... | #Swift | Swift | func printAll<T>(things: T...) {
// "things" is a [T]
for i in things {
print(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... | #Tcl | Tcl | proc print_all {args} {puts [join $args \n]}
print_all 4 3 5 6 4 3
print_all 4 3 5
print_all Rosetta Code Is Awesome!
set things {Rosetta Code Is Awesome!}
print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all
print_all {*}$things ;# ==> correct: passes each element of the list to the... |
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... | #jq | jq | def dot_product(a; b):
reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );
# for 3d vectors
def cross_product(a;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] ];
def scalar_triple_product(a;b;c):
dot_product(a; cross_product(b; c));
def vector_triple_product(a;b;c):
cross_pr... |
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... | #Vlang | Vlang | import regex
const (
inc = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9],
]
)
fn valid_isin(n string) bool {
mut r,_,_ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\d$')
if !r.matches_string(n) {
return false
}
mut sum := 0
mut p := 0
for i := 1... |
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... | #Wren | Wren | import "/str" for Char
import "/trait" for Stepped
import "/fmt" for Conv, Fmt
var luhn = Fn.new { |s|
s = s[-1..0]
var s1 = Stepped.new(s, 2).reduce(0) { |sum, d| sum + d.bytes[0] - 48 }
var s2 = Stepped.new(s[1..-1], 2).reduce(0) { |sum, d|
var d2 = (d.bytes[0] - 48) * 2
return sum + ((... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: vdc (in var integer: number, in integer: base) is func
result
var float: vdc is 0.0;
local
var integer: denom is 1;
var integer: remainder is 0;
begin
while number <> 0 do
denom *:= base;
remainder := number rem base;... |
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... | #Sidef | Sidef | func vdc(value, base=2) {
while (value[-1] > 0) {
value.append(value[-1] / base -> int)
}
var (x, sum) = (1, 0)
value.each { |i|
sum += ((i % base) / (x *= base))
}
return sum
}
for base in (2..5) {
var seq = 10.of {|i| vdc([i], base) }
"base %d: %s\n".printf(base, seq.... |
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... | #NewLISP | NewLISP | ;; universal decoder, works for ASCII and UTF-8
;; (source http://www.newlisp.org/index.cgi?page=Code_Snippets)
(define (url-decode url (opt nil))
(if opt (replace "+" url " "))
(replace "%([0-9a-f][0-9a-f])" url (pack "b" (int $1 0 16)) 1))
(url-decode "http%3A%2F%2Ffoo%20bar%2F") |
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... | #Nim | Nim | import cgi
echo decodeUrl("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... | #PicoLisp | PicoLisp | (de l2n (Lst)
(case Lst
((0 0 0 1 1 0 1) 0)
((0 0 1 1 0 0 1) 1)
((0 0 1 0 0 1 1) 2)
((0 1 1 1 1 0 1) 3)
((0 1 0 0 0 1 1) 4)
((0 1 1 0 0 0 1) 5)
((0 1 0 1 1 1 1) 6)
((0 1 1 1 0 1 1) 7)
((0 1 1 0 1 1 1) 8)
((0 0 0 1 0 1 1) 9) ) )
(de convs (Lst Flg)
(make
... |
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... | #Tcl | Tcl | package require Tcl 8.6
oo::class create Config {
variable filename contents
constructor fileName {
set filename $fileName
set contents {}
try {
set f [open $filename]
### Sanitize during input
foreach line [split [read $f] \n] {
if {[string match "#*" $line]} {
lappend contents $line
... |
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
| #jq | jq | def read(int):
null | until( . == int; "Expecting \(int)" | stderr | input);
def read_string:
null | until( type == "string"; "Please enter a string" | stderr | input);
(read_string | "I see the string: \(.)"),
(read(75000) | "I see the expected integer: \(.)") |
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
| #Julia | Julia |
print("String? ")
y = readline()
println("Your input was \"", y, "\".\n")
print("Integer? ")
y = readline()
try
y = parse(Int, y)
println("Your input was \"", y, "\".\n")
catch
println("Sorry, but \"", y, "\" does not compute as an integer.")
end
|
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
| #PowerShell | PowerShell | #region Define the Windows Form
[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form1 = New-Object System.Windows.Forms.Form
$label1 = New-Object System.Windows.Forms.Label
$label2 = New-Object System.Windows.Forms.Label
$txtInputText = New-Object System.Windows.Forms.TextBox
$txtInputNumber... |
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... | #Scala | Scala | object UTF8EncodeAndDecode extends App {
val codePoints = Seq(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E)
def utf8Encode(codepoint: Int): Array[Byte] =
new String(Array[Int](codepoint), 0, 1).getBytes(StandardCharsets.UTF_8)
def utf8Decode(bytes: Array[Byte]): Int =
new String(bytes, StandardCharsets.U... |
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... | #Phix | Phix | --
-- demo\rosetta\encode_url.exw
-- ===========================
--
with javascript_semantics
function nib(integer b)
return b+iff(b<=9?'0':'A'-10)
end function
function encode_url(string s, string exclusions="", integer spaceplus=0)
string res = ""
for i=1 to length(s) do
integer ch = s[i]
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
| #LotusScript | LotusScript | Sub Click()
'a few declarations as example
Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession
Dim i as Integer ' i = 0
Dim s as String ' s= ""
Dim v as Variant ' v is nothing
Dim l as Long ' l = 0
Dim doc as NotesDocument 'doc is EMTPY
'...
End Sub
|
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
| #Lua | Lua | a = 1 -- Here we declare a numeric variable
fruit = "banana" -- Here we declare a string datatype
needspeeling = True -- This is a boolean
local b = 2 -- This variable declaration is prefixed with a scope modifier |
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 ... | #Wren | Wren | var max = 1000
var a = List.filled(max, 0)
var seen = {}
for (n in 0...max-1) {
var m = seen[a[n]]
if (m != null) a[n+1] = n - m
seen[a[n]] = n
}
System.print("The first ten terms of the Van Eck sequence are:")
System.print(a[0...10])
System.print("\nTerms 991 to 1000 of the sequence are:")
System.print(a[9... |
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 ... | #XPL0 | XPL0 | int Seq(1001), Back, N, M, Term;
func New; \Return 'true' if last term is new to sequence
[for Back:= N-2 downto 1 do
if Seq(Back) = Seq(N-1) then return false;
return true;
];
func VanEck; \Return term of Van Eck sequence
[Seq(N):= if New then 0 else N-Back-1;
N:= N+1;
return Seq(N-1);
];
[N:= 1... |
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... | #TIScript | TIScript |
function printAll(separator,argv..) {
if(argv.length)
stdout.print(argv[0]);
for (var i=1; i < argv.length; i++)
stdout.print(separator, argv[i]);
}
printAll(" ", 4, 3, 5, 6, 4, 3);
printAll(",", 4, 3, 5);
printAll("! ","Rosetta", "Code", "Is", "Awesome"); |
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... | #uBasic.2F4tH | uBasic/4tH | Push _Mary, _had, _a, _little, _lamb ' Push the hashes
Proc _PrintStrings (5) ' Print the string
Push 1, 4, 5, 19, 12, 3 ' Push the numbers
Print "Maximum is: ";FUNC(_Max(6)) ' Call the function
End
_PrintStrings Param(1) ' Print a variadic number of strings
... |
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... | #Julia | Julia | using LinearAlgebra
const a = [3, 4, 5]
const b = [4, 3, 5]
const c = [-5, -12, -13]
println("Test Vectors:")
@show a b c
println("\nVector Products:")
@show a ⋅ b
@show a × b
@show a ⋅ (b × c)
@show a × (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... | #XPL0 | XPL0 | string 0; \use zero-terminated strings
func Luhn(Str); \Return 'true' if digits in Str pass Luhn test
char Str;
int Len, Sum, I, Dig;
[Len:= 0; \find length of Str
while Str(Len) do Len:= Len+1;
Sum:= 0; \sum even and odd digits
for I:= 0 to Len-1 do \(no ne... |
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... | #Yabasic | Yabasic | sub luhntest(cardnr$)
local i, j, s1, s2, l
cardnr$ = Trim$(cardnr$) // remove spaces
l = Len(cardnr$)
// sum odd numbers
For i = l To 1 Step -2
s1 = s1 + (asc(mid$(cardnr$, i, 1)) - Asc("0"))
Next
// sum even numbers
For i = l-1 To 1 Step -2
j = asc(mid$(cardnr$, i... |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #Stata | Stata | mata
// 5th term of Van der Corput sequence
halton(1,1,5)
.625
// the first 10 terms of Van der Corput sequence
halton(10,1)
1
+---------+
1 | .5 |
2 | .25 |
3 | .75 |
4 | .125 |
5 | .625 |
6 | .375 |
7 | .875 |
8 | .0625 |
9 | .5625 |
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... | #Swift | Swift | func vanDerCorput(n: Int, base: Int, num: inout Int, denom: inout Int) {
var n = n, p = 0, q = 1
while n != 0 {
p = p * base + (n % base)
q *= base
n /= base
}
num = p
denom = q
while p != 0 {
n = p
p = q % p
q = n
}
num /= q
denom /= q
}
var num = 0
var denom = 0
f... |
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... | #Oberon-2 | Oberon-2 |
MODULE URLDecoding;
IMPORT
URI := URI:String,
Out := NPCT:Console;
BEGIN
Out.String(URI.Unescape("http%3A%2F%2Ffoo%20bar%2F"));Out.Ln;
Out.String(URI.Unescape("google.com/search?q=%60Abdu%27l-Bah%C3%A1"));Out.Ln;
END URLDecoding.
|
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... | #Objeck | Objeck |
class UrlDecode {
function : Main(args : String[]) ~ Nil {
Net.UrlUtility->Decode("http%3A%2F%2Ffoo%20bar%2F")->PrintLine();
}
}
|
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... | #Python | Python | """UPC-A barcode reader. Requires Python =>3.6"""
import itertools
import re
RE_BARCODE = re.compile(
r"^(?P<s_quiet> +)" # quiet zone
r"(?P<s_guard># #)" # start guard
r"(?P<left>[ #]{42})" # left digits
r"(?P<m_guard> # # )" # middle guard
r"(?P<right>[ #]{42})" # right digits
r"(?P<e_g... |
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... | #TXR | TXR | VAR # define or update VAR as a true-valued boolean
VAR= # ensure "; VAR" in the config file.
VAR=VAL # ensure "VAR VAL" in the config file |
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... | #VBScript | VBScript |
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Paramater lookups
Set objParamLookup = CreateObject("Scripting.Dictionary")
With objParamLookup
.Add "FAVOURITEFRUIT", "banana"
.Add "NEEDSPEELING", ""
.Add "SEEDSREMOVED", ""
.Add "NUMBEROFBANANAS", "1024"
.Add "NUMBEROFSTRAWBERRIES", "62000"
End With
... |
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
| #Kite | Kite |
System.file.stdout|write("Enter a String ");
string = System.file.stdin|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
| #Kotlin | Kotlin | // version 1.1
fun main(args: Array<String>) {
print("Enter a string : ")
val s = readLine()!!
println(s)
do {
print("Enter 75000 : ")
val number = readLine()!!.toInt()
} while (number != 75000)
} |
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
| #Processing | Processing | import javax.swing.JOptionPane;
int number = int(JOptionPane.showInputDialog ("Enter an Integer"));
println(number);
String string = JOptionPane.showInputDialog ("Enter a String");
println(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
| #PureBasic | PureBasic | string$=InputRequester("Some Title","Enter a string","")
variable=Val(InputRequester("Some other Title","Enter a 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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "unicode.s7i";
include "console.s7i";
include "bytedata.s7i";
const proc: main is func
local
var char: ch is ' ';
var string: utf8 is "";
begin
OUT := STD_CONSOLE;
writeln("Character Unicode UTF-8 encoding (hex) Decoded");
writeln("-------------------... |
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... | #Sidef | Sidef | func utf8_encoder(Number code) {
code.chr.encode('UTF-8').bytes.map{.chr}
}
func utf8_decoder(Array bytes) {
bytes.map{.ord}.decode('UTF-8')
}
for n in ([0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E]) {
var encoded = utf8_encoder(n)
var decoded = utf8_decoder(encoded)
assert_eq(n, decoded.ord)
sa... |
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... | #PHP | PHP | <?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.