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... | #Perl | Perl | use warnings;
use strict;
my @sq = map { $_ ** 2 } 0 .. 9;
my %cache;
my $cnt = 0;
sub Euler92 {
my $n = 0 + join( '', sort split( '', shift ) );
$cache{$n} //= ($n == 1 || $n == 89) ? $n :
Euler92( sum( @sq[ split '', $n ] ) )
}
sub sum {
my $sum;
$sum += shift while @_;
$sum;
}
for (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... | #BASIC | BASIC | 10 LET A = 0
20 LET A = A + 1
30 PRINT A
40 GO TO 20 |
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... | #BASIC256 | BASIC256 | i = 1
do
print i
i += 1
until 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... | #C.2B.2B | C++ | class Camera
{
// ...
};
class MobilePhone
{
// ...
};
class CameraPhone:
public Camera,
public 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... | #Clojure | Clojure | (defprotocol Camera)
(defprotocol MobilePhone)
(deftype CameraPhone []
Camera
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... | #COBOL | COBOL | CLASS-ID. Camera.
*> ...
END CLASS Camera.
CLASS-ID. Mobile-Phone.
*> ...
END CLASS Mobile-Phone.
CLASS-ID. Camera-Phone INHERITS Camera, Mobile-Phone.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
CLASS Camera
... |
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... | #Clojure | Clojure | (* -1 (dec -9223372036854775807))
(+ 5000000000000000000 5000000000000000000)
(- -9223372036854775807 9223372036854775807)
(* 3037000500 3037000500) |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. PROCRUSTES-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-EXAMPLE.
05 X PIC 999.
PROCEDURE DIVISION.
MOVE 1002 TO X.
DISPLAY X UPON CONSOLE.
STOP RUN. |
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.
| #AmigaE | AmigaE | CONST BUFLEN=1024, EOF=-1
PROC consume_input(fh)
DEF buf[BUFLEN] : STRING, r
REPEAT
/* even if the line si longer than BUFLEN,
ReadStr won't overflow; rather the line is
"splitted" and the remaining part is read in
the next ReadStr */
r := ReadStr(fh, buf)
IF buf[] OR (r <> EOF)
... |
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.
| #APL | APL |
h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
⍴h
7 49
]boxing 8
h
┌→────────────────────────────────────────────────┐
↓This is some sample text. │
│The text itself has multiple lines, and │
│the text has some words that occur multiple times│
│in the text. ... |
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... | #Lua | Lua | function isqrt(x)
local q = 1
local r = 0
while q <= x do
q = q << 2
end
while q > 1 do
q = q >> 2
local t = x - r - q
r = r >> 1
if t >= 0 then
x = t
r = r + q
end
end
return r
end
print("Integer square root for numbe... |
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... | #Delphi | Delphi |
program Inverted_index;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
system.Generics.Collections,
SYstem.IOUtils;
type
TIndex = class
private
FFileNames: TArray<string>;
FIndexs: TDictionary<string, string>;
class function SplitWords(Text: string): TArray<string>; static;
function StoreFil... |
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... | #Go | Go | package main
import (
"debug/elf"
"debug/gosym"
"fmt"
"log"
"math"
"os"
"runtime"
)
var bloop = -3.4
func main() {
fmt.Println("task 1: verify version")
fmt.Println(" program compiled with", runtime.Version())
fmt.Println("task 2: check for presence of variable and func... |
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... | #Haskell | Haskell | import Data.List ((\\))
import System.Environment (getArgs)
prisoners :: Int -> [Int]
prisoners n = [0 .. n - 1]
counter :: Int -> [Int]
counter k = cycle [k, k-1 .. 1]
killList :: [Int] -> [Int] -> ([Int], [Int], [Int])
killList xs cs = (killed, survivors, newCs)
where
(killed, newCs) = kill xs cs []... |
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"... | #Phix | Phix | with javascript_semantics
function terms(sequence wheels, integer n)
sequence res = repeat(' ',n),
pos = repeat(2,length(wheels)),
wvs = vslice(wheels,1)
integer wheel = 1, rdx = 1
while rdx<=n do
integer p = pos[wheel],
c = wheels[wheel][p]
p = iff(... |
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... | #Java | Java |
public static void main(String[] args) {
System.out.println(concat("Rosetta", "Code", ":"));
}
public static String concat(String a, String b, String c) {
return a + c + c + b;
}
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... | #JavaScript | JavaScript | $ java -cp js.jar org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2009 03 22
js> function f(a,b,s) {return a + s + s + b;}
js> f('Rosetta', 'Code', ':')
Rosetta::Code
js> quit()
$ |
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)
... | #Nanoquery | Nanoquery | def checkIsbn13(isbn)
// remove any hyphens or spaces
isbn = str(isbn).replace("-","").replace(" ","")
// check length = 13
if len(isbn) != 13
return false
end
// check only contains digits and calculate weighted sum
sum = 0
for i in ra... |
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... | #Racket | Racket | #lang racket/base
;; {{trans|C}}
(require data/bit-vector)
(define (jaro-distance str1 str2)
(define str1-len (string-length str1))
(define str2-len (string-length str2))
(cond
[(and (zero? str1-len) (zero? str2-len)) 0]
[(or (zero? str1-len) (zero? str2-len)) 1]
[else
;; vectors of bools... |
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... | #ActionScript | ActionScript | public class 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... | #Ada | Ada | package Inheritance is
type Animal is tagged private;
type Dog is new Animal with private;
type Cat is new Animal with private;
type Lab is new Dog with private;
type Collie is new Dog with private;
private
type Animal is tagged null record;
type Dog is new Animal with null record;
type Cat is 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... | #Phix | Phix | with javascript_semantics
constant MAXINT = power(2,iff(machine_bits()=32?53:64))
procedure main(integer limit)
sequence sums = repeat(0,limit*81+1)
sums[1] = 1
for n=1 to limit do
for i=n*81 to 1 by -1 do
for j=1 to 9 do
integer s = j*j, i1= i+1, i1ms = i1-s
... |
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... | #Batch_File | Batch File |
@echo off
set number=0
:loop
set /a number+=1
echo %number%
goto loop
|
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... | #BBC_BASIC | BBC BASIC | *FLOAT 64
REPEAT
i += 1
PRINT TAB(0,0) i;
UNTIL FALSE |
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... | #Common_Lisp | Common Lisp | (defclass camera () ())
(defclass mobile-phone () ())
(defclass 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... | #D | D | interface Camera {
// member function prototypes and static methods
}
interface MobilePhone {
// member function prototypes and static methods
}
class CameraPhone: Camera, MobilePhone {
// member function implementations for Camera,
// MobilePhone, and 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... | #Delphi | Delphi | type
ICamera = Interface
// ICamera methods...
end;
IMobilePhone = Interface
// IMobilePhone methods...
end;
TCameraPhone = class(TInterfacedObject, ICamera, IMobilePhone)
// ICamera and IMobilePhone methods...
end; |
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... | #Computer.2Fzero_Assembly | Computer/zero Assembly | LDA ff
ADD one
...
ff: 255
one: 1 |
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... | #D | D | void main() @safe {
import std.stdio;
writeln("Signed 32-bit:");
writeln(-(-2_147_483_647 - 1));
writeln(2_000_000_000 + 2_000_000_000);
writeln(-2147483647 - 2147483647);
writeln(46_341 * 46_341);
writeln((-2_147_483_647 - 1) / -1);
writeln("\nSigned 64-bit:");
writeln(-(-9_223_... |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program inputLoop.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/************************************... |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
R INTEGER SQUARE ROOT OF X
INTERNAL FUNCTION(X)
ENTRY TO ISQRT.
Q = 1
FNDPW4 WHENEVER Q.LE.X
Q = Q * 4
TRANSFER TO FNDPW4
END OF CONDITIONAL
Z = X
R = 0
FNDRT ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ISqrt]
ISqrt[x_Integer?NonNegative] := Module[{q = 1, z, r, t},
While[q <= x,
q *= 4
];
z = x;
r = 0;
While[q > 1,
q = Quotient[q, 4];
t = z - r - q;
r /= 2;
If[t >= 0,
z = t;
r += q
];
];
r
]
ISqrt /@ Range[65]
Column[ISqrt /@ (7^Range[1, 73])] |
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... | #EchoLisp | EchoLisp |
;; set of input files
(define FILES {T0.txt T1.txt T2.txt})
;; store name for permanent inverted index
(define INVERT "INVERTED-INDEX")
;; get text for each file, and call (action filename text)
(define (map-files action files)
(for ((file files))
(file->string action file)))
;; create store
(local-make-s... |
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... | #Haskell | Haskell | import Data.Version
import Control.Monad
import System.Info
minGHCVersion = Version [6, 8] []
main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $
fail "Compiler too old." |
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... | #Icon_and_Unicon | Icon and Unicon | global bloop
procedure main(A)
if older(11,7) then stop("Must have version >= 11.7!")
bloop := -5 # global variable
floop := -11.3 # local variable
write(proc("abs")(variable("bloop")))
write(proc("abs")(variable("floop")))
end
procedure older(maj,min)
&version ? {
(tab(... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
m := integer(A[1]) | 41
c := integer(A[2]) | 3
write("With ",m," men, counting to ",c," last position is: ", j(m,c))
end
procedure j(m,c)
return if m==1 then 0 else (j(m-1,c)+c)%m
end |
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"... | #Python | Python | from itertools import islice
class INW():
"""
Intersecting Number Wheels
represented as a dict mapping
name to tuple of values.
"""
def __init__(self, **wheels):
self._wheels = wheels
self.isect = {name: self._wstate(name, wheel)
for name, wheel in whee... |
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... | #Jsish | Jsish | prompt$ jsish
Jsish interactive: see 'help [cmd]'
# function f(a:string, b:string, s:string):string { return a+s+s+b; }
# f('Rosetta', 'Code', 1)
warn: type mismatch for argument arg 3 's': expected "string" but got "number", in call to 'f' <1>. (at or near "Code")
"Rosetta11Code"
# f('Rosetta', 'Code', ':')
"Roset... |
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... | #Julia | Julia | usr@host:~/rosetta/julia$ julia
_
_ _ _(_)_ | A fresh approach to technical computing
(_) | (_) (_) | Documentation: http://docs.julialang.org
_ _ _| |_ __ _ | Type "help()" for help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 0.3.7 (2015-03-23 21:36 UTC)
... |
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... | #K | K | $ rlwrap k
K Console - Enter \ for help
f:{x,z,z,y}
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)
... | #Nim | Nim | import strutils, strformat
func is_isbn*(s: string): bool =
var sum, len: int
for c in s:
if is_digit(c):
sum += (ord(c) - ord('0')) * (if len mod 2 == 0: 1 else: 3)
len += 1
elif c != ' ' and c != '-':
return false
return (len == 13) and (sum mod 10 == 0)
when is_main_module:
let ... |
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)
... | #Pascal | Pascal | program ISBNChecksum(output);
const
codeIndexMaximum = 17;
ISBNIndexMinimum = 1;
ISBNIndexMaximum = 13;
ISBNIndexRange = ISBNIndexMaximum - ISBNIndexMinimum + 1;
type
code = string(codeIndexMaximum);
codeIndex = 1..codeIndexMaximum value 1;
decimalDigit = '0'..'9';
decimalValue = 0..9;
ISBNIndex = ISBNInde... |
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... | #Raku | Raku | sub jaro ($s, $t) {
return 1 if $s eq $t;
my $s_len = + my @s = $s.comb;
my $t_len = + my @t = $t.comb;
my $match_distance = ($s_len max $t_len) div 2 - 1;
my ($matches, @s_matches, @t_matches);
for ^@s -> $i {
my $start = 0 max $i - $match_distance;
my $end = $i + $match_d... |
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 |... | #11l | 11l | V a = Int(input(‘Enter value of a: ’))
V b = Int(input(‘Enter value of b: ’))
I a < b
print(‘a is less than b’)
I a > b
print(‘a is greater than b’)
I a == b
print(‘a is equal to b’) |
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... | #Aikido | Aikido | class Animal{
//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... | #AmigaE | AmigaE |
OBJECT animal
ENDOBJECT
OBJECT dog OF animal
ENDOBJECT
OBJECT cat OF animal
ENDOBJECT
OBJECT lab OF dog
ENDOBJECT
OBJECT collie OF dog
ENDOBJECT
|
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... | #AppleScript | AppleScript | script Animal
end script
script Dog
property parent : Animal
end script
script Cat
property parent : Animal
end script
script Lab
property parent : Dog
end script
script Collie
property parent : Dog
end script |
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... | #PicoLisp | PicoLisp | (de *Idx1or89 (89 . 89) ((1 . 1)))
(de 1or89 (N)
(let L (mapcar format (chop N))
(if (lup *Idx1or89 (setq N (sum * L L)))
(cdr @)
(prog1
(1or89 N)
(idx '*Idx1or89 (cons N @) T) ) ) ) ) |
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... | #PL.2FI | PL/I |
test: procedure options (main, reorder); /* 6 August 2015 */
declare (m, n) fixed decimal (10);
declare (i, j, p, s, tally initial (0) ) fixed binary (31);
declare d fixed binary (7);
declare (start_time, finish_time, elapsed_time) float (15);
start_time = secs();
do m = 1 to 1000000;
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... | #bc | bc | while (++i) 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... | #beeswax | beeswax | qNP<
_1>{d |
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... | #DWScript | DWScript | def minherit(self, supers) {
def forwarder match [verb, args] {
escape __return {
if (verb == "__respondsTo") {
def [verb, arity] := args
for super ? (super.__respondsTo(verb, arity)) in supers {
return true
}
re... |
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... | #E | E | def minherit(self, supers) {
def forwarder match [verb, args] {
escape __return {
if (verb == "__respondsTo") {
def [verb, arity] := args
for super ? (super.__respondsTo(verb, arity)) in supers {
return true
}
re... |
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... | #Factor | Factor | #include <stdio.h> |
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... | #Fortran | Fortran | #include <stdio.h> |
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.
| #AutoHotkey | AutoHotkey | Loop, Read, Input.txt, Output.txt
{
FileAppend, %A_LoopReadLine%`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.
| #AWK | AWK | { print $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... | #Maxima | Maxima | /* -*- Maxima -*- */
/*
The Rosetta Code integer square root task, in Maxima.
I have not tried to make the output conform quite to the task
description, because Maxima is not a general purpose programming
language. Perhaps someone else will care to do it.
I *do* check that the Rosetta Code routine gives the sam... |
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... | #Mercury | Mercury | :- module isqrt_in_mercury.
:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
:- implementation.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module integer. % Integers of arbitrary size.
:- import_module list.
:- import_module string.
... |
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... | #Erlang | Erlang |
-module( inverted_index ).
-export( [from_files/1, search/2, task/0] ).
from_files( Files ) ->
lists:foldl( fun import_from_file/2, dict:new(), Files ).
search( Binaries, Inverted_index ) ->
[Files | T] = [dict:fetch(X, Inverted_index) || X <- Binaries],
lists:foldl( fun search_common/2,... |
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... | #Inform_7 | Inform 7 | Home is a room.
When play begins:
let V be the current runtime version;
if V is less than the required runtime version:
say "Version [required runtime version] required, but [V] found.";
otherwise:
say "Your interpreter claims version [V].";
end the story.
A version is a kind of value.
Section - Checking ... |
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... | #Io | Io | if(System version < 20080000, exit)
if(hasSlot("bloop") and bloop hasSlot("abs"), bloop abs) |
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... | #J | J | 3 ([ (1 }. <:@[ |. ])^:(1 < #@])^:_ i.@]) 41
30 |
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"... | #Quackery | Quackery | [ ]this[ ]done[
dup take behead
dup dip
[ nested join
swap put ]
do ] is wheel ( --> n )
[ ]'[
]'[ nested
' [ wheel ]
swap join
swap replace ] is newwheel ( --> )
forward is A forward is B forward is C
forward is D ( a... |
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"... | #Raku | Raku |
#| advance rotates a named wheel $n by consuming an item from an infinite sequence. It is called
#| from within a gather block and so can use take in order to construct an infinite, lazy sequence
#| of result values
sub advance($g, $n) {
given $g{$n}.pull-one {
when /\d/ { take $_ }
default { samewith $g, $_ }... |
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... | #Kotlin | Kotlin | c:\kotlin-compiler-1.0.6>kotlinc
Welcome to Kotlin version 1.0.6-release-127 (JRE 1.8.0_31-b13)
Type :help for help, :quit for quit
>>> fun f(s1: String, s2: String, sep: String) = s1 + sep + sep + s2
>>> f("Rosetta", "Code", ":")
Rosetta::Code
>>> :quit |
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... | #Lasso | Lasso | #!/usr/bin/lasso9
// filename: interactive_demo
define concatenate_with_delimiter(
string1::string,
string2::string,
delimiter::string
) => #string1 + (#delimiter*2) + #string2
define read_input(prompt::string) => {
local(string)
// display prompt
stdout(#prompt)
// the following bits wait until the ... |
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)
... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub check_digit {
my($isbn) = @_; my($sum);
$sum += (1,3)[$_%2] * (split '', join '', split /\D/, $isbn)[$_] for 0..11;
(10 - $sum % 10) % 10;
}
for (<978-1734314502 978-1734314509 978-1788399081 978-1788399083 978-2-74839-908-0 978-2-74839-908-5>) {
my($... |
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... | #REXX | REXX | /*REXX program computes the Jaro distance between two strings (or a list of strings).*/
@.= /*define a default for the @. array. */
parse arg @.1 /*obtain an optional character string. */
if @.1='' then do; @.1= 'MARTHA MARHTA' ... |
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 |... | #360_Assembly | 360 Assembly | INTCOMP PROLOG
* Reg1=Addr(Addr(argA),Addr(argB))
L 2,0(1) Reg2=Addr(argA)
L 3,4(1) Reg3=Addr(argB)
L 4,0(2) Reg4=argA
L 5,0(3) Reg5=argA
ST 4,A Store R4 in A
ST 5,B 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 |... | #6502_Assembly | 6502 Assembly | Compare PHA ;push Accumulator onto stack
JSR GetUserInput ;routine not implemented
;integers to compare now in memory locations A and B
LDA A
CMP B ;sets flags as if a subtraction (a - b) had been carried out
BCC A_less_than_B ;branch if carry clear
BEQ A_equals_B ;branch if equal
;else A greater th... |
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... | #AutoHotkey | AutoHotkey | dog := new Collie
MsgBox, % "A " dog.__Class " is a " dog.base.base.__Class " and is part of the " dog.kingdom " kingdom."
class Animal {
static kingdom := "Animalia" ; Class variable
}
class Dog extends Animal {
}
class Cat 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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"CLASSLIB"
DIM Animal{method}
PROC_class(Animal{})
DIM Cat{method}
PROC_inherit(Cat{}, Animal{})
PROC_class(Cat{})
DIM Dog{method}
PROC_inherit(Dog{}, Animal{})
PROC_class(Dog{})
DIM Labrador{method}
PROC_inherit(Labrador{}, 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... | #C | C | class Animal
{
/* ... */
// ...
}
class Dog : Animal
{
/* ... */
// ...
}
class Lab : Dog
{
/* ... */
// ...
}
class Collie : Dog
{
/* ... */
// ...
}
class 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... | #PureBasic | PureBasic | OpenConsole()
Procedure is89(x)
Repeat
s=0
While x : s+ x%10*x%10 : x/10 : Wend
If s=89 : ProcedureReturn 1 : EndIf
If s=1 : ProcedureReturn 0 : EndIf
x=s
ForEver
EndProcedure
Procedure main()
Dim sums(32*81+1) : sums(0)=1 : sums(1)=0
For n=1 To n+1
For i=n*81 To 1 Step -1
For... |
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... | #Befunge | Befunge | 1+:0`!#@_:.55+, |
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... | #BQN | BQN | _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(1+•Show) _while_ (≤⟜∞) 1 |
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... | #11l | 11l | print(Float.infinity) |
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... | #Eiffel | Eiffel | class
CAMERA
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... | #Elena | Elena | singleton CameraFeature
{
cameraMsg
= "camera";
}
class MobilePhone
{
mobileMsg
= "phone";
}
class CameraPhone : MobilePhone
{
dispatch() => CameraFeature;
}
public program()
{
var cp := new CameraPhone();
console.writeLine(cp.cameraMsg);
console.writeLine(cp.mobileMsg)
} |
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... | #F.23 | F# | type Picture = System.Drawing.Bitmap // (a type synonym)
// an interface type
type Camera =
abstract takePicture : unit -> Picture
// an interface that inherits multiple interfaces
type Camera2 =
inherits System.ComponentModel.INotifyPropertyChanged
inherits Camera
// a class with an abstract method with 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... | #11l | 11l | F digit_sum(=n, =sum)
sum++
L n > 0 & n % 10 == 0
sum -= 9
n /= 10
R sum
V previous = 1
V gap = 0
V s = 0
V niven_index = 0
V gap_index = 1
print(‘Gap index Gap Niven index Niven number’)
V niven = 1
L gap_index <= 22
s = digit_sum(niven, s)
I niven % s == 0
I niven > pre... |
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... | #FreeBASIC | FreeBASIC | #include <stdio.h> |
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... | #Frink | Frink | 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.
| #BASIC | BASIC | f = freefile
open f, "test.txt"
while not eof(f)
linea$ = readline(f)
print linea$ # echo to the console
end while
close f
end |
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.
| #Batch_File | Batch File |
for /f %%i in (file.txt) do if %%i@ neq @ echo %%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... | #Modula-2 | Modula-2 |
MODULE IntSqrt;
IMPORT IO;
(* Procedure to find integer square root of a 32-bit unsigned integer. *)
PROCEDURE Isqrt( X : LONGCARD) : LONGCARD;
VAR
Xdiv4, q, r, s, z : LONGCARD;
BEGIN
Xdiv4 := X DIV 4;
q := 1;
WHILE q <= Xdiv4 DO q := 4*q; END;
z := X;
r := 0;
REPEAT
s := q + r;
r := r DIV 2... |
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... | #F.23 | F# | open System
open System.IO
// Map search terms to associated set of files
type searchIndexMap = Map<string, Set<string>>
let inputSearchCriteria() =
let readLine prompt =
printf "%s: " prompt
Console.ReadLine().Split()
readLine "Files", (readLine "Find") |> Array.map (fun s -> s.ToLower())... |
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... | #IS-BASIC | IS-BASIC | 100 IF VERNUM<2.1 THEN PRINT "Version is too old.":STOP
110 WHEN EXCEPTION USE ERROR
120 PRINT ABS(BLOOP)
130 END WHEN
140 HANDLER ERROR
150 PRINT EXSTRING$(EXTYPE)
160 CONTINUE
170 END HANDLER |
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... | #J | J | 6 (2!:55@:]^:>) 0 ". 1 { 9!:14'' |
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... | #Java | Java | import java.util.ArrayList;
public class Josephus {
public static int execute(int n, int k){
int killIdx = 0;
ArrayList<Integer> prisoners = new ArrayList<Integer>(n);
for(int i = 0;i < n;i++){
prisoners.add(i);
}
System.out.println("Prisoners executed in order:... |
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"... | #REXX | REXX | /*REXX program expresses numbers from intersecting number wheels (or wheel sets). */
@.= /*initialize array to hold the wheels. */
parse arg lim @.1 /*obtain optional arguments from the CL*/
if lim='' | lim="," then lim= 20 ... |
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... | #Lambdatalk | Lambdatalk |
{def F {lambda {:a :b :s} :a:s:s:b}}
-> F
{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... | #Lingo | Lingo | > m=new(#script)
> m.scripttext="on conc(a,b,c)"&RETURN&"return a&c&c&b"&RETURN&"end"
> put 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... | #Logo | Logo | $ <i>logo</i>
Welcome to Berkeley Logo version 5.6
? <i>to f :prefix :suffix :separator</i>
> <i>output (word :prefix :separator :separator :suffix)</i>
> <i>end</i>
f defined
? <i>show f "Rosetta "Code ":</i>
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)
... | #Phix | Phix | with javascript_semantics
procedure check_isbn13(string isbn)
integer digits = 0, checksum = 0, w = 1
for i=1 to length(isbn) do
integer ch = isbn[i]
if ch!=' ' and ch!='-' then
ch -= '0'
if ch<0 or ch>9 then checksum = 9 exit end if
checksum += ch*w
... |
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... | #Ring | Ring |
# Project : Jaro distance
decimals(12)
see " jaro (MARTHA, MARHTA) = " + jaro("MARTHA", "MARHTA") + nl
see " jaro (DIXON, DICKSONX) = " + jaro("DIXON", "DICKSONX") + nl
see " jaro (JELLYFISH, SMELLYFISH) = " + jaro("JELLYFISH", "SMELLYFISH") + nl
func jaro(word1, word2)
if len(word1) > len(word2)
... |
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 |... | #8051_Assembly | 8051 Assembly | compare:
push psw
cjne a, b, clt
; a == b
; implement code here
jmp compare_
clt:
jc lt
; a > b
; implement code here
jmp compare_
lt:
; a < b
; implement code here
compare_:
pop psw
ret |
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... | #C.23 | C# | class Animal
{
/* ... */
// ...
}
class Dog : Animal
{
/* ... */
// ...
}
class Lab : Dog
{
/* ... */
// ...
}
class Collie : Dog
{
/* ... */
// ...
}
class Cat : 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... | #C.2B.2B | C++ | class Animal
{
// ...
};
class Dog: public Animal
{
// ...
};
class Lab: public Dog
{
// ...
};
class Collie: public Dog
{
// ...
};
class Cat: public Animal
{
// ...
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.