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/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... | #Kotlin | Kotlin | interface Camera {
val numberOfLenses : Int
}
interface MobilePhone {
fun charge(n : Int) {
if (n >= 0)
battery_level = (battery_level + n).coerceAtMost(100)
}
var battery_level : Int
}
data class CameraPhone(override val numberOfLenses : Int = 1, override var battery_level: I... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
# print uint32 right-aligned in column, with
# thousands separators
sub print_col(num: uint32, width: uint8) is
# maximum integer is 4,294,967,296 for length 13,
# plus one extra for the zero terminator
var buf: uint8[14];
var start := &buf[0];
var last := UIToA(num, 10, &buf... |
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... | #Fortran | Fortran | program nivengaps
implicit none
integer*8 prev /1/, gap /0/, sum /0/
integer*8 nividx /0/, niven /1/
integer gapidx /1/
character*13 idxfmt
character*14 nivfmt
write (*,*) 'Gap no Gap Niven index Niven number '
write (*,*) '------ --- ------... |
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... | #J | J | -(_2147483647-1)
2.14748e9
2000000000 + 2000000000
4e9
_2147483647 - 2147483647
_4.29497e9
46341 * 46341
2.14749e9
(_2147483647-1) % -1
2.14748e9
-(_9223372036854775807-1)
9.22337e18
5000000000000000000+5000000000000000000
1e19
_9223372036854775807 - 9223372036854775807
_1.84467e19
303700050... |
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... | #Java | Java | public class integerOverflow {
public static void main(String[] args) {
System.out.println("Signed 32-bit:");
System.out.println(-(-2147483647-1));
System.out.println(2000000000 + 2000000000);
System.out.println(-2147483647 - 2147483647);
System.out.println(46341 * 46341);
... |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Common_Lisp | Common Lisp | (defun basic-input (filename)
(with-open-file (stream (make-pathname :name filename) :direction :input)
(loop for line = (read-line stream nil nil)
while line
do (format t "~a~%" line)))) |
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.
| #D | D | void main() {
import std.stdio;
immutable fileName = "input_loop1.d";
foreach (const line; fileName.File.byLine) {
pragma(msg, typeof(line)); // Prints: const(char[])
// line is a transient slice, so if you need to
// retain it for later use, you have to .dup or .idup it.
... |
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... | #Perl | Perl | # 20201029 added Perl programming solution
use strict;
use warnings;
use bigint;
use CLDR::Number 'decimal_formatter';
sub integer_sqrt {
( my $x = $_[0] ) >= 0 or die;
my $q = 1;
while ($q <= $x) {
$q <<= 2
}
my ($z, $r) = ($x, 0);
while ($q > 1) {
$q >>= 2;
my $t = $z - $r - ... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
texts := table() # substitute for read and parse files
texts["T0.txt"] := ["it", "is", "what", "it", "is"]
texts["T1.txt"] := ["what", "is", "it"]
texts["T2.txt"] := ["it", "is", "a", "banana"]
every textname := key(texts) do # build index for each 'text'
SII := InvertedIndex(SI... |
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... | #Kotlin | Kotlin | // version 1.0.6 (intro.kt)
import java.lang.reflect.Method
val bloop = -3
val i = 4
val j = 5
val k = 6
fun main(args: Array<String>) {
// get version of JVM
val version = System.getProperty("java.version")
if (version >= "1.6") println("The current JVM version is $version")
else println("Must us... |
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... | #Kotlin | Kotlin | // version 1.1.3
fun josephus(n: Int, k: Int, m: Int): Pair<List<Int>, List<Int>> {
require(k > 0 && m > 0 && n > k && n > m)
val killed = mutableListOf<Int>()
val survived = MutableList(n) { it }
var start = k - 1
outer@ while (true) {
val end = survived.size - 1
var i = start
... |
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"... | #zkl | zkl | fcn intersectingNumberWheelsW(wheels){ // ("A":(a,b,"C"), "C":(d,e) ...)
ws:=wheels.pump(Dictionary(),fcn([(k,v)]){ return(k,Walker.cycle(v)) }); // new Dictionary
Walker.zero().tweak(fcn(w,wheels){
while(1){
w=wheels[w].next(); // increment wheel w
if(Int.isType(w)) return(w);
}
}.fp("A... |
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... | #ML.2FI | ML/I | MCSKIP MT,<>
MCINS %.
MCDEF F WITHS (,,)
AS <%WA1.%WA3.%WA2.%WA2.> |
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... | #Nanoquery | Nanoquery | >nq
[no file | rec1 col1] % def f(a, b, sep)
... return a + sep + sep + b
... end
[no file | rec1 col1] % println 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... | #Nim | Nim | proc f(x, y, z: string) = echo x, z, z, y
f("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)
... | #Python | Python | def is_isbn13(n):
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
return False
product = (sum(int(ch) for ch in n[::2])
+ sum(int(ch) * 3 for ch in n[1::2]))
return product % 10 == 0
if __name__ == '__main__':
tests = '''
978-1734314502
978-1734314509
978-1788399081... |
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... | #Stata | Stata | ssc install jarowinkler |
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... | #Swift | Swift | func jaroWinklerMatch(_ s: String, _ t: String) -> Double {
let s_len: Int = s.count
let t_len: Int = t.count
if s_len == 0 && t_len == 0 {
return 1.0
}
if s_len == 0 || t_len == 0 {
return 0.0
}
var match_distance: Int = 0
if s_len == 1 && t_len == 1 {
m... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #11l | 11l | V next = String(Int(‘123’) + 1) |
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 |... | #Aime | Aime | void
output(integer a, integer b, text condition)
{
o_integer(a);
o_text(condition);
o_integer(b);
o_byte('\n');
}
integer
main(void)
{
if (a < b) {
output(a, b, " is less then ");
}
if (a == b) {
output(a, b, " is equal to ");
}
if (a > b) {
output(a, b, " is greater than... |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #360_Assembly | 360 Assembly | COPY member |
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... | #Delphi | Delphi | type
Animal = class(TObject)
private
// private functions/variables
public
// public functions/variables
end;
Dog = class(Animal);
Cat = class(Animal);
Collie = class(Dog);
Lab = class(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... | #DWScript | DWScript | type
Animal = class(TObject)
private
// private functions/variables
public
// public functions/variables
end;
type Dog = class(Animal) end;
type Cat = class(Animal) end;
type Collie = class(Dog) end;
type Lab = class(Dog) end; |
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... | #REXX | REXX | /*REXX program performs the squaring of iterated digits (until the sum equals 1 or 89).*/
parse arg n . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n=10 * 1000000 /*Not specified? Then use the default.*/
!.=0; do m=1 for 9; !.m=m**2; end /*m*/ ... |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #Arturo | Arturo | rank: function [arr][
if empty? arr -> return 0
from.binary "1" ++ join.with:"0" map arr 'a -> repeat "1" a
]
unrank: function [rnk][
if rnk=1 -> return [0]
bn: as.binary rnk
map split.by:"0" slice bn 1 dec size bn => size
]
l: [1, 2, 3, 5, 8]
print ["The initial list:" l]
r: rank l
print [... |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #D | D | import std.stdio, std.algorithm, std.array, std.conv, std.bigint;
BigInt rank(T)(in T[] x) pure /*nothrow*/ @safe {
return BigInt("0x" ~ x.map!text.join('F'));
}
BigInt[] unrank(BigInt n) pure /*nothrow @safe*/ {
string s;
while (n) {
s = "0123456789ABCDEF"[n % 16] ~ s;
n /= 16;
}
... |
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... | #Clean | Clean | module IntegerSequence
import StdEnv
Start = [x \\ x <- [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... | #Clojure | Clojure | (map println (next (range))) |
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... | #C | C | #include <math.h> /* HUGE_VAL */
#include <stdio.h> /* printf() */
double inf(void) {
return HUGE_VAL;
}
int main() {
printf("%g\n", inf());
return 0;
} |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #C.23 | C# | using System;
class Program
{
static double PositiveInfinity()
{
return double.PositiveInfinity;
}
static void Main()
{
Console.WriteLine(PositiveInfinity());
}
} |
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... | #C.2B.2B | C++ | #include <limits>
double inf()
{
if (std::numeric_limits<double>::has_infinity)
return std::numeric_limits<double>::infinity();
else
return std::numeric_limits<double>::max();
} |
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... | #Lasso | Lasso | define trait_camera => trait {
require zoomfactor
provide has_zoom() => {
return .zoomfactor > 0
}
}
define trait_mobilephone => trait {
require brand
provide is_smart() => {
return .brand == 'Apple'
}
}
define cameraphone => type {
trait {
import trait_camera, trait_mobilephone
}
data pu... |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Latitude | Latitude | Camera ::= Mixin clone.
MobilePhone ::= Mixin clone.
CameraPhone ::= Object clone.
Camera inject: CameraPhone.
MobilePhone inject: 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... | #Lingo | Lingo | -- parent script "Camera"
property resolution
on new (me)
me.resolution = "1024x768"
return me
end
on snap (me)
put "SNAP!"
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... | #Logtalk | Logtalk | :- object(camera,
...).
...
:- end_object. |
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... | #FreeBASIC | FreeBASIC |
Function digit_sum(n As Uinteger, sum As Ulong) As Ulong
' devuelve la suma de los dígitos de n dada la suma de los dígitos de n - 1
sum += 1
While (n > 0 And n Mod 10 = 0)
sum -= 9
n = Int(n / 10)
Wend
Return sum
End Function
Function divisible(n As Uinteger, d As Uinteger) As B... |
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... | #Go | Go | package main
import "fmt"
type is func() uint64
func newSum() is {
var ms is
ms = func() uint64 {
ms = newSum()
return ms()
}
var msd, d uint64
return func() uint64 {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
... |
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... | #jq | jq |
def compare:
if type == "string" then "\n\(.)\n"
else map(tostring)
| .[1] as $s
| .[0]
| if $s == . then . + ": agrees"
else $s + ": expression evaluates to " + .
end
end;
[ -(-2147483647-1),"2147483648"],
[2000000000 + 2000000000, "4000000000"],
[-2147483647 - 2147483647, "-4294967294"],
[463... |
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... | #Julia | Julia | using Printf
S = subtypes(Signed)
U = subtypes(Unsigned)
println("Integer limits:")
for (s, u) in zip(S, U)
@printf("%8s: [%s, %s]\n", s, typemin(s), typemax(s))
@printf("%8s: [%s, %s]\n", u, typemin(u), typemax(u))
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.
| #Delphi | Delphi | program InputLoop;
{$APPTYPE CONSOLE}
uses SysUtils, Classes;
var
lReader: TStreamReader; // Introduced in Delphi XE
begin
lReader := TStreamReader.Create('input.txt', TEncoding.Default);
try
while lReader.Peek >= 0 do
Writeln(lReader.ReadLine);
finally
lReader.Free;
end;
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | while /= :eof dup !read-line!stdin:
!print( "Read a line: " !decode!utf-8 swap )
drop
!print "End of file." |
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... | #Phix | Phix | with javascript_semantics
include mpfr.e
function isqrt(mpz x)
if mpz_cmp_si(x,0)<0 then
crash("Argument cannot be negative.")
end if
mpz q = mpz_init(1),
r = mpz_init(0),
t = mpz_init(),
z = mpz_init_set(x)
while mpz_cmp(q,x)<= 0 do
mpz_mul_si(q,q,4)
end wh... |
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... | #J | J | require'files regex strings'
rxutf8 0 NB. support latin1 searches for this example, instead of utf8
files=:words=:buckets=:''
wordre=: rxcomp '[\w'']+'
parse=: ,@:rxfrom~ wordre&rxmatches
invert=: verb define
files=: files,todo=. ~.y-.files
>invert1 each todo
)
invert1=: verb define
file=. files i.<y
wor... |
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... | #Lasso | Lasso | var(bloob = -26)
decimal(lasso_version(-lassoversion)) < 9.2 ? abort
var_defined('bloob') and $bloob -> isa(::integer) and lasso_tagexists('math_abs') ? math_abs($bloob) |
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... | #Lingo | Lingo | put _player.productVersion
-- "11.5.9"
_player.itemDelimiter="."
if integer(_player.productVersion.item[1])<11 then _player.quit() |
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... | #Lua | Lua | function josephus(n, k, m)
local positions={}
for i=1,n do
table.insert(positions, i-1)
end
local i,j=1,1
local s='Execution order: '
while #positions>m do
if j==k then
s=s .. positions[i] .. ', '
table.remove(positions, i)
i=i-1
end
... |
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... | #OCaml | OCaml | $ ocaml
Objective Caml version 3.12.1
# let f s1 s2 sep = String.concat sep [s1; ""; s2];;
val f : string -> string -> string -> string = <fun>
# f "Rosetta" "Code" ":";;
- : string = "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)
... | #Quackery | Quackery | [ char 0 char 9 1+ within ] is digit? ( c --> b )
[ 1 & ] is odd? ( n --> b )
[ [] swap ]'[ swap
witheach [
dup nested
unrot over do
iff [ dip join ]
else nip
] drop ] is filter ( [ --> [ )
[ 0 swap
witheach [
char->n i^ odd?
iff [... |
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... | #Tcl | Tcl | proc jaro {s1 s2} {
set l1 [string length $s1]
set l2 [string length $s2]
set dmax [expr {max($l1, $l2)/2 - 1}] ;# window size to scan for matches
set m1 {} ;# match indices
set m2 {}
for {set i 0} {$i < $l1} {incr i} {
set jmin [expr {$i - $dmax}] ... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Increment the number in the $-terminated string under HL.
;;; The new string is written back to the original location.
;;; It may grow by one byte (e.g. 999 -> 1000).
incstr: mvi a,'$' ; End marker
lxi d,303Ah ; D='0', E='9'+1
lxi b,0 ; Find the end of the string and find the length
isrch: ... |
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 |... | #ALGOL_68 | ALGOL 68 | main: (
INT a, b;
read((a, space, b, new line));
IF a <= b OR a LE b # OR a ≤ b # THEN
print((a," is less or equal to ", b, new line))
FI;
IF a < b OR a LT b THEN
print((a," is less than ", b, new line))
ELIF a = b OR a EQ b THEN
print((a," is equal to ", b, new line))
ELIF a > b OR a GT b T... |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #6502_Assembly | 6502 Assembly | ;main.asm
org $8000
include "foo.txt"
;eof |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #68000_Assembly | 68000 Assembly |
'file constant include : includeConstantesARM64.inc'
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDIN, 0 // Linux input console
.equ STDOUT, 1 // linux output console
.equ OPEN, 56 ... |
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... | #E | E | def makeType(label, superstamps) {
def stamp {
to audit(audition) {
for s in superstamps { audition.ask(s) }
return true
}
}
def guard {
to coerce(specimen, ejector) {
if (__auditedBy(stamp, specimen)) {
return specimen
... |
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... | #Eiffel | Eiffel | class
ANIMAL
end |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #AWK | AWK | # usage: gawk -f Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols.awk
function is_valid_identifier(id, rc) {
fn = "is_valid_identifier.awk"
printf("function unused(%s) { arr[%s] = 1 }\n", id, id, id) >fn
printf("BEGIN { exit(0) }\n") >>fn
close(fn)
rc = system("gawk -f is_va... |
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... | #Ring | Ring |
nr = 1000
num = 0
for n = 1 to nr
sum = 0
for m = 1 to len(string(n))
sum += pow(number(substr(string(n),m,1)),2)
if sum = 89 num += 1 see "" + n + " " + sum + nl ok
next
next
see "Total under 1000 is : " + num + nl
|
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... | #Ruby | Ruby | # Count how many number chains for Natural Numbers < 10**d end with a value of 1.
def iterated_square_digit(d)
f = Array.new(d+1){|n| (1..n).inject(1, :*)} #Some small factorials
g = -> (n) { res = n.digits.sum{|d| d*d}
res==89 ? 0 : res }
#An array: table[n]==0 means that n translates to 8... |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #FreeBASIC | FreeBASIC | type duple
A as ulongint
B as ulongint
end type
function two_to_one( A as ulongint, B as ulongint ) as ulongint 'converts two numbers into one
dim as uinteger ret = A*A + B*B + 2*A*B - 3*A - B 'according to the table
return 1 + ret/2 ' 1 2... |
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... | #CLU | CLU | % This iterator will generate all integers until the built-in type
% overflows. It is a signed machine-sized integer; so 64 bits on
% a modern machine. After that it will raise an exception.
to_infinity_and_beyond = iter () yields (int)
i: int := 0
while true do
i := i + 1
yield(i)
end
end... |
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... | #Clojure | Clojure | ##Inf ;; same as Double/POSITIVE_INFINITY
##-Inf ;; same as Double/NEGATIVE_INFINITY
(Double/isInfinite ##Inf) ;; true |
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... | #CoffeeScript | CoffeeScript | 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... | #Lua | Lua | function setmetatables(t,mts) --takes a table and a list of metatables
return setmetatable(t,{__index = function(self, k)
--collisions are resolved in this implementation by simply taking the first one that comes along.
for i, mt in ipairs(mts) do
local member = mt[k]
if member then return member ... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Class Camera {
Private:
cameratype$
Class:
module Camera (.cameratype$){
}
}
\\ INHERITANCE AT CODE LEVEL
Class MobilePhone {
Private:
model$
Class:
module MobilePhone (.model$) {... |
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... | #Haskell | Haskell | {-# LANGUAGE NumericUnderscores #-}
import Control.Monad (guard)
import Text.Printf (printf)
import Data.List (intercalate, unfoldr)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)
nivens :: [Int]
nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n]
where
digitSum = sum . unfoldr (\x -> guard... |
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... | #Kotlin | Kotlin | // version 1.0.5-2
/* Kotlin (like Java) does not have unsigned integer types but we can simulate
what would happen if we did have an unsigned 32 bit integer type using this extension function */
fun Long.toUInt(): Long = this and 0xffffffffL
@Suppress("INTEGER_OVERFLOW")
fun main(args: Array<String>) {
//... |
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.
| #EasyLang | EasyLang | repeat
l$ = input
until error = 1
print l$
. |
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.
| #Eiffel | Eiffel |
note
description : "{
There are several examples included, including input from a text file,
simple console input and input from standard input explicitly.
See notes in the code for details.
Examples were compile using Eiffel Studio 6.6 with only the default
class libraries.
}"
class APPLICATION
create
make
... |
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... | #Prolog | Prolog | %%% -*- Prolog -*-
%%%
%%% The Rosetta Code integer square root task, for SWI Prolog.
%%%
%% pow4gtx/2 -- Find a power of 4 greater than X.
pow4gtx(X, Q) :- pow4gtx(X, 1, Q), !.
pow4gtx(X, A, Q) :- X < A, Q is A.
pow4gtx(X, A, Q) :- A1 is A * 4,
pow4gtx(X, A1, Q).
%% isqrt/2 -- Find integer squa... |
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... | #Java | Java |
package org.rosettacode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
impor... |
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... | #Locomotive_Basic | Locomotive Basic | org &4000 ; program start address
push bc
push de
push hl
push af
ld bc,&df00 ; select BASIC ROM
out (c),c ; (ROM 0)
ld bc,&7f86 ; make ROM accessible at &c000
out (c),c ; (RAM block 3)
ld hl,&c001 ; copy ROM version number to RAM
ld de,&4040
ld bc,3
ldir
ld bc,&7f8e ; turn off ROM
out (c),... |
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... | #Logo | Logo | show logoversion ; 5.6
if logoversion < 6.0 [print [too old!]]
if and [name? "a] [number? :a] [
print ifelse procedure? "abs [abs :a] [ifelse :a < 0 [minus :a] [:a]]
] |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | survivor[n_, k_] := Nest[Most[RotateLeft[#, k]] &, Range[0, n - 1], n - 1]
survivor[41, 3] |
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... | #Octave | Octave | $ octave
GNU Octave, version 3.0.2
Copyright (C) 2008 John W. Eaton and others.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTIBILITY or
FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'.
Octave was configured for "i586-mandriva-... |
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)
... | #Racket | Racket | #lang racket/base
(define (isbn13-check-digit-valid? s)
(zero? (modulo (for/sum ((i (in-naturals))
(d (regexp-replace* #px"[^[:digit:]]" s "")))
(* (- (char->integer d) (char->integer #\0))
(if (even? i) 1 3)))
10)))
(module+ tes... |
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... | #Turbo-Basic_XL | Turbo-Basic XL |
10 DIM Word_1$(20), Word_2$(20), Z$(20)
11 CLS
20 Word_1$="MARTHA" : Word_2$="MARHTA" : ? Word_1$;" - ";Word_2$ : EXEC _JWD_ : ?
30 Word_1$="DIXON" : Word_2$="DICKSONX" : ? Word_1$;" - ";Word_2$ : EXEC _JWD_ : ?
40 Word_1$="JELLYFISH" : Word_2$="SMELLYFISH" : ? Word_1$;" - ";Word_2$ : EXEC _JWD_ : ?
11000 END
12000... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
section .text
org 100h
jmp demo ; Jump towards demo code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Increment the number in the $-terminated string
;;; in [ES:DI]. The string is written back to its original
;;; location. It may grow by one byte.
incnum: mov al,'$' ; F... |
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 |... | #ALGOL_W | ALGOL W | begin
integer a, b;
write( "first number: " );
read( a );
write( "second number: " );
read( b );
if a < b then write( a, " is less than ", b );
if a = b then write( a, " is equal to ", b );
if a > b then write( a, " is greater than ", b );
end. |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #AArch64_Assembly | AArch64 Assembly |
'file constant include : includeConstantesARM64.inc'
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDIN, 0 // Linux input console
.equ STDOUT, 1 // linux output console
.equ OPEN, 56 ... |
http://rosettacode.org/wiki/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #ACL2 | ACL2 | (include-book "filename") |
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... | #Elena | Elena | 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... | #F.23 | F# | type Animal() =
class // explicit syntax needed for empty class
end
type Dog() =
inherit Animal()
type Lab() =
inherit Dog()
type Collie() =
inherit Dog()
type Cat() =
inherit Animal() |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Factor | Factor | TUPLE: animal ;
TUPLE: dog < animal ;
TUPLE: cat < animal ;
TUPLE: lab < dog ;
TUPLE: collie < dog ; |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #F.23 | F# |
let ``+`` = 5
printfn "%d" ``+``
|
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Factor | Factor | USING: parser see ;
\ scan-word-name see |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols | Idiomatically determine all the characters that can be used for symbols | Idiomatically determine all the characters that can be used for symbols.
The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ... | #Go | Go | package main
import (
"fmt"
"go/ast"
"go/parser"
"strings"
"unicode"
)
func isValidIdentifier(identifier string) bool {
node, err := parser.ParseExpr(identifier)
if err != nil {
return false
}
ident, ok := node.(*ast.Ident)
return ok && ident.Name == identifier
}
type runeRanges struct {
ranges []s... |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Rust | Rust | fn digit_square_sum(mut num: usize) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
fn last_in_chain(num: usize) -> usize {
match num {
1 | 89 => num,
_ => last_in_chain(digit_square_sum(num)),
}
}
fn main() {
let ... |
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... | #Scala | Scala | import scala.annotation.tailrec
object Euler92 extends App {
override val executionStart = compat.Platform.currentTime
@tailrec
private def calcRec(i: Int): Int = {
@tailrec
def iter0(n: Int, total: Int): Int =
if (n > 0) {
val rest = n % 10
iter0(n / 10, total + rest * rest)
... |
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers | Index finite lists of positive integers | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
Task
Implement such a mapping:
write a function rank which assigns an integer to any finite, arbi... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func rank(l []uint) (r big.Int) {
for _, n := range l {
r.Lsh(&r, n+1)
r.SetBit(&r, int(n), 1)
}
return
}
func unrank(n big.Int) (l []uint) {
m := new(big.Int).Set(&n)
for a := m.BitLen(); a > 0; {
m.SetBit(m, a-1, 0)
... |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Int-Sequence.
DATA DIVISION.
WORKING-STORAGE SECTION.
* *> 36 digits is the largest size a numeric field can have.
01 I PIC 9(36).
PROCEDURE DIVISION.
* *> Display numbers until I overflows.
PERFORM VARYING I FR... |
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... | #CoffeeScript | CoffeeScript |
# This very limited BCD-based collection of functions
# makes it easy to count very large numbers. All arrays
# start off with the ones columns in position zero.
# Using arrays of decimal-based digits to model integers
# doesn't make much sense for most tasks, but if you
# want to keep counting forever, this does th... |
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... | #Common_Lisp | Common Lisp | > (apropos "MOST-POSITIVE" :cl)
MOST-POSITIVE-LONG-FLOAT, value: 1.7976931348623158D308
MOST-POSITIVE-SHORT-FLOAT, value: 3.4028172S38
MOST-POSITIVE-SINGLE-FLOAT, value: 3.4028235E38
MOST-POSITIVE-DOUBLE-FLOAT, value: 1.7976931348623158D308
MOST-POSITIVE-FIXNUM, value: 536870911
> (apropos "MOST-NEGATIVE" :cl)
MOST-N... |
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... | #Component_Pascal | Component Pascal |
MODULE Infinity;
IMPORT StdLog;
PROCEDURE Do*;
VAR
x: REAL;
BEGIN
x := 1 / 0;
StdLog.String("x:> ");StdLog.Real(x);StdLog.Ln
END Do;
|
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... | #Nemerle | Nemerle | interface ICamera {
// ...
}
class MobilePhone {
// ...
}
class CameraPhone: MobilePhone, ICamera {
// ...
} |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
class RInheritMultiple public
method main(args = String[]) public static
iPhone = RInheritMultiple_CameraPhone()
if iPhone <= RInheritMultiple_Camera then -
say -
'Object' hashToString(iPhone) '['iPhone.getClass().getSimp... |
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... | #J | J |
tasks=: (gap , (,:~ index))@:niven
gap=: 0 ,~ 2 -~/\ ]
index=: i.@:#
niven=: I.@:nivenQ@:i.
nivenQ=: 0 = (|~ ([: (+/"1) 10&#.^:_1))
assert 1 0 1 -: nivenQ 10 11 12 NB. demonstrate correct niven test
assert 1 = +/ 10 12 E. niven 100 NB. the sublist 10 12 occurs once in niven numbers less than 100
assert 0 1 6 9... |
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... | #Java | Java |
public class NivenNumberGaps {
// Title: Increasing gaps between consecutive Niven numbers
public static void main(String[] args) {
long prevGap = 0;
long prevN = 1;
long index = 0;
System.out.println("Gap Gap Index Starting Niven");
for ( long n = 2 ; n < ... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Integer overflow
# # Variables:
#
typeset -si SHORT_INT
typeset -i INTEGER
typeset -li LONG_INT
######
# main #
######
(( SHORT_INT = 2**15 -1 )) ; print "SHORT_INT (2^15 -1) = $SHORT_INT"
(( SHORT_INT = 2**15 )) ; print "SHORT_INT (2^15) : $SHORT_INT"
(( INTEGER = 2**31 -1 )) ; print " I... |
http://rosettacode.org/wiki/Integer_overflow | Integer overflow | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually 8-bit, 16-bit, 32-bit, or 64-bit.
The integers supported by such a type can be signed or unsigned.
Arithmetic for machine level integers can often be done by single CPU instruct... | #Lingo | Lingo | #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.
| #Elena | Elena | import system'routines;
import system'io;
import extensions'routines;
public program()
{
ReaderEnumerator.new(File.assign:"file.txt").forEach(printingLn)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.