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/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...
#Python
Python
from math import ceil, log10, factorial   def next_step(x): result = 0 while x > 0: result += (x % 10) ** 2 x /= 10 return result   def check(number): candidate = 0 for n in number: candidate = candidate * 10 + n   while candidate != 89 and candidate != 1: candida...
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...
#Bracmat
Bracmat
0:?n&whl'out$(1+!n:?n)
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...
#Brainf.2A.2A.2A
Brainf***
++++++++++>>>+[[->>+<[+>->+<<--------------------------------------- -------------------[>>-<++++++++++<[+>-<]]>[-<+>]<++++++++++++++++++ ++++++++++++++++++++++++++++++>]<[<]>>[-<+++++++++++++++++++++++++++ ++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>>+]
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#ActionScript
ActionScript
trace(5 / 0); // outputs "Infinity" trace(isFinite(5 / 0)); // outputs "false"
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Infinities is function Sup return Float is -- Only for predefined types Result : Float := Float'Last; begin if not Float'Machine_Overflows then Result := Float'Succ (Result); end if; return Result; end Sup;   function Inf return...
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...
#Factor
Factor
TUPLE: camera ; TUPLE: mobile-phone ; UNION: camera-phone 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...
#Fantom
Fantom
// a regular class class Camera { Str cameraMsg () { "camera" } }   // a mixin can only contain methods mixin MobilePhone { Str mobileMsg () { "mobile phone" } }   // class inherits from Camera, and mixes in the methods from MobilePhone class CameraPhone : Camera, MobilePhone { }   class Main { pu...
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...
#Forth
Forth
    \ define class camera with method say: :class camera  :m say: ." camera " ;m ;class   \ define class phone with method say: :class phone  :m say: ." phone " ;m ;class   \ define cameraPhone phone with method say: \ class cameraPhone inherits from both class \ camera and class phone :class cameraPhone super{ camera ...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' FB does not currently support multiple inheritance. Composition has to be used instead if one wants ' to (effectively) inherit from more than one class. In some cases, this might arguably be a better ' solution anyway.   Type Camera Extends Object ' if virtual methods etc needed ' ... End Ty...
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#ALGOL_68
ALGOL 68
BEGIN # show where the gaps increase in the series of Niven numbers # # ( numbers divisible by the sum of their digits ) # INT n count := 0; INT g count := 0; INT n gap := 0; INT this n := 1; print( ( " Gap Gap Niven Niven Next", newline ) ); print( ( "Index Value 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...
#Go
Go
package main   import "fmt"   func main() { // Go's builtin integer types are: // int, int8, int16, int32, int64 // uint, uint8, uint16, uint32, uint64 // byte, rune, uintptr // // int is either 32 or 64 bit, depending on the system // uintptr is large enough to hold the bit pattern of any pointer //...
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.
#Bracmat
Bracmat
( put$("This is a three line text","test.txt",NEW) & fil$("test.txt",r) & fil$(,STR," \t\r\n") & 0:?linenr & whl ' ( fil$:(?line.?breakchar) & put $ ( str $ ( "breakchar:" ( !breakchar:" "&SP | !breakchar:\t&"\\t" | !breakchar:\r&"\\r" | !breakchar...
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.
#C
C
#include <stdlib.h> #include <stdio.h>   char *get_line(FILE* fp) { int len = 0, got = 0, c; char *buf = 0;   while ((c = fgetc(fp)) != EOF) { if (got + 1 >= len) { len *= 2; if (len < 4) len = 4; buf = realloc(buf, len); } buf[got++] = c; if (c == '\n') break; } if (c == EOF && !got) return 0;   ...
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...
#Nim
Nim
import strformat, strutils import bignum     func isqrt*[T: SomeSignedInt | Int](x: T): T = ## Compute integer square root for signed integers ## and for big integers.   when T is Int: result = newInt() var q = newInt(1) else: result = 0 var q = T(1)   while q <= x: q = q shl 2   var z =...
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...
#Factor
Factor
USING: assocs fry io.encodings.utf8 io.files kernel sequences sets splitting vectors ; IN: rosettacode.inverted-index   : file-words ( file -- assoc ) utf8 file-contents " ,;:!?.()[]{}\n\r" split harvest ; : add-to-file-list ( files file -- files ) over [ swap [ adjoin ] keep ] [ nip 1vector ] if ; : add-to-ind...
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...
#Java
Java
public class VersCheck { public static void main(String[] args) { String vers = System.getProperty("java.version"); vers = vers.substring(0,vers.indexOf('.')) + "." + //some String fiddling to get the version number into a usable form vers.substring(vers.indexOf('.')+1,vers.lastIndexOf('.')); if(Double.parse...
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...
#JavaScript
JavaScript
var Josephus = { init: function(n) { this.head = {}; var current = this.head; for (var i = 0; i < n-1; i++) { current.label = i+1; current.next = {prev: current}; current = current.next; } current.label = n; current.next = this.head; this.head.prev = current; return 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"...
#Ruby
Ruby
groups = [{A: [1, 2, 3]}, {A: [1, :B, 2], B: [3, 4]}, {A: [1, :D, :D], D: [6, 7, 8]}, {A: [1, :B, :C], B: [3, 4], C: [5, :B]} ]   groups.each do |group| p group wheels = group.transform_values(&:cycle) res = 20.times.map do el = wheels[:A].next el = wheels[el].next until el....
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...
#Lua
Lua
$ lua Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio > function conc(a, b, c) >> return a..c..c..b >> end > print(conc("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...
#M2000_Interpreter
M2000 Interpreter
>edit f$()
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)   ...
#PicoLisp
PicoLisp
(de isbn13? (S) (let L (make (for N (chop S) (and (format N) (link @)) ) ) (and (= 13 (length L)) (=0 (% (sum * L (circ 1 3)) 10)) ) ) ) (mapc '((A) (tab (-19 1) A (if (isbn13? A) 'ok 'fail) ) ) (quote "978-1734314502" ...
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...
#Ruby
Ruby
def jaro(s, t) return 1.0 if s == t   s_len = s.size t_len = t.size match_distance = ([s_len, t_len].max / 2) - 1   s_matches = [] t_matches = [] matches = 0.0   s_len.times do |i| j_start = [0, i-match_distance].max j_end = [i+match_distance, t_len-1].min   (j_st...
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#8th
8th
  : compare \ n m -- 2dup n:= if "They are equal" . cr then 2dup n:< if "First less than second" . cr then n:> if "First greater than second" . cr then ;  
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...
#ChucK
ChucK
public class Drums{ //functions go here... }
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...
#Clojure
Clojure
(gen-class :name Animal) (gen-class :name Dog :extends Animal) (gen-class :name Cat :extends Animal) (gen-class :name Lab :extends Dog) (gen-class :name Collie :extends Dog)
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...
#COBOL
COBOL
CLASS-ID. Animal. *> ... END CLASS Animal.   CLASS-ID. Dog INHERITS Animal. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. CLASS Animal.   *> ... END CLASS Dog.   CLASS-ID. Cat INHERITS Animal. ENVIRONMENT DIVISIO...
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...
#QBasic
QBasic
REM Version 1: Brute force   T = TIMER n1 = 0 FOR i = 1 TO 10000000 j = i DO k = 0 DO k = INT(k + (j MOD 10) ^ 2) j = INT(j / 10) LOOP WHILE j <> 0 j = k LOOP UNTIL j = 89 OR j = 1 IF j > 1 THEN n1 = n1 + 1 NEXT i PRINT USING "Version 1: ####### in...
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...
#Brat
Brat
i = 1   loop { p i i = 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...
#Burlesque
Burlesque
  1R@  
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#ALGOL_68
ALGOL 68
printf(($"max int: "gl$,max int)); printf(($"long max int: "gl$,long max int)); printf(($"long long max int: "gl$,long long max int)); printf(($"max real: "gl$,max real)); printf(($"long max real: "gl$,long max real)); printf(($"long long max real: "gl$,long long max real)); printf(($"error char: "gl$,error char))
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#APL
APL
inf ← {⌊/⍬}
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Argile
Argile
use std printf "%f\n" atof "infinity" (: this prints "inf" :) #extern :atof<text>: -> real
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...
#Go
Go
// Example of composition of anonymous structs package main   import "fmt"   // Two ordinary structs type camera struct { optics, sensor string }   type mobilePhone struct { sim, firmware string }   // Fields are anonymous because only the type is listed. // Also called an embedded field. type cameraPhone struc...
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...
#Groovy
Groovy
class Camera a class MobilePhone a class (Camera a, MobilePhone a) => CameraPhone a
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...
#Haskell
Haskell
class Camera a class MobilePhone a class (Camera a, MobilePhone a) => CameraPhone a
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#AWK
AWK
  # syntax: GAWK -f INCREASING_GAPS_BETWEEN_CONSECUTIVE_NIVEN_NUMBERS.AWK # converted from C BEGIN { gap_index = 1 previous = 1 print("Gap index Gap Niven index Niven number") print("--------- --- ----------- ------------") for (niven=1; gap_index<=22; niven++) { sum = digit_sum(niven,su...
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#BASIC256
BASIC256
  function digit_sum(n, sum) # devuelve la suma de los dígitos de n dada la suma de los dígitos de n - 1 sum ++ while (n > 0 and n mod 10 = 0) sum -= 9 n = int(n / 10) end while return sum end function   function divisible(n, d) if ((d mod 1) = 0) and ((n mod 1) = 1) then return 0 end if return (n mod d =...
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...
#Groovy
Groovy
println "\nSigned 32-bit (failed):" assert -(-2147483647-1) != 2147483648g println(-(-2147483647-1)) assert 2000000000 + 2000000000 != 4000000000g println(2000000000 + 2000000000) assert -2147483647 - 2147483647 != -4294967294g println(-2147483647 - 2147483647) assert 46341 * 46341 != 2147488281g println(46341 * 46341)...
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.
#C.23
C#
using System; using System.IO;   class Program { static void Main(string[] args) { // For stdin, you could use // new StreamReader(Console.OpenStandardInput(), Console.InputEncoding)   using (var b = new StreamReader("file.txt")) { string line; while ((lin...
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.
#C.2B.2B
C++
  #include <istream> #include <string> #include <vector> #include <algorithm> #include <iostream> #include <iterator>   // word by word template<class OutIt> void read_words(std::istream& is, OutIt dest) { std::string word; while (is >> word) { // send the word to the output iterator *dest = word; } }  ...
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...
#ObjectIcon
ObjectIcon
# -*- ObjectIcon -*-   import io import ipl.numbers # For the "commas" procedure. import ipl.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", ...
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...
#OCaml
OCaml
(* The Rosetta Code integer square root task, in OCaml, using Zarith for large integers.   Compile with, for example:   ocamlfind ocamlc -package zarith -linkpkg -o isqrt isqrt.ml   Translated from the Scheme. *)   let find_a_power_of_4_greater_than_x x = let open Z in let rec loop q = if x < q t...
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...
#Go
Go
package main   import ( "bufio" "bytes" "errors" "fmt" "io" "os" )   // inverted index representation var index map[string][]int // ints index into indexed var indexed []doc   type doc struct { file string title string }   func main() { // initialize representation index = make(...
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...
#JavaScript
JavaScript
if (typeof bloop !== "undefined") { ... }
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...
#jq
jq
jq --arg version $(jq --version) '$version'
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...
#jq
jq
# A control structure, for convenience: # as soon as "condition" is true, then emit . and stop: def do_until(condition; next): def u: if condition then . else (next|u) end; u;   # n is the initial number; every k-th prisoner is removed until m remain. # Solution by simulation def josephus(n;k;m): reduce range(0...
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"...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Iterator Function Loopy(Of T)(seq As IEnumerable(Of T)) As IEnumerable(Of T) While True For Each element In seq Yield element Next End While End Function   Iterator Function T...
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...
#M4
M4
$ m4 define(`f',`$1`'$3`'$3`'$2') ==> f(`Rosetta',`Code',`:') ==>Rosetta::Code m4exit
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...
#Maple
Maple
$ maple
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
$ math
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)   ...
#PL.2FM
PL/M
100H:   CHECK$ISBN13: PROCEDURE (PTR) BYTE; DECLARE PTR ADDRESS, ISBN BASED PTR BYTE; DECLARE (I, F, T) BYTE; F = 1; T = 0; DO I = 0 TO 13; IF I = 3 THEN DO; /* THIRD CHAR SHOULD BE '-' */ IF ISBN(I) <> '-' THEN RETURN 0; END; ELSE DO; /* D...
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)   ...
#PowerShell
PowerShell
  function Get-ISBN13 { $codes = ( "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" )   foreach ($line in $codes) {   $sum = $null $codeNoDash = $line.Replace("-","")   for ($i = 0; $i -lt $codeNoDash.length; $i++) {   ...
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...
#Rust
Rust
use std::cmp;   pub fn jaro(s1: &str, s2: &str) -> f64 { let s1_len = s1.len(); let s2_len = s2.len(); if s1_len == 0 && s2_len == 0 { return 1.0; } let match_distance = cmp::max(s1_len, s2_len) / 2 - 1; let mut s1_matches = vec![false; s1_len]; let mut s2_matches = vec![false; s2_len]; let ...
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...
#Scala
Scala
object Jaro extends App {   def distance(s1: String, s2: String): Double = { val s1_len = s1.length val s2_len = s2.length if (s1_len == 0 && s2_len == 0) return 1.0 val match_distance = Math.max(s1_len, s2_len) / 2 - 1 val s1_matches = Array.ofDim[Boolean](s1_len) va...
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AArch64_Assembly
AArch64 Assembly
.equ STDOUT, 1 .equ SVC_WRITE, 64 .equ SVC_EXIT, 93   .text .global _start   _start: stp x29, x30, [sp, -16]! mov x0, #123 mov x1, #456 mov x29, sp bl integer_compare // integer_compare(123, 456); mov x0, #-123 mov x1, #-456 bl integer_compare // integer_compare(-123, -456); mov x0, #123 mov x1, #123 bl inte...
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ABAP
ABAP
  report z_integer_comparison.   parameters: a type int4, b type int4.   data(comparison_result) = cond string( when a < b " can be replaced by a lt b then |{ a } is less than { b }| when a = b " can be replaced by a eq b then |{ a } is equal to { b }| when a > b " can be replaced by a gt b then |{ a } is g...
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...
#Coco
Coco
class Animal class Cat extends Animal class Dog extends Animal class Lab extends Dog class Collie extends Dog
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...
#Comal
Comal
STRUC Animal DIM Species$ OF 20 ENDSTRUC Animal   STRUC Dog INHERIT Animal DIM Race$ OF 20 FUNC New CONSTRUCTOR Species$="Dog" ENDFUNC New ENDSTRUC Dog   STRUC Cat INHERIT Animal ...
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...
#Common_Lisp
Common Lisp
(defclass animal () ()) (defclass dog (animal) ()) (defclass lab (dog) ()) (defclass collie (dog) ()) (defclass cat (animal) ())
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...
#Quackery
Quackery
[ abs 0 swap [ base share /mod dup * rot + swap dup 0 = until ] drop ] is digitsquaresum ( n --> n )   [ dup 1 != while dup 89 != while digitsquaresum again ] is chainends ( n --> n )   0 1000000 times [ i^ 1+ chainends 89 = + ] echo
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...
#Racket
Racket
#lang racket ;; Tim-brown 2014-09-11   ;; The basic definition. ;; It is possible to memoise this or use fixnum (native) arithmetic, but frankly iterating over a ;; hundred million, billion, trillion numbers will be slow. No matter how you do it. (define (digit^2-sum n) (let loop ((n n) (s 0)) (if (= 0 n) s (let-...
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...
#C
C
#include <stdio.h>   int main() { unsigned int i = 0; while (++i) printf("%u\n", i);   return 0; }
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...
#C.23
C#
using System; using System.Numerics;   class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Arturo
Arturo
print infinity print neg infinity
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#AWK
AWK
BEGIN { k=1; while (2^(k-1) < 2^k) k++; INF = 2^k; print INF; }
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#BASIC256
BASIC256
onerror TratoError infinity = 1e300*1e300 end   TratoError: if lasterror = 29 then print lasterrormessage return
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...
#Icon_and_Unicon
Icon and Unicon
class Camera (instanceVars) # methods... # initializer... end   class Phone (instanceVars) # methods... # initializer... end   class CameraPhone : Camera, Phone (instanceVars) # methods... # initialiser... end
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...
#Io
Io
Camera := Object clone Camera click := method("Taking snapshot" println)   MobilePhone := Object clone MobilePhone call := method("Calling home" println)   CameraPhone := Camera clone CameraPhone appendProto(MobilePhone)   myPhone := CameraPhone clone myPhone click // --> "Taking snapshot" myPhone call // --> "Calling ...
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...
#Ioke
Ioke
Camera = Origin mimic MobilePhone = Origin mimic CameraPhone = Camera mimic mimic!(MobilePhone)
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...
#J
J
coclass 'Camera'   create=: verb define NB. creation-specifics for a camera go here )   destroy=: codestroy   NB. additional camera methods go here   coclass 'MobilePhone'   create=: verb define NB. creation-specifics for a mobile phone go here )   destroy=: codestroy   NB. additional phone methods go here   coclas...
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#C
C
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   // Returns the sum of the digits of n given the // sum of the digits of n - 1 uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; }   inline...
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#C.2B.2B
C++
#include <cstdint> #include <iomanip> #include <iostream>   // Returns the sum of the digits of n given the // sum of the digits of n - 1 uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; }   inline bool divisible(uint64...
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...
#Haskell
Haskell
import Data.Int import Data.Word import Control.Exception   f x = do catch (print x) (\e -> print (e :: ArithException))   main = do f ((- (-2147483647 - 1)) :: Int32) f ((2000000000 + 2000000000) :: Int32) f (((-2147483647) - 2147483647) :: Int32) f ((46341 * 46341) :: Int32) f ((((-2147483647) - 1) `div` ...
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.
#Clojure
Clojure
(defn basic-input [fname] (line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. input-loop.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT in-stream ASSIGN TO KEYBOARD *> or any other file/stream ORGANIZATION LINE SEQUENTIAL FILE STATUS in-stream-status.   DAT...
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...
#Ol
Ol
  (print "Integer square roots of 0..65") (for-each (lambda (x) (display (isqrt x)) (display " ")) (iota 66)) (print)   (print "Integer square roots of 7^n") (for-each (lambda (x) (print "x: " x ", isqrt: " (isqrt x))) (map (lambda (i) (expt 7 i)) (iota 73 1))) (print)  
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...
#Pascal
Pascal
  //************************************************// // // // Thanks for rvelthuis for BigIntegers library // // https://github.com/rvelthuis/DelphiBigNumbers // // // //************************************************// ...
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...
#Haskell
Haskell
import Control.Monad import Data.Char (isAlpha, toLower) import qualified Data.Map as M import qualified Data.IntSet as S import System.Environment (getArgs)   main = do (files, _ : q) <- liftM (break (== "--")) getArgs buildII files >>= mapM_ putStrLn . queryII q   data IIndex = IIndex [FilePath] ...
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...
#Jsish
Jsish
/* Introspection, in jsish */ if (Info.version() < Util.verConvert('2.8.6')) { puts("need at least version 2.8.6 of jsish for this application"); exit(1); }   /* Check for "abs()" as function and "bloop" as defined value, call if both check true */ if ((bloop != undefined) && (typeof Math.abs == 'function')) { ...
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...
#Julia
Julia
@show VERSION VERSION < v"0.4" && exit(1)   if isdefined(Base, :bloop) && !isempty(methods(abs)) @show abs(bloop) end   a, b, c = 1, 2, 3 vars = filter(x -> eval(x) isa Integer, names(Main)) println("Integer variables: ", join(vars, ", "), ".") println("Sum of integers in the global scope: ", sum(eval.(vars)), ".")
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...
#Julia
Julia
using Memoize @memoize josephus(n::Integer, k::Integer, m::Integer=1) = n == m ? collect(0:m .- 1) : mod.(josephus(n - 1, k, m) + k, n)   @show josephus(41, 3) @show josephus(41, 3, 5)
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"...
#Wren
Wren
import "/dynamic" for Struct import "/sort" for Sort import "/fmt" for Fmt   var Wheel = Struct.create("Wheel", ["next", "values"])   var generate = Fn.new { |wheels, start, maxCount| var count = 0 var w = wheels[start] while (true) { var s = w.values[w.next] var v = Num.fromString(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...
#MATLAB_.2F_Octave
MATLAB / Octave
  >> f = @(str1, str2, delim) [str1, delim, delim, str2];  
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...
#Maxima
Maxima
(%i1) f(a, b, c) := sconcat(a, c, c, b)$ (%i2) f("Rosetta", "Code", ":"); (%o2) "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...
#min
min
$ (dup suffix swap suffix suffix) :glue $ "Rosetta" "Code" ":" glue puts! 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)   ...
#PureBasic
PureBasic
Macro TestISBN13(X) Print(X) If IsISBN13(X) : PrintN(" good") : Else : PrintN(" bad") : EndIf EndMacro   Procedure.b IsISBN13(ISBN13.s) ISBN13=Left(ISBN13,3)+Mid(ISBN13,5) If IsNAN(Val(ISBN13)) Or Len(ISBN13)<>13 : ProcedureReturn #False : EndIf Dim ISBN.s{1}(12) : PokeS(@ISBN(),ISBN13) For i=0 T...
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...
#Sidef
Sidef
func jaro(s, t) {   return 1 if (s == t)   var s_len = s.len var t_len = t.len   var match_distance = ((s_len `max` t_len) // 2 - 1)   var s_matches = [] var t_matches = []   var matches = 0 var transpositions = 0   for i (^s_len) { var start = (0 `max` i-match_distance) ...
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Action.21
Action!
PROC Main() INT a,b   Print("Input value of a:") a=InputI() Print("Input value of b:") b=InputI()   IF a<b THEN PrintF("%I is less than %I%E",a,b) FI IF a>b THEN PrintF("%I is greater than %I%E",a,b) FI IF a=b THEN PrintF("%I is equal to %I%E",a,b) FI RETURN
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_Io;   procedure Compare_Ints is A, B : Integer; begin Get(Item => A); Get(Item => B);   -- Test for equality if A = B then Put_Line("A equals B"); end if;   -- Test For Less Than if A < B then Put_Line(...
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...
#Component_Pascal
Component Pascal
  TYPE Animal = ABSTRACT RECORD (* *) END; Cat = RECORD (Animal) (* *) END; (* final record (cannot be extended) - by default *) Dog = EXTENSIBLE RECORD (Animal) (* *) END; (* extensible record *) Lab = RECORD (Dog) (* *) END; Collie = RECORD (Dog) (* *) END;  
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...
#D
D
class Animal { // ... }   class Dog: Animal { // ... }   class Lab: Dog { // ... }   class Collie: Dog { // ... }   class Cat: Animal { // ... }   void main() {}
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...
#Raku
Raku
constant @sq = ^10 X** 2; my $cnt = 0;   sub Euler92($n) { $n == any(1,89) ?? $n !! (state %){$n} //= Euler92( [+] @sq[$n.comb] ) }   for 1 .. 1_000_000 -> $n { my $i = +$n.comb.sort.join; ++$cnt if Euler92($i) == 89; }   say $cnt;
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#11l
11l
F rank(x) R BigInt(([1] [+] x).map(String).join(‘A’), radix' 11)   F unrank(n) V s = String(n, radix' 11) R s.split(‘A’).map(Int)[1..]   V l = [1, 2, 3, 10, 100, 987654321] print(l) V n = rank(l) print(n) l = unrank(n) print(l)
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...
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <limits>   int main() { auto i = std::uintmax_t{};   while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
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...
#ChucK
ChucK
  for(1 => int i; i < Math.INT_MAX; i ++) { <<< i >>>; }  
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#BBC_BASIC
BBC BASIC
*FLOAT 64 PRINT FNinfinity END   DEF FNinfinity LOCAL supported%, maxpos, prev, inct supported% = TRUE ON ERROR LOCAL supported% = FALSE IF supported% THEN = 1/0 RESTORE ERROR inct = 1E10 REPEAT prev = maxpos inct *= 2 ON ERROR LO...
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#bootBASIC
bootBASIC
10 print 1/0
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#BQN
BQN
∞ + 1 ∞ ∞ - 3 ∞ -∞ ¯∞ ∞ - ∞ NaN
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...
#Java
Java
public interface Camera{ //functions here with no definition... //ex: //public void takePicture(); }
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...
#Julia
Julia
  abstract type Phone end   struct DeskPhone <: Phone book::Dict{String,String} end   abstract type Camera end   struct kodak roll::Vector{Array{Int32,2}} end   struct CellPhone <: Phone book::Dict{String,String} roll::Vector{AbstractVector} end   function dialnumber(phone::CellPhone) printl...