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/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... | #D | D | import std.bigint;
import std.conv;
import std.exception;
import std.range;
import std.regex;
import std.stdio;
//Taken from the task http://rosettacode.org/wiki/Commatizing_numbers#D
auto commatize(in char[] txt, in uint start=0, in uint step=3, in string ins=",") @safe
in {
assert(step > 0);
} body {
if (st... |
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... | #Elixir | Elixir |
defmodule Josephus do
def find(n,k) do
find(Enum.to_list(0..n-1),0..k-2,k..n)
end
def find([_|[r|_]],_,_..d) when d < 3 do
IO.inspect r
end
def find(arr,a..c,b..d) when length(arr) >= 3 do
find(Enum.slice(arr,b..d) ++ Enum.slice(arr,a..c),a..c,b..d-1)
end
end
Josephus.find(41,3)
|
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"... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Wheel {
char *seq;
int len;
int pos;
};
struct Wheel *create(char *seq) {
struct Wheel *w = malloc(sizeof(struct Wheel));
if (w == NULL) {
return NULL;
}
w->seq = seq;
w->len = strlen(seq);
w->pos = 0;
... |
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... | #BBC_BASIC | BBC BASIC | >r$ = "Rosetta"
>c$ = "Code"
>s$ = ":"
>PRINT r$+s$+s$+c$
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... | #bc | bc | $ »bc
»obase = ibase = 16
»1000 - 2
FFE
|
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... | #BQN | BQN | Join ← {a 𝕊 b‿c: b∾a∾a∾c}
(function block)
":" Join "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)
... | #Factor | Factor | USING: combinators.short-circuit formatting kernel math
math.functions math.parser math.vectors qw sequences
sequences.extras sets unicode ;
: (isbn13?) ( str -- ? )
string>digits
[ <evens> sum ] [ <odds> 3 v*n sum + ] bi 10 divisor? ;
: isbn13? ( str -- ? )
"- " without
{ [ length 13 = ] [ [ digit?... |
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)
... | #Forth | Forth | : is-digit [char] 0 - 10 u< ;
: isbn? ( a n -- f)
1- chars over + 2>r 0 1 2r> ?do
dup i c@ dup is-digit \ get length and factor, setup loop
if [char] 0 - * rot + swap 3 * 8 mod else drop drop then
-1 chars +loop drop 10 mod 0= \ now calculate checksum
; |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Jaro.bas"
110 DO
120 READ IF MISSING EXIT DO:A$,B$
130 PRINT A$;", ";B$;":";JARO(A$,B$)
140 LOOP
150 DEF JARO(A$,B$)
160 LET J=1:LET M,T,JARO=0:LET S1=LEN(A$):LET S2=LEN(B$)
170 IF S1>S2 THEN
180 LET Z$=A$:LET A$=B$:LET B$=Z$
190 LET Z=S1:LET S1=S2:LET S2=Z
200 END IF
210 LET MAXDIST=IN... |
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... | #Frink | Frink |
total = 0
d = new dict
var sum
for n = 1 to 100 million - 1
{
sum = n
do
{
if sum < 1000 and d@sum != undef
{
sum = d@sum
break
}
c = sum
sum = 0
for digit = integerDigits[c]
sum = sum + digit^2
} while (sum != 89) and (sum != 1)
i... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
)
func main() {
var d, n, o, u, u89 int64
for n = 1; n < 100000000; n++ {
o = n
for {
u = 0
for {
d = o%10
o = (o - d) / 10
u += d*d
if o == 0 {
break
}
}
if u == 89 || u == 1 {
if u == 89 { u89++ }
break
}
o = u
}
}
fmt.Pr... |
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... | #Delphi | Delphi | /* Integer square root using quadratic residue method */
proc nonrec isqrt(ulong x) ulong:
ulong q, z, r;
long t;
q := 1;
while q <= x do q := q << 2 od;
z := x;
r := 0;
while q > 1 do
q := q >> 2;
t := z - r - q;
r := r >> 1;
if t >= 0 then
z ... |
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... | #Draco | Draco | /* Integer square root using quadratic residue method */
proc nonrec isqrt(ulong x) ulong:
ulong q, z, r;
long t;
q := 1;
while q <= x do q := q << 2 od;
z := x;
r := 0;
while q > 1 do
q := q >> 2;
t := z - r - q;
r := r >> 1;
if t >= 0 then
z ... |
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... | #Emacs_Lisp | Emacs Lisp | (defun jo (n k)
(if (= 1 n)
1
(1+ (% (+ (1- k)
(jo (1- n) k))
n))))
(message "%d" (jo 50 2))
(message "%d" (jo 60 3)) |
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"... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public static class IntersectingNumberWheels
{
public static void Main() {
TurnWheels(('A', "123")).Take(20).Print();
TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print();
TurnWheels(('A', "1DD"), ('D', "678")).Take(20).P... |
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... | #Bracmat | Bracmat | D:\projects\Bracmat>bracmat
Bracmat version 5, build 105 (1 December 2011)
Copyright (C) 2002 Bart Jongejan
Bracmat comes with ABSOLUTELY NO WARRANTY; for details type `!w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `!c' for details.
{?} get$help { tutorial }
{?} ) ... |
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... | #Brat | Brat | $ brat
# Interactive Brat
brat:1> f = { a, b, s | a + s + s + b }
#=> function: 0xb737ac08
brat:2> f "Rosetta" "Code" ":"
#=> Rosetta::Code
brat:3> quit
Exiting |
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... | #Burlesque | Burlesque |
C:\Burlesque>Burlesque.exe --shell
blsq ) {+]?+}hd"Rosetta""Code"':!a
"Rosetta:Code"
blsq )
|
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)
... | #Fortran | Fortran |
program isbn13
implicit none
character(len=14), dimension(4), parameter :: isbns=["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
integer :: i
do i = 1, ubound(isbns, 1)
if (check_isbn13(isbns(i))) then
print*, isbns(... |
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... | #J | J | jaro=: dyad define
d=. ((x >.&# y)%2)-1
e=. (x =/y) * d >: |x -/&(i.@#) y
xm=. (+./"1 e)#x
ym=. (+./"2 e)#y
m=. xm <.&# ym
t=. (+/xm ~:&(m&{.) ym)%2
s1=. #x
s2=. #y
((m%s1)+(m%s2)+(m-t)%m)%3
) |
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... | #Go | Go | package main
import (
"fmt"
)
func main() {
var d, n, o, u, u89 int64
for n = 1; n < 100000000; n++ {
o = n
for {
u = 0
for {
d = o%10
o = (o - d) / 10
u += d*d
if o == 0 {
break
}
}
if u == 89 || u == 1 {
if u == 89 { u89++ }
break
}
o = u
}
}
fmt.Pr... |
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... | #F.23 | F# |
// Find Integer Floor sqrt of a Large Integer. Nigel Galloway: July 17th., 2020
let Isqrt n=let rec fN i g l=match(l>0I,i-g-l) with
(true,e) when e>=0I->fN e (g/2I+l) (l/4I)
|(true,_) ->fN i (g/2I) (l/4I)
|_ ... |
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... | #11l | 11l | DefaultDict[String, Set[String]] index
F parse_file(fname, fcontents)
L(word) fcontents.split(re:‘\W’)
:index[word.lowercase()].add(fname)
L(fname, fcontents) [(‘inv1.txt’, ‘It is what it is.’),
(‘inv2.txt’, ‘What is it?’),
(‘inv3.txt’, ‘It is a banana!’)]
parse... |
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... | #Ada | Ada | with Ada.Integer_Text_IO, Ada.Text_IO;
procedure Introspection is
use Ada.Integer_Text_IO, Ada.Text_IO;
begin
Put ("Integer range: ");
Put (Integer'First);
Put (" .. ");
Put (Integer'Last);
New_Line;
Put ("Float digits: ");
Put (Float'Digits);
New_Line;
end Introspection; |
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... | #Erlang | Erlang |
-module( josephus_problem ).
-export( [general_solution/3, task/0] ).
general_solution( Prisoners, Kill, Survive ) -> general_solution( Prisoners, Kill, Survive, erlang:length(Prisoners), [] ).
task() -> general_solution( lists:seq(0, 40), 3, 1 ).
general_solution( Prisoners, _Kill, Survive, Survive, Kill... |
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"... | #C.2B.2B | C++ | #include <initializer_list>
#include <iostream>
#include <map>
#include <vector>
struct Wheel {
private:
std::vector<char> values;
size_t index;
public:
Wheel() : index(0) {
// empty
}
Wheel(std::initializer_list<char> data) : values(data), index(0) {
//values.assign(data);
... |
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... | #C.23 | C# | **********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.14
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>csi /?
Microsof... |
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... | #Clojure | Clojure |
Clojure 1.1.0
user=> (defn f [s1 s2 sep] (str s1 sep sep s2))
#'user/f
user=> (f "Rosetta" "Code" ":")
"Rosetta::Code"
user=>
|
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)
... | #FreeBASIC | FreeBASIC | #define ZEROC asc("0")
function is_num( byval c as string ) as boolean
if asc(c) >= ZEROC andalso asc(c)<ZEROC+10 then return true
return false
end function
function is_good_isbn( isbn as string ) as boolean
dim as uinteger charno = 0, digitno = 0, sum = 0
dim as string*1 currchar
while charno <... |
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... | #Java | Java | public class JaroDistance {
public static double jaro(String s, String t) {
int s_len = s.length();
int t_len = t.length();
if (s_len == 0 && t_len == 0) return 1;
int match_distance = Integer.max(s_len, t_len) / 2 - 1;
boolean[] s_matches = new boolean[s_len];
... |
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... | #Haskell | Haskell | import Data.List (unfoldr)
import Data.Tuple (swap)
step :: Int -> Int
step = sum . map (^ 2) . unfoldr f where
f 0 = Nothing
f n = Just . swap $ n `divMod` 10
iter :: Int -> Int
iter = head . filter (`elem` [1, 89]) . iterate step
main = do
print $ length $ filter ((== 89) . iter) [1 .. 99999999] |
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... | #360_Assembly | 360 Assembly | L 2,=F'2147483647' 2**31-1
L 3,=F'1' 1
AR 2,3 add register3 to register2
BO OVERFLOW branch on overflow
....
OVERFLOW EQU * |
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... | #Factor | Factor | USING: formatting io kernel locals math math.functions
math.ranges prettyprint sequences tools.memory.private ;
:: isqrt ( x -- n )
1 :> q!
[ q x > ] [ q 4 * q! ] until
x 0 :> ( z! r! )
[ q 1 > ] [
q 4 /i q!
z r - q - :> t
r -1 shift r!
t 0 >= [
t z!
... |
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... | #Fish | Fish | 1[:>:r:@@:@,\;
]~$\!?={:,2+/n |
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... | #Ada | Ada | with Ada.Text_IO, Generic_Inverted_Index, Ada.Strings.Hash, Parse_Lines;
use Ada.Text_IO;
procedure Inverted_Index is
type Process_Word is access procedure (Word: String);
package Inv_Idx is new Generic_Inverted_Index
(Source_Type => String,
Item_Type => String,
Hash => Ada.Strings... |
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... | #Aikido | Aikido |
import math
if (version < 144) {
throw "Version of aikido is too old"
}
var bloop = -1.4
// Math package doesn't have 'abs'. We'll use 'fabs' instead.
if ("fabs" in Math) {
if ("bloop" in main) {
println ("fabs(bloop) is " + eval ("Math.fabs(bloop)"))
}
}
var x = 104
var y = 598
var z = "... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
print (("Integer range: ", -max int, " .. ", max int, new line));
print (("Integer digits: ", int width, new line));
print (("Float range: ", -max real, " .. ", max real, new line));
print (("Float digits: ", real width, new line))
END |
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... | #ERRE | ERRE |
PROGRAM JOSEPHUS
!
! for rosettacode.org
!
!$INTEGER
DIM DEAD[100]
PROCEDURE MAIN(N,K,S->ERRORS)
! n - number of prisoners
! k - kill every k'th prisoner
! s - number of survivors
LOCAL KILLED$,SURVIVED$,FOUND,P,NN,I
ERRORS=0
FOR I=0 TO 100 DO
DEAD[I]=0
END FOR ! prepare array
PR... |
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"... | #D | D | import std.exception;
import std.range;
import std.stdio;
struct Wheel {
private string[] values;
private uint index;
invariant {
enforce(index < values.length, "index out of range");
}
this(string[] value...) in {
enforce(value.length > 0, "Cannot create a wheel with no elemen... |
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... | #CoffeeScript | CoffeeScript |
$ coffee -n
coffee> f = (a, b, c) -> a + c + c + b
[Function]
coffee> 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... | #Common_Lisp | Common Lisp | $ rlwrap sbcl
This is SBCL 1.0.25, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
...
* (defun f (string-1 string-2 separator)
(concatenate 'string string-1 separator separator string-2))
F
* (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)
... | #F.23 | F# | // ISBN13 Check Digit
open System
let parseInput (input: string) =
Seq.map(fun c -> c |> string) input |> Seq.toList |> List.map(fun x -> Int32.Parse x)
[<EntryPoint>]
let main argv =
let isbnnum = parseInput (String.filter (fun x -> x <> '-') argv.[0])
// Multiply every other digit by 3
let everyOt... |
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... | #jq | jq | def jaro($s1; $s2):
($s1|length) as $le1
| ($s2|length) as $le2
| if $le1 == 0 and $le2 == 0 then 1
elif $le1 == 0 or $le2 == 0 then 0
else ((((if $le2 > $le1 then $le2 else $le1 end) / 2) | floor) - 1) as $dist
| {matches: 0, matches2: [], matches2: [], transpos: 0 }
| reduce range... |
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... | #J | J | digits=: 10&#.inv |
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... | #6502_Assembly | 6502 Assembly | LDA #$7F
CLC
ADC #$01
BVS ErrorHandler ;this branch will always be taken. |
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... | #68000_Assembly | 68000 Assembly | MOVE.W D0,#0000117F
ADD.W #1,D0 ;DOESN'T SET THE OVERFLOW FLAG, SINCE AT WORD LENGTH WE DIDN'T CROSS FROM 7FFF TO 8000
SUB.B #1,D0 ;WILL SET THE OVERFLOW FLAG SINCE AT BYTE LENGTH WE CROSSED FROM 80 TO 7F |
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... | #Forth | Forth |
: d., ( n -- ) \ write double precision int, commatized.
tuck dabs
<# begin 2dup 1.000 d> while # # # [char] , hold repeat #s rot sign #>
type space ;
: ., ( n -- ) \ write integer commatized.
s>d d., ;
: 4* s" 2 lshift" evaluate ; immediate
: 4/ s" 2 rshift" evaluate ; immediate
: isqrt-... |
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... | #Fortran | Fortran | MODULE INTEGER_SQUARE_ROOT
IMPLICIT NONE
CONTAINS
! Convert string representation number to string with comma digit separation
FUNCTION COMMATIZE(NUM) RESULT(OUT_STR)
INTEGER(16), INTENT(IN) :: NUM
INTEGER(16) I
CHARACTER(83) :: TEMP, OUT_STR
WRITE(TEMP, '(I0)'... |
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... | #AutoHotkey | AutoHotkey | ; http://www.autohotkey.com/forum/viewtopic.php?t=41479
inputbox, files, files, file pattern such as c:\files\*.txt
word2docs := object() ; autohotkey_L is needed.
stime := A_tickcount
Loop, %files%, 0,1
{
tooltip,%A_index% / 500
wordList := WordsIn(A_LoopFileFullPath)
InvertedIndex(wordList, A_loopFile... |
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... | #Arturo | Arturo | if not? sys\version > 0.9.0 -> panic "version too old!"
bloop: 3 - 5
if? set? 'bloop -> "variable 'bloop' is set"
else -> "variable 'bloop' is not set"
if set? 'abs -> print ["the absolute value of bloop is:" abs bloop]
print [
"The sum of all globally defined integers is:"
sum map select key... |
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... | #AutoHotkey | AutoHotkey | if (A_AhkVersion < "1.0.48.03")
{
MsgBox % "you are using" . A_AhkVersion . "`nplease upgrade to" . "1.0.48.03"
ExitApp
}
bloop = -3
if bloop
if IsFunc("abs")
MsgBox % abs(bloop)
return |
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... | #Factor | Factor | USING: kernel locals math math.ranges sequences ;
IN: josephus
:: josephus ( k n -- m )
n [1,b] 0 [ [ k + ] dip mod ] reduce ; |
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"... | #F.23 | F# |
// Wheels within wheels. Nigel Galloway: September 30th., 2019.
let N(n)=fun()->n
let wheel(n:(unit->int)[])=let mutable g= -1 in (fun()->g<-(g+1)%n.Length; n.[g]())
let A1=wheel[|N(1);N(2);N(3)|]
for n in 0..20 do printf "%d " (A1())
printfn ""
let B2=wheel[|N(3);N(4)|]
let A2=wheel[|N(1);B2;N(2)|]
for n in 0..20 d... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | $ vu
<1:1> f str1 str2 sep:
<1:2> join sep [ str2 "" str1 ]
<1:3>
<2:1> . 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... | #E | E | $ rune # from an OS shell. On Windows there is also a desktop shortcut. |
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... | #EchoLisp | EchoLisp |
;; screen copy of the REPL
;; note that the &i variables remember expression evaluation, and may be used in other expressions
EchoLisp - 2.16.2
📗 local-db: db.version: 3
(define ( f s1 s2 s3) (string-append s1 s3 s3 s2))
[0]→ f
(f "Rosetta" "Code" ":")
[1]→ "Rosetta::Code"
(+ 4 8)
[2]→ 12
(* 4 8)
[3]→ 32
(* &2 &3)... |
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)
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
// remove any hyphens or spaces
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
// check length == 13
le := utf8.RuneCountInString(isbn)
if le != 13 {
return fals... |
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... | #Julia | Julia | function jarodistance(s1, s2)
m = t = p = 0
matchstd = max(length(s1), length(s2)) / 2 - 1
for (i1, c1) in enumerate(s1)
for (i2, c2) in enumerate(s2)
(c1 == c2) && (abs(i2 - i1) ≤ matchstd) && (m += 1)
(c1 == c2) && (i2 == i1) && (p += 1)
end
end
t = (m - p) ... |
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... | #Java | Java | import java.util.stream.IntStream;
public class IteratedDigitsSquaring {
public static void main(String[] args) {
long r = IntStream.range(1, 100_000_000)
.parallel()
.filter(n -> calc(n) == 89)
.count();
System.out.println(r);
}
private ... |
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... | #0815 | 0815 | }:_:<:1:+%<:a:~$^:_: |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Overflow is
generic
type T is Range <>;
Name_Of_T: String;
procedure Print_Bounds; -- first instantiate this with T, Name
-- then call the instantiation
procedure Print_Bounds is
begin
Put_Line(" " & Name_Of_T &... |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #FreeBASIC | FreeBASIC |
function isqrt( byval x as ulongint ) as ulongint
dim as ulongint q = 1, r
dim as longint t
while q <= x
q = q shl 2
wend
while q > 1
q = q shr 2
t = x - r - q
r = r shr 1
if t >= 0 then
x = t
r += q
end if
we... |
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... | #BBC_BASIC | BBC BASIC | DIM FileList$(4)
FileList$() = "BBCKEY0.TXT", "BBCKEY1.TXT", "BBCKEY2.TXT", \
\ "BBCKEY3.TXT", "BBCKEY4.TXT"
DictSize% = 30000
DIM Index{(DictSize%-1) word$, link%}
REM Build inverted index:
FOR file% = DIM(FileList$(),1) TO 0 STEP -1
filename$ = FileLis... |
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... | #AWK | AWK |
# syntax: GAWK -f INTROSPECTION.AWK
BEGIN {
if (PROCINFO["version"] < "4.1.0") {
print("version is too old")
exit(1)
}
bloop = -1
if (PROCINFO["identifiers"]["abs"] == "user" && bloop != "") {
printf("bloop = %s\n",bloop)
printf("abs(bloop) = %s\n",abs(bloop))
}
exit(0)... |
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... | #BBC_BASIC | BBC BASIC | IF VAL(FNversion) < 5.94 THEN PRINT "Version is too old" : END
ON ERROR LOCAL PRINT "Variable 'bloop' doesn't exist" : END
test = bloop
RESTORE ERROR
ON ERROR LOCAL PRINT "Function 'FNabs()' is not defined" : END
test = ^FNabs()
RESTORE ERROR
PRINT FNabs(bloop)
... |
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... | #Forth | Forth | : josephus 0 1 begin dup 41 <= while swap 3 + over mod swap 1+ repeat drop ; |
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"... | #Factor | Factor | "A: 1 B C\nB: 3 4\nC: 5 B"
|
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"... | #Go | Go | package main
import (
"fmt"
"sort"
"strconv"
)
type wheel struct {
next int
values []string
}
type wheelMap = map[string]wheel
func generate(wheels wheelMap, start string, maxCount int) {
count := 0
w := wheels[start]
for {
s := w.values[w.next]
v, err := strcon... |
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... | #Elena | Elena |
c:\Alex\ELENA\bin>elt
ELENA command line VM terminal 5.1.13 (C)2011-2020 by Alexei Rakov
ELENA VM 5.1.17 (C)2005-2020 by Alex Rakov
Initializing...
Done...
>f(s1,s2,sep){^ s1 + sep + sep + s2 };
>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... | #Elixir | Elixir | iex(1)> f = fn str1,str2,sep -> [str1,"",str2] |> Enum.join(sep) end # Join list on separator
iex(2)> g = fn str1,str2,sep -> str1 <> sep <> sep <> str2 end # Or concatenate strings
iex(3)> defmodule JoinStrings do
...(3)> def f(str1,str2,sep), do: [str1,"",str2] |> Enum.join(sep)
...(3)> def g(str1,str2,se... |
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... | #Emacs_Lisp | Emacs Lisp | (defun my-join (str1 str2 sep)
(concat str1 sep sep str2))
my-join
(my-join "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)
... | #Go | Go | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func checkIsbn13(isbn string) bool {
// remove any hyphens or spaces
isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "")
// check length == 13
le := utf8.RuneCountInString(isbn)
if le != 13 {
return fals... |
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... | #Kotlin | Kotlin | object Jaro {
fun 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 = BooleanArray(s1_len)
val s2_matches = BooleanAr... |
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... | #jq | jq | def factorial: reduce range(2;.+1) as $i (1; . * $i);
# Pick n items (with replacement) from the input array,
# but only consider distinct combinations:
def pick(n):
def pick(n; m): # pick n, from m onwards
if n == 0 then []
elif m == length then empty
elif n == 1 then (.[m:][] | [.])
else ([.[m]] ... |
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... | #Julia | Julia | function iterate(m::Integer)
while m != 1 && m != 89
s = 0
while m > 0 # compute sum of squares of digits
m, d = divrem(m, 10)
s += d ^ 2
end
m = s
end
return m
end
itercount(k::Integer) = count(x -> iterate(x) == 89, 1:k) |
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... | #11l | 11l | L(i) 1..
print(i) |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #360_Assembly | 360 Assembly | * Integer sequence 06/05/2016
INTSEQED CSECT
USING INTSEQED,12
LR 12,15
LA 6,1 i=1
LOOP CVD 6,DW binary to pack decimal
MVC WTOMSG+4(12),EM12 load mask
ED WTOMSG+4(12),DW+2 packed dec to char
WTO MF=(E,WTOMSG) ... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
print (max int);
print (1+max int)
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... | #Applesoft_BASIC | Applesoft BASIC | A% = -(-32767-1) |
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... | #Go | Go | package main
import (
"fmt"
"log"
"math/big"
)
var zero = big.NewInt(0)
var one = big.NewInt(1)
func isqrt(x *big.Int) *big.Int {
if x.Cmp(zero) < 0 {
log.Fatal("Argument cannot be negative.")
}
q := big.NewInt(1)
for q.Cmp(x) <= 0 {
q.Lsh(q, 2)
}
z := new(big.I... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #C | C | #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)]; /* next letter; slot 0 is for file name */
int eow;
};
... |
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... | #C | C | #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
#pragma error("C compiler must adhere to at least C99 for the following code.")
#else
/* rest of file */
#endif |
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... | #C.23 | C# | using System;
using System.Reflection;
namespace Rosetta_Introspection
{
static public class Program
{
static public int bloop = -10;
static public int bloop2 = -20;
public static void Main()
{
var asm = Assembly.GetExecutingAssembly();
var version = int.Parse(asm.ImageRuntimeVersion.Split('.')[0].S... |
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... | #Fortran | Fortran | program josephus
implicit none
integer :: n, i, k, p
integer, allocatable :: next(:)
read *, n, k
allocate(next(0:n - 1))
do i = 0, n - 2
next(i) = i + 1
end do
next(n - 1) = 0
p = 0
do while(next(p) /= p)
do i = 1, k - 2
p = next(p)
end do
print *, "Kill",... |
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"... | #Haskell | Haskell | import Data.Char (isDigit)
import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
---------------- INTERSECTING NUMBER WHEELS --------------
clockWorkTick ::
M.Map Char String ->
(M.Map Char String, Char)
clockWorkTick = flip click 'A'
where
click wheels name
... |
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... | #Erlang | Erlang | $erl
1> F = fun(X,Y,Z) -> string:concat(string:concat(X,Z),string:concat(Z,Y)) end.
#Fun<erl_eval.18.105910772>
2> 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... | #ERRE | ERRE | r$="Rosetta"
Ok <--- from interpreter
c$="Code"
Ok <--- from interpreter
s$="-"
Ok <--- from interpreter
PRINT r$+s$+c$
Rosetta-Code
Ok <--- from interpreter
|
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)
... | #Haskell | Haskell | import Data.Char (digitToInt, isDigit)
import Text.Printf (printf)
pair :: Num a => [a] -> [(a, a)]
pair [] = []
pair xs = p (take 2 xs) : pair (drop 2 xs)
where
p ps = case ps of
(x : y : zs) -> (x, y)
(x : zs) -> (x, 0)
validIsbn13 :: String -> Bool
validIsbn13 isbn
| length (digits isbn) /= 1... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[JaroDistance]
JaroDistance[s_String, t_String] := Module[{slen, tlen, maxdistance, smatches, tmatches, matches, transpositions, start, end, k, schar, tchar},
slen = StringLength[s];
tlen = StringLength[t];
schar = Characters[s];
tchar = Characters[t];
If[slen == tlen == 0,
1
,
maxdistance = ... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun endsWith89(n: Int): Boolean {
var digit: Int
var sum = 0
var nn = n
while (true) {
while (nn > 0) {
digit = nn % 10
sum += digit * digit
nn /= 10
}
if (sum == 89) return true
if (sum == 1) return false
nn ... |
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... | #8080_Assembly | 8080 Assembly | ORG 0100H
MVI A, 0 ; move immediate
LOOP: INR A ; increment
; call 'PRINT' subroutine, if required
JMP LOOP ; jump unconditionally
END |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Action.21 | Action! | PROC Main()
CARD i
i=0
DO
PrintF("%U ",i)
i==+1
UNTIL i=0
OD
RETURN |
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... | #Arturo | Arturo | big32bit: 2147483646
big64bit: 9223372036854775808
print type big32bit
print type big64bit
print big32bit + 1
print big64bit + 1
print big32bit * 2
print big64bit * 2 |
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... | #AutoHotkey | AutoHotkey | Msgbox, % "Testing signed 64-bit integer overflow with AutoHotkey:`n" -(-9223372036854775807-1) "`n" 5000000000000000000+5000000000000000000 "`n" -9223372036854775807-9223372036854775807 "`n" 3037000500*3037000500 "`n" (-9223372036854775807-1)//-1 |
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... | #Haskell | Haskell | import Data.Bits
isqrt :: Integer -> Integer
isqrt n = go n 0 (q `shiftR` 2)
where
q = head $ dropWhile (< n) $ iterate (`shiftL` 2) 1
go z r 0 = r
go z r q = let t = z - r - q
in if t >= 0
then go t (r `shiftR` 1 + q) (q `shiftR` 2)
else go z (r `shiftR` 1) (... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class InvertedIndex
{
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
return dictionary
.SelectMany(keyValuePair => keyValuePair.Value.Sele... |
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... | #C.2B.2B | C++ | #if !defined(__cplusplus) || __cplusplus < 201103L
#pragma error("The following code requires at least C++11.")
#else
// ...
#endif |
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... | #Clojure | Clojure |
; check Java version
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (System/getProperty "java.version")))]
(if (>= version 1.5)
(println "Version ok")
(throw (Error. "Bad version"))))
; check Clojure version
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (clojure-version)))]
(if (>= ver... |
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... | #FreeBASIC | FreeBASIC |
Function Josephus (n As Integer, k As Integer, m As Integer) As Integer
Dim As Integer lm = m
For i As Integer = m + 1 To n
lm = (lm + k) Mod i
Next i
Josephus = lm
End Function
Dim As Integer n = 41 'prisioneros
Dim As Integer k = 3 'orden de ejecución
Print "n ="; n, "k ="; k, "supervi... |
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"... | #J | J |
wheelgroup=:{{
yield_wheelgroup_=: {{
i=. wheels i.<;y
j=. i{inds
k=. ".;y
l=. j{k
inds=: ((#k)|1+j) i} inds
if. l e. wheels
do.yield l
else.{.".;l
end.
}}
gen_wheelgroup_=: {{
yield wheel
}}
grp=. cocreate ''
coinsert__grp 'wheelgroup'
specs__grp=: cut each boxop... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.