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/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...
#BaCon
BaCon
FUNCTION Url_Decode$(url$)   LOCAL result$   SPLIT url$ BY "%" TO item$ SIZE total FOR x = 1 TO total-1 result$ = result$ & CHR$(DEC(LEFT$(item$[x], 2))) & MID$(item$[x], 3) NEXT RETURN item$[0] & result$   END FUNCTION   PRINT Url_Decode$("http%3A%2F%2Ffoo%20bar%2F") PRINT Url_Decode$("goog...
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...
#BBC_BASIC
BBC BASIC
PRINT FNurldecode("http%3A%2F%2Ffoo%20bar%2F") END   DEF FNurldecode(url$) LOCAL i% REPEAT i% = INSTR(url$, "%", i%+1) IF i% THEN url$ = LEFT$(url$,i%-1) + \ \ CHR$EVAL("&"+FNupper(MID$(url$,i%+1,2))) + \ \ MID$(url$,i%+3) END...
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...
#BASIC
BASIC
  ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Read a Configuration File V1.0 ' ' ' ' Developed by A. David Garza Marín in VB-DOS for ' ' RosettaCode. December 2, 2016. ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ...
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
#AWK
AWK
~/src/opt/run $ awk 'BEGIN{printf "enter a string: "}{s=$0;i=$0+0;print "ok,"s"/"i}' enter a string: hello world ok,hello world/0 75000 ok,75000/75000
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
#Axe
Axe
Disp "String:" input→A length(A)→L   .Copy the string to a safe location Copy(A,L₁,L)   .Display the string Disp "You entered:",i For(I,0,L-1) Disp {L₁+I}►Char End Disp i   Disp "Integer:",i input→B length(B)→L   .Parse the string and convert to an integer 0→C For(I,0,L-1) {B+I}-'0'→N If N>10 .Error checking Dis...
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
#BaCon
BaCon
OPTION GUI TRUE PRAGMA GUI gtk3   DECLARE text TYPE STRING DECLARE data TYPE FLOATING   gui = GUIDEFINE(" \ { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \ { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \ { type=ENTRY name=entry parent=b...
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
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB2" INSTALL @lib$+"WINLIB5" ES_NUMBER = 8192   form% = FN_newdialog("Rosetta Code", 100, 100, 100, 64, 8, 1000) PROC_static(form%, "String:", 100, 8, 8, 30, 14, 0) PROC_editbox(form%, "Example", 101, 40, 6, 52, 14, 0) PROC_static(form%, "Number:", 102, 8, 26...
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...
#BaCon
BaCon
DECLARE x TYPE STRING   CONST letter$ = "A ö Ж € 𝄞"   PRINT "Char", TAB$(1), "Unicode", TAB$(2), "UTF-8 (hex)" PRINT "-----------------------------------"   FOR x IN letter$ PRINT x, TAB$(1), "U+", HEX$(UCS(x)), TAB$(2), COIL$(LEN(x), HEX$(x[_-1] & 255)) NEXT
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...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <inttypes.h>   typedef struct { char mask; /* char data will be bitwise AND with this */ char lead; /* start bytes of current char in utf-8 encoded character */ uint32_t beg; /* beginning of codepoint range */ uint32_t end; /* end of codepoint range */ int bi...
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...
#Haskell
Haskell
#ifdef __GLASGOW_HASKELL__ #include "Called_stub.h" extern void __stginit_Called(void); #endif #include <stdio.h> #include <HsFFI.h>   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   hs_init(&argc, &argv); #ifdef __GLASGOW_HASKELL__ hs_add_root(__stginit_...
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...
#Haxe
Haxe
untyped __call__("functionName", args);
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...
#J
J
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m )   uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment )   queryparts=:3 :0 (0<#y)#<;._1 '?',y )   authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}....
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...
#Clojure
Clojure
(import 'java.net.URLEncoder) (URLEncoder/encode "http://foo bar/" "UTF-8")
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
#COBOL
COBOL
MOVE 5 TO x MOVE FUNCTION SOME-FUNC(x) TO y MOVE "foo" TO z MOVE "values 1234" TO group-item SET some-index TO 5
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 ...
#Dyalect
Dyalect
let max = 1000 var a = Array.Empty(max, 0) for n in 0..(max-2) { var m = n - 1 while m >= 0 { if a[m] == a[n] { a[n+1] = n - m break } m -= 1 } } print("The first ten terms of the Van Eck sequence are: \(a[0..10].ToArray())") print("Terms 991 to 1000 of the se...
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 ...
#F.23
F#
  // Generate Van Eck's Sequence. Nigel Galloway: June 19th., 2019 let ecK()=let n=System.Collections.Generic.Dictionary<int,int>() Seq.unfold(fun (g,e)->Some(g,((if n.ContainsKey g then let i=n.[g] in n.[g]<-e;e-i else n.[g]<-e;0),e+1)))(0,0)  
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...
#Kotlin
Kotlin
// version 1.1   data class Fangs(val fang1: Long = 0L, val fang2: Long = 0L)   fun pow10(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("Can't be negative") else -> { var pow = 1L for (i in 1..n) pow *= 10L pow } }   fun countDigits(n: Long): Int = when { n < 0L ...
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...
#Klingphix
Klingphix
:varfunc 1 tolist flatten len [ get print nl ] for drop ;   "Enter any number of words separated by space: " input nl stklen [split varfunc nl] if   nl "End " input
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...
#Kotlin
Kotlin
// version 1.1   fun variadic(vararg va: String) { for (v in va) println(v) }   fun main(args: Array<String>) { variadic("First", "Second", "Third") println("\nEnter four strings for the function to print:") val va = Array(4) { "" } for (i in 1..4) { print("String $i = ") va[i - 1] =...
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#zkl
zkl
(123).len() //-->1 (byte) (0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int (1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float "this is a test".len() //-->14 L(1,2,3,4).len() //-->4 Dictionary("1",1, "2",2).len() //-->2 (keys) Data(0,Int,1,2,3,4).len() //-->4 (bytes) Data(0,Stri...
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...
#Racket
Racket
#lang racket   (require racket/flonum)   (define (rad->deg x) (fl* 180. (fl/ (exact->inexact x) pi)))   ;Custom printer ;no shared internal structures (define (vec-print v port mode) (write-string "Vec:\n" port) (write-string (format " -Slope: ~a\n" (vec-slope v)) port) (write-string (format " -Angle(deg): ~a\n...
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...
#Raku
Raku
class Vector { has Real $.x; has Real $.y;   multi submethod BUILD (:$!x!, :$!y!) { * } multi submethod BUILD (:$length!, :$angle!) { $!x = $length * cos $angle; $!y = $length * sin $angle; } multi submethod BUILD (:from([$x1, $y1])!, :to([$x2, $y2])!) { $!x =...
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 ...
#Racket
Racket
  #lang racket (define chr integer->char) (define ord char->integer)   (define (encrypt msg key) (define cleaned (list->string (for/list ([c (string-upcase msg)] #:when (char-alphabetic? c)) c))) (list->string (for/list ([c cleaned] [k (in-cycle key)]) (chr (+ (modulo (+ (ord c) (o...
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 ...
#Raku
Raku
sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 } sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }   sub blacken ($red, $key) { v2s(s2v($red) »+» s2v($key)) } sub redden ($blk, $key) { v2s(s2v($blk) »-» s2v($key)) }   my $red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; my $key = "V...
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...
#EchoLisp
EchoLisp
  (lib 'math)   (define (scalar-triple-product a b c) (dot-product a (cross-product b c)))   (define (vector-triple-product a b c) (cross-product a (cross-product b c)))   (define a #(3 4 5)) (define b #(4 3 5)) (define c #(-5 -12 -13))   (cross-product a b) → #( 5 5 -7) (dot-product a b) → 49 (scalar-tripl...
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...
#Haskell
Haskell
module ISINVerification2 where   import Data.Char (isUpper, isDigit, digitToInt)   verifyISIN :: String -> Bool verifyISIN isin = correctFormat isin && mod (oddsum + multiplied_even_sum) 10 == 0 where reverted = reverse $ convertToNumber isin theOdds = fst $ collectOddandEven reverted theEvens = snd $ c...
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...
#Forth
Forth
: fvdc ( base n -- f ) 0e 1e ( F: vdc denominator ) begin dup while over s>d d>f f* over /mod ( base rem n ) swap s>d d>f fover f/ frot f+ fswap repeat 2drop fdrop ;   : test 10 0 do 2 i fvdc cr f. loop ;
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...
#Fortran
Fortran
FUNCTION VDC(N,BASE) !Calculates a Van der Corput number... Converts 1234 in decimal to 4321 in V, and P = 10000. INTEGER N !For this integer, INTEGER BASE !In this base. INTEGER I !A copy of N that can be damaged. INTEGER P !Successive powers of BASE. INTEGER V !Accumulates dig...
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...
#Bracmat
Bracmat
( ( decode = decoded hexcode notencoded .  :?decoded & whl ' ( @(!arg:?notencoded "%" (% %:?hexcode) ?arg) & !decoded !notencoded chr$(x2d$!hexcode):?decoded ) & str$(!decoded !arg) ) & out$(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...
#C
C
#include <stdio.h> #include <string.h>   inline int ishex(int x) { return (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F'); }   int decode(const char *s, char *dec) { char *o; const char *end = s + strlen(s); int c;   for (o = dec; s <= end; o++) { c = *s++; if (c == '+') c = ' ';...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define strcomp(X, Y) strcasecmp(X, Y)   struct option { const char *name, *value; int flag; };   /* TODO: dynamically obtain these */ struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUM...
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
#BASIC
BASIC
INPUT "Enter a string"; s$ INPUT "Enter a number: ", i%
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
#Batch_File
Batch File
@echo off set /p var= echo %var% 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
#C
C
#include <gtk/gtk.h>   void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg;   gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);   msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==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...
#C.23
C#
using System; using System.Text;   namespace Rosetta { class Program { static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint)); static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes); static void Main(string[] args) ...
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...
#J
J
  query=:3 :'0&#^:(y < #)''Here am I'''  
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...
#Java
Java
/* Query.java */ public class Query { public static boolean call(byte[] data, int[] length) throws java.io.UnsupportedEncodingException { String message = "Here am I"; byte[] mb = message.getBytes("utf-8"); if (length[0] < mb.length) return false; length[0] = mb.length; System.arraycopy(mb, 0, data, ...
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...
#Java
Java
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo://example.com:8042/over/there?name=ferret#nose"); parseAddress("urn:example:animal:ferret:nose"); }   static void parseAddress(String 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...
#ColdFusion
ColdFusion
(defun needs-encoding-p (char) (not (digit-char-p char 36)))   (defun encode-char (char) (format nil "%~2,'0X" (char-code char)))   (defun url-encode (url) (apply #'concatenate 'string (map 'list (lambda (char) (if (needs-encoding-p char) (encode-char 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...
#Common_Lisp
Common Lisp
(defun needs-encoding-p (char) (not (digit-char-p char 36)))   (defun encode-char (char) (format nil "%~2,'0X" (char-code char)))   (defun url-encode (url) (apply #'concatenate 'string (map 'list (lambda (char) (if (needs-encoding-p char) (encode-char char)...
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
#Common_Lisp
Common Lisp
(defparameter *x* nil "nothing")
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
#D
D
  float bite = 36.321; ///_Defines a floating-point number (float), "bite", with a value of 36.321 float[3] bites; ///_Defines a static array of 3 floats float[] more_bites; ///_Defines a dynamic array of floats  
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 ...
#Factor
Factor
USING: assocs fry kernel make math namespaces prettyprint sequences ;   : van-eck ( n -- seq ) [ 0 , 1 - H{ } clone '[ building get [ length 1 - ] [ last ] bi _ 3dup 2dup key? [ at - ] [ 3drop 0 ] if , set-at ] times ] { } make ;   1000 van-eck 10 [ head ] [ tail* ] 2bi [...
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 ...
#Fortran
Fortran
program VanEck implicit none integer eck(1000), i, j   eck(1) = 0 do 20 i=1, 999 do 10 j=i-1, 1, -1 if (eck(i) .eq. eck(j)) then eck(i+1) = i-j go to 20 end if 10 continue eck(i+1) = 0 20 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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[VampireQ] VampireQ[num_Integer] := Module[{poss, divs}, divs = Select[Divisors[num], # <= Sqrt[num] &]; poss = {#, num/#} & /@ divs; If[Length[poss] > 0, poss = Select[poss, Mod[#, 10] =!= {0, 0} &]; If[Length[poss] > 0, poss = Select[poss, Length[IntegerDigits[First[#]]] == Length[IntegerDigit...
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...
#Nim
Nim
import algorithm, math, sequtils, strformat, strutils, sugar   const Pow10 = collect(newSeq, for n in 0..18: 10 ^ n)   template isOdd(n: int): bool = (n and 1) != 0   proc fangs(n: Positive): seq[(int, int)] = ## Return the list fo fangs of "n" (empty if "n" is not vampiric). let nDigits = sorted($n) if nDigits.l...
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...
#Ksh
Ksh
  #!/bin/ksh   # Variadic function   # # Variables: # typeset -a arr=( 0 2 4 6 8 )   # # Functions: # function _variadic { while [[ -n $1 ]]; do print $1 shift done }   ###### # main # ######   _variadic Mary had a little lamb echo _variadic ${arr[@]}
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...
#Lambdatalk
Lambdatalk
  {def foo {lambda {:s} {if {S.empty? {S.rest :s}} then {br}{S.first :s} else {br}{S.first :s} {foo {S.rest :s}}}}}   {foo hello brave new world} -> hello brave new world   {foo {S.serie 1 10}} -> 1 2 3 4 5 6 7 8 9 10    
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...
#Red
Red
Red [ Source: https://github.com/vazub/rosetta-red Tabs: 4 ]   comment { Vector type is one of base datatypes in Red, with all arithmetic already implemented.   Caveats to keep in mind: - Arithmetic on a single vector will modify the vector in place, so we use copy to avoid that - Division result on int...
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...
#REXX
REXX
/*REXX program shows how to support mathematical functions for vectors using functions. */ s1 = 11 /*define the s1 scalar: eleven */ s2 = 2 /*define the s2 scalar: two */ x = '(5, 7)' ...
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 ...
#Red
Red
red.exe -c vign1.red
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 ...
#REXX
REXX
/*REXX program encrypts (and displays) uppercased text using the Vigenère cypher.*/ @.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' L=length(@.1) do j=2 to L; jm=j-1; q=@.jm @.j=substr(q, 2, L - 1)left(q, 1) end /*j*/   cy...
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...
#Elixir
Elixir
defmodule Vector do def dot_product({a1,a2,a3}, {b1,b2,b3}), do: a1*b1 + a2*b2 + a3*b3   def cross_product({a1,a2,a3}, {b1,b2,b3}), do: {a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1}   def scalar_triple_product(a, b, c), do: dot_product(a, cross_product(b, c))   def vector_triple_product(a, b, c), do: cross_prod...
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...
#J
J
require'regex' validFmt=: 0 -: '^[A-Z]{2}[A-Z0-9]{9}[0-9]{1}$'&rxindex   df36=: ;@([: <@":"0 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'&i.) NB. decimal from base 36 luhn=: 0 = 10 (| +/@,) 10 #.inv 1 2 *&|: _2 "."0\ |. NB. as per task Luhn_test_of_credit_card_numbers#J   validISIN=: validFmt *. luhn@df36
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...
#Java
Java
public class ISIN {   public static void main(String[] args) { String[] isins = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" }; for (S...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#FreeBASIC
FreeBASIC
' version 03-12-2016 ' compile with: fbc -s console   Function num_base(number As ULongInt, _base_ As UInteger) As String   If _base_ > 9 Then Print "base not handled by function" Sleep 5000 Return "" End If   Dim As ULongInt n Dim As String ans   While number <> 0 n ...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func v2(n uint) (r float64) { p := .5 for n > 0 { if n&1 == 1 { r += p } p *= .5 n >>= 1 } return }   func newV(base uint) func(uint) float64 { invb := 1 / float64(base) return func(n uint) (r float64) { p := invb ...
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...
#C.23
C#
using System;   namespace URLEncode { internal class Program { private static void Main(string[] args) { Console.WriteLine(Decode("http%3A%2F%2Ffoo%20bar%2F")); }   private static string Decode(string uri) { return Uri.UnescapeDataString(uri); ...
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...
#C.2B.2B
C++
#include <string> #include "Poco/URI.h" #include <iostream>   int main( ) { std::string encoded( "http%3A%2F%2Ffoo%20bar%2F" ) ; std::string decoded ; Poco::URI::decode ( encoded , decoded ) ; std::cout << encoded << " is decoded: " << decoded << " !" << std::endl ; return 0 ; }
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...
#D
D
import std.stdio, std.file, std.string, std.regex, std.path, std.typecons;   final class Config { enum EntryType { empty, enabled, disabled, comment, ignore }   static protected struct Entry { EntryType type; string name, value; } protected Entry[] entries; protected string pa...
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
#BBC_BASIC
BBC BASIC
INPUT LINE "Enter a string: " string$ INPUT "Enter a number: " number   PRINT "String = """ string$ """" PRINT "Number = " ; number
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Befunge
Befunge
<>:v:"Enter a string: " ^,_ >~:1+v ^ _@
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
#C.2B.2B
C++
task.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
#Clojure
Clojure
(import 'javax.swing.JOptionPane) (let [number (-> "Enter an Integer" JOptionPane/showInputDialog Integer/parseInt) string (JOptionPane/showInputDialog "Enter a String")] [number 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...
#Common_Lisp
Common Lisp
  (defun ascii-byte-p (octet) "Return t if octet is a single-byte 7-bit ASCII char. The most significant bit is 0, so the allowed pattern is 0xxx xxxx." (assert (typep octet 'integer)) (assert (<= (integer-length octet) 8)) (let ((bitmask #b10000000) (template #b00000000)) ;; bitwise and the with...
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...
#Kotlin
Kotlin
// Kotlin Native v0.6   import kotlinx.cinterop.* import platform.posix.*   fun query(data: CPointer<ByteVar>, length: CPointer<size_tVar>): Int { val s = "Here am I" val strLen = s.length val bufferSize = length.pointed.value if (strLen > bufferSize) return 0 // buffer not large enough for (i in 0...
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...
#Lisaac
Lisaac
Section Header   + name := QUERY; - external := `#define main _query_main`; - external := `#define query Query`;   Section External   - query(buffer : NATIVE_ARRAY[CHARACTER], size : NATIVE_ARRAY[INTEGER]) : INTEGER <- ( + s : STRING_CONSTANT; + len, result : INTEGER; s := "Here am I"; len := s.count; (len > ...
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...
#JavaScript
JavaScript
(function (lstURL) {   var e = document.createElement('a'), lstKeys = [ 'hash', 'host', 'hostname', 'origin', 'pathname', 'port', 'protocol', 'search' ],   fnURLParse = function (strURL) { ...
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...
#Crystal
Crystal
require "uri"   puts URI.encode("http://foo bar/") puts URI.encode("http://foo bar/", space_to_plus: true) puts URI.encode_www_form("http://foo bar/") puts URI.encode_www_form("http://foo bar/", space_to_plus: false)
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...
#D
D
import std.stdio, std.uri;   void main() { writeln(encodeComponent("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
#DBL
DBL
; ; Variables examples for DBL version 4 by Dario B. ;   .DEFINE NR,10  ;const .DEFINE AP,"PIPPO"  ;const     RECORD CUSTOM COD, D5 NAME, A80 ZIP, D6 CITY, A80 ;-----------------------   RECORD   ALPHA, A5  ;alphanumeric NUMBR, D5  ;number DECML, F5....
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
#Delphi
Delphi
var i: Integer; s: string; o: TObject; begin i := 123; s := 'abc'; o := TObject.Create; try // ... finally o.Free; end; end;
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 ...
#FreeBASIC
FreeBASIC
  Const limite = 1000   Dim As Integer a(limite), n, m, i   For n = 0 To limite-1 For m = n-1 To 0 Step -1 If a(m) = a(n) Then a(n+1) = n-m: Exit For Next m Next n   Print "Secuencia de Van Eck:" &Chr(10) Print "Primeros 10 terminos: "; For i = 0 To 9 Print a(i) &" "; Next i Print Chr(10) & "Termino...
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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func main() { const max = 1000 a := make([]int, max) // all zero by default for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("...
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...
#PARI.2FGP
PARI/GP
fang(n)=my(v=digits(n),u=List());if(#v%2,return([]));fordiv(n,d,if(#Str(d)==#v/2 && #Str(n/d)==#v/2 && vecsort(v)==vecsort(concat(digits(d),digits(n/d))) && (d%10 || (n/d)%10), if(d^2>n,return(Vec(u))); listput(u, d))); Vec(u) k=25;forstep(d=4,6,2,for(n=10^(d-1),10^d-1,f=fang(n); for(i=1,#f,print(n" "f[i]" "n/f[i]); if...
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...
#Lasso
Lasso
define printArgs(...items) => stdoutnl(#items) define printEachArg(...) => with i in #rest do stdoutnl(#i)   printArgs('a', 2, (:3)) printEachArg('a', 2, (:3))
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Logo
Logo
to varargs [:args] foreach :args [print ?] end   (varargs "Mary "had "a "little "lamb) apply "varargs [Mary had a little lamb]
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...
#Ring
Ring
  # Project : Vector   decimals(1) vect1 = [5, 7] vect2 = [2, 3] vect3 = list(len(vect1))   for n = 1 to len(vect1) vect3[n] = vect1[n] + vect2[n] next showarray(vect3)   for n = 1 to len(vect1) vect3[n] = vect1[n] - vect2[n] next showarray(vect3)   for n = 1 to len(vect1) vect3[n] = vect1[n] * vect2[n] nex...
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...
#Ruby
Ruby
class Vector def self.polar(r, angle=0) new(r*Math.cos(angle), r*Math.sin(angle)) end   attr_reader :x, :y   def initialize(x, y) raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric) @x, @y = x, y end   def +(other) raise TypeError if self.class != other.class self.class.new(@x +...
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 ...
#Ring
Ring
  # Project : Vigenère cipher   key = "LEMON" plaintext = "ATTACK AT DAWN" ciphertext = encrypt(plaintext, key) see "key = "+ key + nl see "plaintext = " + plaintext + nl see "ciphertext = " + ciphertext + nl see "decrypted = " + decrypt(ciphertext, key) + nl     func encrypt(plain, key) o = "" k = 0 ...
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 ...
#Ruby
Ruby
module VigenereCipher   BASE = 'A'.ord SIZE = 'Z'.ord - BASE + 1   def encrypt(text, key) crypt(text, key, :+) end   def decrypt(text, key) crypt(text, key, :-) end   def crypt(text, key, dir) text = text.upcase.gsub(/[^A-Z]/, '') key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| ...
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Erlang
Erlang
  -module(vector). -export([main/0]). vector_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1], Ans. dot_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=X1*Y1+X2*Y2+X3*Y3, io:fwrite("~p~n",[Ans]). main()-> {ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"), {ok, B} = io:fread("Enter v...
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...
#jq
jq
# This filter may be applied to integers or integer-valued strings def luhntest: def digits: tostring | explode | map([.]|implode|tonumber); (digits | reverse) | ( [.[range(0;length;2)]] | add ) as $sum1 | [.[range(1;length;2)]] | (map( (2 * .) | if . > 9 then (digits|add) else . end) | add) as $sum2 | ($s...
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...
#Julia
Julia
using Printf   luhntest(x) = luhntest(parse(Int, x))   function checkISIN(inum::AbstractString) if length(inum) != 12 || !all(isalpha, inum[1:2]) return false end return parse.(Int, collect(inum), 36) |> join |> luhntest end   for inum in ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU...
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...
#Go
Go
package main   import "fmt"   func v2(n uint) (r float64) { p := .5 for n > 0 { if n&1 == 1 { r += p } p *= .5 n >>= 1 } return }   func newV(base uint) func(uint) float64 { invb := 1 / float64(base) return func(n uint) (r float64) { p := invb ...
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...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Write $ZConvert("http%3A%2F%2Ffoo%20bar%2F", "I", "URL") 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...
#Clojure
Clojure
(java.net.URLDecoder/decode "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...
#11l
11l
V LEFT_DIGITS = [ ‘ ## #’ = 0, ‘ ## #’ = 1, ‘ # ##’ = 2, ‘ #### #’ = 3, ‘ # ##’ = 4, ‘ ## #’ = 5, ‘ # ####’ = 6, ‘ ### ##’ = 7, ‘ ## ###’ = 8, ‘ # ##’ = 9 ]   V RIGHT_DIGITS = Dict(LEFT_DIGITS.items(), (k, v) -> (k.replace(‘ ’, ‘s’).replace(‘#’, ‘ ’).replace(‘s’, ‘#’), v))   V ...
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...
#Delphi
Delphi
  program uConfigFile;   {$APPTYPE CONSOLE}   uses System.SysUtils, uSettings;   const FileName = 'uConf.txt';   var Settings: TSettings;   procedure show(key: string; value: string); begin writeln(format('%14s = %s', [key, value])); end;   begin Settings := TSettings.Create; Settings.LoadFromFile(FileNam...
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
#Bracmat
Bracmat
( doit = out'"Enter a string" & get':?mystring & whl ' ( out'"Enter a number" & get':?mynumber & !mynumber:~# & out'"I said:\"a number\"!" ) & out$(mystring is !mystring \nmynumber is !mynumber \n) );
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
#C
C
#include <stdio.h> #include <stdlib.h>   int main(void) { // Get a string from stdin char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin);   // Get 75000 from stdin long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), s...
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
#Common_Lisp
Common Lisp
(capi:prompt-for-string "Enter a string:")
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Dart
Dart
import 'package:flutter/material.dart';   main() => runApp( OutputLabel() );   class OutputLabel extends StatefulWidget { @override _OutputLabelState createState() => _OutputLabelState(); }   class _OutputLabelState extends State<OutputLabel> { String output = "output"; // This will be displayed in an output text...
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...
#D
D
import std.conv; import std.stdio;   immutable CHARS = ["A","ö","Ж","€","𝄞"];   void main() { writeln("Character Code-Point Code-Units"); foreach (c; CHARS) { auto bytes = cast(ubyte[]) c; //The raw bytes of a character can be accessed by casting auto unicode = cast(uint) to!dstring(c)[0]; ...
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...
#Elena
Elena
import system'routines; import extensions;   extension op : String { string printAsString() { console.print(self," ") }   string printAsUTF8Array() { self.toByteArray().forEach:(b){ console.print(b.toString(16)," ") } }   string printAsUTF32() { self.toArray().forE...
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...
#Mercury
Mercury
:- module query. :- interface.   :- pred query(string::in, string::out) is det.   :- implementation.   query(_, "Hello, world!").   :- pragma foreign_export("C", query(in, out), "query").   :- pragma foreign_decl("C", " #include <string.h> int Query (char * Data, size_t * Length); "). :- pragma foreign_code("C", " int ...
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...
#Nim
Nim
proc Query*(data: var array[1024, char], length: var cint): cint {.exportc.} = const text = "Here am I" if length < text.len: return 0   for i in 0 .. text.high: data[i] = text[i] length = text.len return 1
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...
#OCaml
OCaml
#include <stdio.h> #include <string.h> #include <caml/mlvalues.h> #include <caml/callback.h>   extern int Query (char * Data, size_t * Length) { static value * closure_f = NULL; if (closure_f == NULL) { closure_f = caml_named_value("Query function cb"); } value ret = caml_callback(*closure_f, Val_uni...
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...
#Julia
Julia
using Printf, URIParser   const FIELDS = names(URI)   function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f))  !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s:  %s", ind...
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...
#Kotlin
Kotlin
// version 1.1.2   import java.net.URL import java.net.MalformedURLException   fun parseUrl(url: String) { var u: URL var scheme: String try { u = URL(url) scheme = u.protocol } catch (ex: MalformedURLException) { val index = url.indexOf(':') scheme = url.take(index)...