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/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #F.23 | F# | Microsoft F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727
Please send bug reports to fsbugs@microsoft.com
For help type #help;;
> let f a b sep = String.concat sep [a; ""; b] ;;
val f : string -> string -> string -> string
> f "R... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Factor | Factor | ./factor -run=listener
|
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #IS-BASIC | IS-BASIC | 100 PROGRAM "ISBN13.bas"
110 DO
120 PRINT :INPUT PROMPT "ISBN-13 code: ":IS$
130 IF IS$="" THEN EXIT DO
140 IF ISBN(IS$) THEN
150 PRINT "Ok."
160 ELSE
170 PRINT "CRC error."
180 END IF
190 LOOP
200 DEF TRIM$(S$)
210 LET T$=""
220 FOR I=1 TO LEN(S$)
230 IF S$(I)>CHR$(47) AND S$(I)<CHR$(58) THEN... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #J | J | D =: '0123456789'
isbn13c =: D&([ check@:i. clean)
check =: 0 = 10 | lc
lc =: [ +/@:* weight
weight =: 1 3 $~ #
clean =: ] -. a. -. [ |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Nim | Nim | import lenientops
func jaro(s1, s2: string): float =
if s1.len == 0 and s2.len == 0: return 1
if s1.len == 0 or s2.len == 0: return 0
let matchDistance = max(s1.len, s2.len) div 2 - 1
var s1Matches = newSeq[bool](s1.len)
var s2Matches = newSeq[bool](s2.len)
var matches = 0
for i in 0..s1.high:
f... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Objeck | Objeck | class JaroDistance {
function : Main(args : String[]) ~ Nil {
Jaro("MARTHA", "MARHTA")->PrintLine();
Jaro("DIXON", "DICKSONX")->PrintLine();
Jaro("JELLYFISH", "SMELLYFISH")->PrintLine();
}
function : Jaro(s : String, t : String) ~ Float {
s_len := s->Size();
t_len := t->Size();
if (s_... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Lua | Lua | squares = {}
for i = 0, 9 do
for j = 0, 9 do
squares[i * 10 + j] = i * i + j * j
end
end
for i = 1, 99 do
for j = 0, 99 do
squares[i * 100 + j] = squares[i] + squares[j]
end
end
function sum_squares(n)
if n < 9999.5 then
return squares[n]
else
local m = math... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Ada | Ada | with Ada.Text_IO;
procedure Integers is
Value : Integer := 1;
begin
loop
Ada.Text_IO.Put_Line (Integer'Image (Value));
Value := Value + 1; -- raises exception Constraint_Error on overflow
end loop;
end Integers; |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #ALGOL_68 | ALGOL 68 | main:
(
FOR i DO
printf(($g(0)","$,i))
OD
) |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Axe | Axe | Disp -65535▶Dec,i
Disp 40000+40000▶Dec,i
Disp 32767-65535▶Dec,i
Disp 257*257▶Dec,i |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Befunge | Befunge | "a9jc>"*:*+*+:0\- "(-",,:.048*"="99")1 -" >:#,_$v
v,,,9"="*84 .: ,,"+"*84 .: **:*" }}" ,+55 .-\0-1<
>:+. 55+, ::0\- :. 48*"-",, \:. 48*"="9,,, -. 55v
v.*: ,,,,,999"="*84 .: ,,"*"*84 .: *+8*7"s9" ,+<
>55+, 0\- "(",:.048*"="99"1-/)1 -">:#,_$ 1-01-/.@ |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Icon | Icon | link numbers # For the "commas" procedure.
link printf
procedure main ()
write ("isqrt(i) for 0 <= i <= 65:")
write ()
roots_of_0_to_65()
write ()
write ()
write ("isqrt(7**i) for 1 <= i <= 73, i odd:")
write ()
printf ("%2s %84s %43s\n", "i", "7**i", "sqrt(7**i)")
write (repl("-"... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #C.2B.2B | C++ |
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/";
const size_t MAX_NODES = 41;
class node
{
public:
node() { clear(); }
node( char z ) { clear(); }
~node() { for( int x = 0; x < MAX_NO... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Common_Lisp | Common Lisp | (let* ((ver (lisp-implementation-version))
(major (parse-integer ver :start 0 :end (position #\. ver))))
#+lispworks (assert (>= 5 major) () "Requires Lispworks version 5 or above")
#+clisp (assert (>= 2 major) () "Requires CLISP 2.n")
) |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #D | D | // Some module-level variables (D doesn't have a global scope).
immutable x = 3, y = 100, z = 3_000;
short w = 1; // Not an int, must be ignored.
immutable s = "some string"; // Not an int, must be ignored.
void main() {
import std.compiler, std.math, std.traits;
// Compile-time constants of the compiler ve... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #friendly_interactive_shell | friendly interactive shell | function execute
# If the list is empty, don't do anything.
test (count $argv) -ge 2; or return
# If the list has only one element, return it
if test (count $argv) -eq 2
echo $argv[2]
return
end
# Rotate prisoners
for i in (seq 2 $argv[1])
set argv $argv[1 3..-1 2]
... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Java | Java |
package intersectingNumberWheels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class WheelController {
private static final String IS_NUMBER = "[0-9]";
private static final int TWENTY = 20;
private static Map<String, ... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Fantom | Fantom | $ fansh
Fantom Shell v1.0.57 ('?' for help)
fansh> f := |Str a, Str b, Str c -> Str| {"$a$c$c$b"}
|sys::Str,sys::Str,sys::Str->sys::Str|
fansh> f("Rosetta", "Code", ":")
Rosetta::Code
|
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Forth | Forth | $ gforth
Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
ok
: f ( separator suffix prefix -- ) compiled
pad place 2swap 2dup compiled
pad +place compiled
pad +place compiled
pad +place c... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim As String s1, s2, sep
Input "First string "; s1
Input "Second string "; s2
Input "Separator "; sep
Print : Print s1 + sep + sep + s2
Sleep |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Java | Java | public static void main(){
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
System.out.println(isISBN13("978-1788399081"));
System.out.println(isISBN13("978-1788399083"));
}
public static boolean isISBN13(String in){
int pre = In... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #PARI.2FGP | PARI/GP |
\\Jaro distance between 2 strings s1 and s2.
\\ 4/12/16 aev
jaroDist(s1,s2)={
my(vt1=Vecsmall(s1),vt2=Vecsmall(s2),n1=#s1,n2=#s2,d,
md=max(n1,n2)\2-1,cs,ce,mc=0,tr=0,k=1,ds,
s1m=vector(n1,z,0),s2m=vector(n2,z,0));
if(!n1||!n2, return(0));
for(i=1,n1,
cs=max(1,i-md);
ce=min(i+md+1,n2);
for(j=cs,ce,
if(... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sumDigitsSquared[n_Integer] := Total[IntegerDigits[n]^2]
stopValues = Join[{1}, NestList[sumDigitsSquared, 89, 7]];
iterate[n_Integer] :=
NestWhile[sumDigitsSquared, n, Intersection[stopValues, {#}] == {} &]
numberOfDigits = 8;
maxSum = numberOfDigits 9^2;
loopVariables =
ToExpression@Table["i" <> ToString[n], {... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Nim | Nim | import tables
iterator digits(n: int): int =
## Yield the digits starting from the unit.
var n = n
while true:
yield n mod 10
n = n div 10
if n == 0:
break
func gen(n: int): int =
## Compute the chain.
result = n
while result notin [1, 89]:
var s = 0
for d in digits(result):
... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #ALGOL_W | ALGOL W | begin
% print the integers from 1 onwards %
% Algol W only has 32-bit integers. When i reaches 2^32, %
% an integer overflow event would be raised which by default, %
% should terminate the program ... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Applesoft_BASIC | Applesoft BASIC | 10 I% = 1
20 PRINT I%;
30 I% = I% + 1
40 PRINT ", ";
50 GOTO 20 |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Bracmat | Bracmat | #include <stdio.h>
int main (int argc, char *argv[])
{
printf("Signed 32-bit:\n");
printf("%d\n", -(-2147483647-1));
printf("%d\n", 2000000000 + 2000000000);
printf("%d\n", -2147483647 - 2147483647);
printf("%d\n", 46341 * 46341);
printf("%d\n", (-2147483647-1) / -1);
printf("Signed 64-bit:\n");
print... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputLoop64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #J | J |
isqrt_float=: <.@:%:
isqrt_newton=: 9&$: :(x:@:<.@:-:@:(] + x:@:<.@:%)^:_&>~&:x:)
align=: (|.~ i.&' ')"1
comma=: (' ' -.~ [: }: [: , [: (|.) _3 (',' ,~ |.)\ |.)@":&>
While=: {{ u^:(0-.@:-:v)^:_ }}
isqrt=: 3 :0&>
y =. x: y
NB. q is a power of 4 that's greater than y. Append 0 0 under binary representation
q ... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #Clojure | Clojure | (ns inverted-index.core
(:require [clojure.set :as sets]
[clojure.java.io :as io]))
(def pattern #"\w+") ; Java regex for a raw term: here a substring of alphanums
(defn normalize [match] (.toLowerCase match)) ; normalization of a raw term
(defn term-seq [text] (map normalize (re-seq pattern text... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #E | E | def version := interp.getProps()["e.version"] |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #EchoLisp | EchoLisp |
(version)
→ EchoLisp - 2.50.3
📗 local-db: db.version: 3
(when (< (version) 2.6)
(writeln "Please reload EchoLisp : CTRL-F5, CMD-R or other...")
(exit))
(if (and (bound? 'bloop) (bound? 'abs) (procedure? abs))
(abs bloop) 'NOT-HERE)
→ NOT-HERE
(define bloop -777)
→ bloop
(if (and (bound? 'bloo... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Frink | Frink |
killingCycle[prisonerCount,killStep = 2] :=
{
i = 0
killed = new array
prisoners = array[0 to prisonerCount - 1]
while length[prisoners] > 1
{
i = (i + killStep - 1) mod length[prisoners]
killed.push[prisoners.remove[i]] // Remove the killed prisoner from the prisoners array and add it to t... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () => {
// clockWorkTick :: Dict -> (Dict, Char)
const clockWorkTick = wheelMap => {
// The new configuration of the wheels, tupled with
// a digit found by recursive descent from a single
// click o... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Frink | Frink | $ java -cp frink.jar frink.parser.Frink
f[a,b,s] := "$a$s$s$b"
f["Rosetta", "Code", ":"] |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | ~% gap
######### ###### ########### ###
############# ###### ############ ####
############## ######## ############# #####
############### ######## ##### ###### #####
#####... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #GAP | GAP | ~% gap
######### ###### ########### ###
############# ###### ############ ####
############## ######## ############# #####
############### ######## ##### ###### #####
#####... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #jq | jq |
def isbn_check:
def digits: tostring | explode | map( select(. >= 48 and . <= 57) | [.] | implode | tonumber);
def sum(s): reduce s as $x (null; . + $x);
digits
| . as $digits
| sum(range(0;length;2) | $digits[.]) as $one
| (3 * sum(range(1;length;2) | $digits[.])) as $two
| (($one+$two) % 10) == 0... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Julia | Julia | function isbncheck(str)
return sum(iseven(i) ? 3 * parse(Int, ch) : parse(Int, ch)
for (i, ch) in enumerate(replace(str, r"\D" => ""))) % 10 == 0
end
const testingcodes = ["978-1734314502", "978-1734314509",
"978-1788399081", "978-1788399083"]
for code in testingcodes
println(... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Pascal | Pascal |
program Jaro_distance;
uses SysUtils, Math;
//converted from C source by /u/bleuge
function ssJaroWinkler(s1, s2: string): double;
var
l1, l2, match_distance, matches, i, k, trans: integer;
bs1, bs2: array[1..255] of boolean; //used to avoid getmem, max string length is 255
begin
l1 := length(s1);
l2 := l... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Oberon-2 | Oberon-2 |
MODULE DigitsSquaring;
IMPORT
Out;
VAR
i,hits89: LONGINT;
PROCEDURE Squaring(n: LONGINT): LONGINT;
VAR
d, sum: LONGINT;
BEGIN
LOOP
sum := 0;
WHILE n > 0 DO
d := n MOD 10;
INC(sum,d * d);
n := n DIV 10
END;
IF (sum = 1) OR (sum = 89) THEN EXIT END;
... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #ARM_Assembly | ARM Assembly | .text
.global main
@ An ARM program that keeps incrementing R0 forever
@
@ If desired, a call to some 'PRINT' routine --
@ which would depend on the OS -- could be included
main:
mov r0, #0 @ start with R0 = 0
repeat:
@ call to 'PRINT' routine
add r0, r0, #1 @ increme... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #ArnoldC | ArnoldC | IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
STICK AROUND @NO PROBLEMO
TALK TO THE HAND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #C | C | #include <stdio.h>
int main (int argc, char *argv[])
{
printf("Signed 32-bit:\n");
printf("%d\n", -(-2147483647-1));
printf("%d\n", 2000000000 + 2000000000);
printf("%d\n", -2147483647 - 2147483647);
printf("%d\n", 46341 * 46341);
printf("%d\n", (-2147483647-1) / -1);
printf("Signed 64-bit:\n");
print... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Action.21 | Action! | PROC ReadStream(BYTE stream)
CHAR ARRAY line(255)
WHILE Eof(stream)=0
DO
InputSD(stream,line)
PrintE(line)
OD
RETURN
PROC Main()
BYTE streamId=[1]
Close(streamId)
Open(streamId,"H6:INPUT_PU.ACT",4)
PrintE("Reading from stream...") PutE()
ReadStream(streamId)
Close(streamId)
RETURN |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Java | Java | import java.math.BigInteger;
public class Isqrt {
private static BigInteger isqrt(BigInteger x) {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Argument cannot be negative");
}
var q = BigInteger.ONE;
while (q.compareTo(x) <= 0) {
... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #CoffeeScript | CoffeeScript |
fs = require 'fs'
make_index = (fns) ->
# words are indexed by filename and 1-based line numbers
index = {}
for fn in fns
for line, line_num in fs.readFileSync(fn).toString().split '\n'
words = get_words line
for word in words
word = mangle(word)
index[word] ||= []
inde... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Erlang | Erlang |
-module( introspection ).
-export( [task/0] ).
task() ->
exit_if_too_old( erlang:system_info(otp_release) ),
Bloop = lists:keyfind( bloop, 1, ?MODULE:module_info(functions) ),
Abs = lists:keyfind( abs, 1, erlang:module_info(exports) ),
io:fwrite( "abs( bloop ) => ~p~n", [call_abs_with_bloop(Abs, B... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
// basic task function
func finalSurvivor(n, k int) int {
// argument validation omitted
circle := make([]int, n)
for i := range circle {
circle[i] = i
}
k--
exPos := 0
for len(circle) > 1 {
exPos = (exPos + k) % len(circle)
circle = appe... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Julia | Julia | const d1 = Dict("A" => [["1", "2", "3"], 1])
const d2 = Dict("A" => [["1", "B", "2"], 1], "B" => [["3", "4"], 1])
const d3 = Dict("A" => [["1", "D", "D"], 1], "D" => [["6", "7", "8"], 1])
const d4 = Dict("A" => [["1", "B", "C"], 1], "B" => [["3", "4"], 1],
"C" => [["5", "B"], 1])
function getvalue!(wheelname, all... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Kotlin | Kotlin | import java.util.Collections
import java.util.stream.IntStream
object WheelController {
private val IS_NUMBER = "[0-9]".toRegex()
private const val TWENTY = 20
private var wheelMap = mutableMapOf<String, WheelModel>()
private fun advance(wheel: String) {
val w = wheelMap[wheel]
if (w... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Go | Go | package main
import "fmt"
func f(s1, s2, sep string) string {
return s1 + sep + sep + s2
}
func main() {
fmt.Println(f("Rosetta", "Code", ":"))
} |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Groovy | Groovy | C:\Apps\groovy>groovysh
Groovy Shell (1.6.2, JVM: 1.6.0_13)
Type 'help' or '\h' for help.
---------------------------------------------------------------------------------------------------
groovy:000> f = { a, b, sep -> a + sep + sep + b }
===> groovysh_evaluate$_run_closure1@5e8d7d
groovy:000> println f('Rosetta','Co... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Kotlin | Kotlin |
fun isValidISBN13(text: String): Boolean {
val isbn = text.replace(Regex("[- ]"), "")
return isbn.length == 13 && isbn.map { it - '0' }
.mapIndexed { index, value -> when (index % 2) { 0 -> value else -> 3 * value } }
.sum() % 10 == 0
}
|
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #langur | langur | val .isbn13checkdigit = f(var .s) {
.s = replace(.s, RE/[\- ]/)
matching(re/^[0-9]{13}$/, .s) and
fold(f{+}, map [_, f{x 3}], s2n .s) div 10
}
val .tests = h{
"978-1734314502": true,
"978-1734314509": false,
"978-1788399081": true,
"978-1788399083": false,
}
for .key of .tests {
... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Perl | Perl | use strict;
use warnings;
use List::Util qw(min max);
sub jaro {
my($s, $t) = @_;
my(@s_matches, @t_matches, $matches);
return 1 if $s eq $t;
my($s_len, @s) = (length $s, split //, $s);
my($t_len, @t) = (length $t, split //, $t);
my $match_distance = int (max($s_len, $t_len) / 2) - 1;
... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Objeck | Objeck | class Abbreviations {
function : Main(args : String[]) ~ Nil {
Count89s(1000000)->PrintLine();
Count89s(100000000)->PrintLine();
}
function : Count89s(limit : Int) ~ Int {
if(limit < 1) {
return 0;
};
result := 0;
ends := Int->New[Int->Min(limit, 9 * 9 * 9 + 2)];
for(i := 1; ... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Arturo | Arturo | i:0
while ø [
print i
inc 'i
] |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #AutoHotkey | AutoHotkey | x=0
Loop
TrayTip, Count, % ++x |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Ada | Ada | package Multiple_Interfaces is
type Camera is tagged null record;
type Mobile_Phone is limited Interface;
type Camera_Phone is new Camera and Mobile_Phone with null record;
end Multiple_Interfaces; |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #C.23 | C# | using System;
public class IntegerOverflow
{
public static void Main() {
unchecked {
Console.WriteLine("For 32-bit signed integers:");
Console.WriteLine(-(-2147483647 - 1));
Console.WriteLine(2000000000 + 2000000000);
Console.WriteLine(-2147483647 - 21474836... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Read_Stream is
Line : String(1..10);
Length : Natural;
begin
while not End_Of_File loop
Get_Line(Line, Length); -- read up to 10 characters at a time
Put(Line(1..Length));
-- The current line of input data may be longer than the string receiving ... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Aime | Aime | void
read_stream(file f)
{
text s;
while (f_line(f, s) != -1) {
# the read line available as -s-
}
} |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #jq | jq | # For gojq
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
# input should be non-negative
def isqrt:
. as $x
| 1 | until(. > $x; . * 4) as $q
| {$q, $x, r: 0}
| until( .q <= 1;
.q |= idivide(4)
| .t = .x - .r - .q
| .r |= idivide(2)
| if .t >... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Julia | Julia | using Formatting
function integer_sqrt(x)
@assert(x >= 0)
q = one(x)
while q <= x
q <<= 2
end
z, r = x, zero(x)
while q > 1
q >>= 2
t = z - r - q
r >>= 1
if t >= 0
z = t
r += q
end
end
return r
end
println("The i... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #Common_Lisp | Common Lisp | (defpackage rosettacode.inverted-index
(:use cl))
(in-package rosettacode.inverted-index)
;; Return a list of tokens in the string LINE. This is rather
;; complicated as CL has no good standard function to do it.
(defun tokenize (line)
(let ((start 0) (len (length line)))
(loop for s = (position-if #'alphanu... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Factor | Factor | : if-older ( n true false -- )
[ build > ] 2dip if ; inline
: when-older ( n true -- )
[ ] if-older ; inline
: unless-older ( n false -- )
[ [ ] ] dip if-older ; inline
900 [ "Your version of Factor is too old." print 1 exit ] when-older |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Forth | Forth | s" MAX-U" environment? [IF]
0xffffffff <> [IF] .( Requires 32 bits! ) bye [THEN]
[THEN]
[defined] bloop [if]
[defined] abs [if]
bloop @ abs
[then] [then] |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Go | Go | package main
import "fmt"
// basic task function
func finalSurvivor(n, k int) int {
// argument validation omitted
circle := make([]int, n)
for i := range circle {
circle[i] = i
}
k--
exPos := 0
for len(circle) > 1 {
exPos = (exPos + k) % len(circle)
circle = appe... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Maple | Maple |
with(ArrayTools):
module Wheel()
option object;
local spokes := Array([1,2,3]);
local currentSpoke := 1;
export currentValue::static := proc(self::Wheel)
local valueOut;
if type(self:-spokes[self:-currentSpoke], integer) then
valueOut := self:-spokes[self:-currentSpoke]:
else
valueOut := currentVa... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Nim | Nim | import strutils, tables
type
ElemKind = enum eValue, eWheel
Elem = object
case kind: ElemKind
of eValue:
value: Natural
of eWheel:
name: char
Wheel = ref object
elems: seq[Elem]
index: Natural
Wheels = Table[char, Wheel]
WheelDescription = tuple[name: char; elems: s... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Haskell | Haskell | $ ghci
___ ___ _
/ _ \ /\ /\/ __(_)
/ /_\// /_/ / / | | GHC Interactive, version 6.4.2, for Haskell 98.
/ /_\\/ __ / /___| | http://www.haskell.org/ghc/
\____/\/ /_/\____/|_| Type :? for help.
Loading package base-1.0 ... linking ... done.
Prelude> let f as bs sep = as ++ sep ++ sep ++... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #HicEst | HicEst | CHARACTER A*40, B*40, C*40
READ(Text=$CMD_LINE, Format="'','','',") A, B, C
WRITE(ClipBoard, Name) A, B, C ! A=Rosetta; B=Code; C=:;
WRITE(ClipBoard) TRIM(A) // ':' // TRIM(C) // TRIM(B) ! Rosetta::Code |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Lua | Lua | function checkIsbn13(isbn)
local count = 0
local sum = 0
for c in isbn:gmatch"." do
if c == ' ' or c == '-' then
-- skip
elseif c < '0' or '9' < c then
return false
else
local digit = c - '0'
if (count % 2) > 0 then
sum ... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Phix | Phix | function jaro(string str1, str2)
str1 = trim(upper(str1))
str2 = trim(upper(str2))
integer len1 = length(str1),
len2 = length(str2),
match_distance = floor(max(len1,len2)/2)-1,
match_count = 0,
half_transposed = 0
if len1==0 then return len2==0 end if
... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Oforth | Oforth | : sq_digits(n)
while (n 1 <> n 89 <> and ) [
0 while(n) [ n 10 /mod ->n dup * + ]
->n
] n ;
: iterDigits | i | 0 100000000 loop: i [ i sq_digits 89 &= + ] . ; |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #PARI.2FGP | PARI/GP | ssd(n)=n=digits(n); sum(i=1, #n, n[i]^2);
happy(n)=while(n>6, n=ssd(n)); n==1;
ct(n)=my(f=n!,s=10^n-1,d); forvec(v=vector(9,i,[0,n]), d=vector(9,i, if(i>8,n,v[i+1])-v[i]); if(happy(sum(i=1,9,d[i]*i^2)), s-=f/prod(i=1,9,d[i]!)/v[1]!), 1); s;
ct(8) |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #AWK | AWK | BEGIN {
for( i=0; i != i + 1; i++ )
print( i )
} |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Axe | Axe | While getKey(0)
End
0→I
Repeat getKey(0)
Disp I▶Dec,i
I++
EndIf I=0 |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Aikido | Aikido | interface Camera {
}
interface Mobile_Phone {
}
class Camera_Phone implements Camera, Mobile_Phone {
} |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"CLASSLIB"
DIM Camera{TakePicture}
PROC_class(Camera{})
DIM MobilePhone{MakeCall}
PROC_class(MobilePhone{})
DIM CameraPhone{methods}
PROC_inherit(CameraPhone{}, Camera{})
PROC_inherit(CameraPhone{}, MobilePhone{})
PROC_class(CameraPhone{}) |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #C | C |
typedef struct{
double focalLength;
double resolution;
double memory;
}Camera;
typedef struct{
double balance;
double batteryLevel;
char** contacts;
}Phone;
typedef struct{
Camera cameraSample;
Phone phoneSample;
}CameraPhone;
|
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #C.23 | C# | interface ICamera {
// ...
}
class MobilePhone {
// ...
}
class CameraPhone: ICamera, MobilePhone {
// ...
} |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
#include <limits>
int main (int argc, char *argv[])
{
std::cout << std::boolalpha
<< std::numeric_limits<std::int32_t>::is_modulo << '\n'
<< std::numeric_limits<std::uint32_t>::is_modulo << '\n' // always true
<< std::numeric_limits<std::int64_t>::is_modulo << '\n'
<< ... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #ALGOL_68 | ALGOL 68 | main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
DO
print(read string);
read(new line);
print(new line)
OD;
except logical file end:
SKIP
) |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #ALGOL_W | ALGOL W | begin
string(80) line;
% allow the program to continue after reaching end-of-file %
% without this, end-of-file would cause a run-time error %
ENDFILE := EXCEPTION( false, 1, 0, false, "EOF" );
% read lines until end of file %
read( line );
while not XCPNOTED(EN... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #Kotlin | Kotlin | import java.math.BigInteger
fun isqrt(x: BigInteger): BigInteger {
if (x < BigInteger.ZERO) {
throw IllegalArgumentException("Argument cannot be negative")
}
var q = BigInteger.ONE
while (q <= x) {
q = q.shiftLeft(2)
}
var z = x
var r = BigInteger.ZERO
while (q > BigInt... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #D | D | import std.stdio, std.algorithm, std.string, std.file, std.regex;
void main() {
string[][string] index;
void parseFile(in string fn) {
if (!exists(fn) || !isFile(fn))
throw new Exception("File not found");
foreach (word; readText(fn).splitter(regex(r"\W"))) {
word =... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#If __FB_VERSION__ < "1.06.0"
#Error "Compiler version is too old - needs to be 1.06.0 or later"
#EndIf
Dim bloop As Integer = -15
#IfDef bloop
#IfDef Abs
Print "Abs(bloop) = "; Abs(bloop)
#Else
Print "Abs is not available"
#EndIf
#Else
Print "bloop does not exist"
#EndIf
Sleep |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #GAP | GAP | # Apply a function to a value, given variable names for both function and value
CheckEval := function(fun, val)
local f, x;
if IsBoundGlobal(fun) and IsBoundGlobal(val) then
f := ValueGlobal(fun);
x := ValueGlobal(val);
return f(x);
fi;
end;
bloop := -1;
CheckEval("AbsInt", "bloop");
# 1
# Sum of integer... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Groovy | Groovy | int[] Josephus (int size, int kill, int survivors) {
// init user pool
def users = new int[size];
// give initial values such that [0] = 1 (first person) [1] = 2 (second person) etc
users.eachWithIndex() {obj, i -> users[i] = i + 1};
// keep track of which person we are on (ranging from 1 to kil... |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub get_next {
my($w,%wheels) = @_;
my $wh = \@{$wheels{$w}}; # reference, not a copy
my $value = $$wh[0][$$wh[1]];
$$wh[1] = ($$wh[1]+1) % @{$$wh[0]};
defined $wheels{$value} ? get_next($value,%wheels) : $value;
}
sub spin_wheels {
my(%wheels) = ... |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Huginn | Huginn | $ io
Io 20110905
Io> f := method(str1,str2,sep,
... str1 .. sep .. sep .. str2)
==> method(str1, str2, sep,
str1 .. sep .. sep .. str2
)
Io> f("Rosetta","Code",":")
==> Rosetta::Code
Io> writeln("I am going to exit now")
I am going to exit now
==> nil
Io> exit
$ |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Io | Io | $ io
Io 20110905
Io> f := method(str1,str2,sep,
... str1 .. sep .. sep .. str2)
==> method(str1, str2, sep,
str1 .. sep .. sep .. str2
)
Io> f("Rosetta","Code",":")
==> Rosetta::Code
Io> writeln("I am going to exit now")
I am going to exit now
==> nil
Io> exit
$ |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #J | J | f=: [: ; 0 2 2 1&{
f 'Rosetta';'Code';':'
Rosetta::Code |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[ValidISBNQ]
ValidISBNQ[iban_String] := Module[{i},
i = StringReplace[iban, {" " -> "", "-" -> ""}];
If[StringMatchQ[i, Repeated[DigitCharacter]],
i = ToExpression /@ Characters[i];
i[[2 ;; ;; 2]] *= 3;
Mod[Total[i], 10] == 0
,
False
]
]
ValidISBNQ["978-1734314502"]
ValidISBNQ["978-17343... |
http://rosettacode.org/wiki/ISBN13_check_digit | ISBN13 check digit | Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
978-1734314502 (good)
... | #Modula-2 | Modula-2 | MODULE ISBN;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;
PROCEDURE validISBN(s: ARRAY OF CHAR): BOOLEAN;
VAR total, i, length: CARDINAL;
BEGIN
total := 0;
length := Length(s);
IF (length # 14) OR (s[3] # '-') THEN
RETURN FALSE;
END;
FOR i := 0 TO length-1 DO
... |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Python | Python | '''Jaro distance'''
from __future__ import division
def jaro(s, t):
'''Jaro distance between two strings.'''
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] ... |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #11l | 11l | T Animal
{
}
T Dog(Animal)
{
}
T Cat(Animal)
{
}
T Lab(Dog)
{
}
T Collie(Dog)
{
} |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Pascal | Pascal | 1E8 -> runtime 0..4 ms // not really measureable
1E12-> runtime 0.22 secs
1E14 -> runtime 2,7 secs
1E16 -> runtime 31,0 secs
1E18 -> runtime 354 secs // 2GByte |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.