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/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, ... | #Raku | Raku | sub postfix:<𒋦>($n) { say "$n trilobites" }
sub term:<𝍧> { unival('𝍧') }
𝍧𒋦 |
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, ... | #REXX | REXX | /*REXX program determines what characters are valid for REXX symbols. */
@= /*set symbol characters " " */
do j=0 for 2**8 /*traipse through all the chars. */
_=d2c(j) /*convert decimal number to char.*/
if datatype(_,'S'... |
http://rosettacode.org/wiki/Image_noise | Image noise | Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| #C | C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
pr... |
http://rosettacode.org/wiki/Image_convolution | Image convolution | One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square
K
k
l
{\displaystyle K_{kl}}
, where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine... | #Common_Lisp | Common Lisp | (load "rgb-pixel-buffer")
(load "ppm-file-io")
(defpackage #:convolve
(:use #:common-lisp #:rgb-pixel-buffer #:ppm-file-io))
(in-package #:convolve)
(defconstant +row-offsets+ '(-1 -1 -1 0 0 0 1 1 1))
(defconstant +col-offsets+ '(-1 0 1 -1 0 1 -1 0 1))
(defstruct cnv-record descr width kernel divisor offset)
(def... |
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... | #X86_Assembly | X86 Assembly |
section .data
count dd 0
section .text
global _main
_main:
mov ecx, 1
looping:
mov eax, ecx ;pass parameter in eax
push ecx
call doMath
pop ecx
add [count], eax ;doMath returns 0 or 1 in eax
inc ecx
cmp ecx, 100000001
jl looping
mov eax... |
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... | #Phix | Phix | without javascript_semantics
include mpfr.e
procedure rank(mpz r, sequence s)
s = deep_copy(s)
for i=1 to length(s) do
s[i] = sprintf("%d",s[i])
end for
mpz_set_str(r,join(s,'a'),11)
end procedure
function unrank(mpz i)
sequence res = split(mpz_get_str(i,11),'a')
for j=1 to length(r... |
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... | #DCL | DCL | $ i = 1
$ loop:
$ write sys$output i
$ i = i + 1
$ goto loop |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Delphi | Delphi | program IntegerSequence;
{$APPTYPE CONSOLE}
var
i: Integer;
begin
for i := 1 to High(i) do
WriteLn(i);
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... | #Forth | Forth | : inf ( -- f ) 1e 0e f/ ;
inf f. \ implementation specific. GNU Forth will output "inf"
: inf? ( f -- ? ) s" MAX-FLOAT" environment? drop f> ;
\ IEEE infinity is the only value for which this will return true
: has-inf ( -- ? ) ['] inf catch if false else inf? then ; |
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... | #Fortran | Fortran | program to_f_the_ineffable
use, intrinsic :: ieee_arithmetic
integer :: i
real dimension(2) :: y, x = (/ 30, ieee_value(y,ieee_positive_inf) /)
do i = 1, 2
if (ieee_support_datatype(x(i))) then
if (ieee_is_finite(x(i))) then
print *, 'x(',i,') is finite'
else
... |
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... | #Raku | Raku | class Camera {}
class MobilePhone {}
class CameraPhone is Camera is MobilePhone {}
say CameraPhone.^mro; # undefined type object
say CameraPhone.new.^mro; # instantiated object |
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... | #Ring | Ring |
# Project : Inheritance/Multiple
mergemethods(:CameraPhone,:MobilePhone)
o1 = new CameraPhone
? o1
? o1.testCamera()
? o1.testMobilePhone()
func AddParentClassAttributes oObject,cClass
# Add Attributes
cCode = "oTempObject = new " + cClass
eval(cCode)
for cAttribute in Attributes(... |
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... | #Ruby | Ruby | module Camera
# define methods here
end
class MobilePhone
# define methods here
end
class CameraPhone < MobilePhone
include Camera
# define methods here
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... | #Rust | Rust | trait Camera {}
trait MobilePhone {}
trait CameraPhone: Camera + MobilePhone {} |
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... | #REXX | REXX | /*REXX program finds and displays the largest gap between Niven numbers (up to LIMIT).*/
parse arg lim . /*obtain optional arguments from the CL*/
if lim=='' | lim==',' then lim= 10000000 /*Not specified? Then use the default.*/
numeric digits 2 + max(8, length(lim) ) ... |
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... | #PicoLisp | PicoLisp | 100H: /* SHOW INTEGER OVERFLOW */
/* CP/M SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CONSOLE I/O ROUTINES */
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); 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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim line_ As String ' line is a keyword
Open "input.txt" For Input As #1
While Not Eof(1)
Input #1, line_
Print line_ ' echo to the console
Wend
Close #1
Print
Print "Press any key to quit"
Sleep |
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.
| #Frink | Frink | while (line = readStdin[]) != undef
println[line]
|
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... | #Rust | Rust |
use num::BigUint;
use num::CheckedSub;
use num_traits::{One, Zero};
fn isqrt(number: &BigUint) -> BigUint {
let mut q: BigUint = One::one();
while q <= *number {
q <<= &2;
}
let mut z = number.clone();
let mut result: BigUint = Zero::zero();
while q > One::one() {
q >>= &... |
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... | #S-BASIC | S-BASIC |
comment
return integer square root of n using quadratic
residue algorithm. WARNING: the function will fail
for x > 16,383.
end
function isqrt(x = integer) = integer
var q, r, t = integer
q = 1
while q <= x do
q = q * 4 rem overflow may occur here!
r = 0
while q > 1 do
begin
q = ... |
http://rosettacode.org/wiki/Inverted_index | Inverted index | An Inverted Index is a data structure used to create full text search.
Task
Given a set of text files, implement a program to create an inverted index.
Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.
The search index can be i... | #OCaml | OCaml | ocamlc -c \
-pp "camlp4o -I `ocamlc -where`/type-conv \
-I `ocamlc -where`/sexplib \
pa_type_conv.cmo pa_sexp_conv.cmo" \
unix.cma bigarray.cma nums.cma -I +sexplib sexplib.cma str.cma \
inv.ml
|
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... | #Perl | Perl | use Set::Object 'set';
# given an array of files, returns the index
sub createindex
{
my @files = @_;
my %iindex;
foreach my $file (@files)
{
open(F, "<", $file) or die "Can't read file $file: $!";
while(<F>) {
s/\A\W+//;
foreach my $w (map {lc} grep {length() >= 3} spl... |
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... | #OCaml | OCaml | # Sys.ocaml_version;;
- : string = "3.10.2" |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #Oforth | Oforth | : bloopAbs
| bl m |
System.VERSION println
Word find("bloop") ->bl
bl isA(Constant) ifFalse: [ "bloop constant does not exist" println return ]
"abs" asMethod ->m
m ifNull: [ "abs method does not exist" println return ]
System.Out "bloop value is : " << bl value << cr
System.Out "bloop abs ... |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Objeck | Objeck | class Josephus {
function : Execute(n : Int, k : Int) ~ Int {
killIdx := 0;
prisoners := Collection.IntVector->New();
for(i := 0;i < n;i+=1;){
prisoners->AddBack(i);
};
"Prisoners executed in order:"->PrintLine();
while(prisoners->Size() > 1){
killIdx := (killIdx + k - 1) % priso... |
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... | #Quackery | Quackery | > quackery
Welcome to Quackery.
Enter "leave" to leave the shell.
/O> say " now entering a nested shell..."
... shell
...
now entering a nested shell...
/O> say " now leaving the nested shell"
... leave
...
now leaving the nested shell
Auf wiedersehen.
Stack empty.
/O> say " now leaving the shell invoked at ... |
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... | #R | R | $ R
R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language supp... |
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... | #Racket | Racket | oiseau:/tmp> racket
Welcome to Racket v5.3.3.5.
> (define (f string-1 string-2 separator)
(string-append string-1 separator separator string-2))
> (f "Rosetta" "Code" ":")
"Rosetta::Code"
> ^D
oiseau:/tmp> |
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)
... | #Rust | Rust | fn main() {
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}
fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != 13 {
return false;
}
... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #APL | APL | ⍕1+⍎'12345' |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- succString :: Bool -> String -> String
on succString(blnPruned, s)
script go
on |λ|(w)
try
if w contains "." then
set v to w as real
else
... |
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 |... | #Avail | Avail | // This code doesn't try to protect against any malformed input.
a ::= next line from standard input→integer;
b ::= next line from standard input→integer;
If a > b then [Print: "a > b";]
else if a < b then [Print: "a < b";]
else if a = b then [Print: "a = b";]; |
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 |... | #AWK | AWK | /[0-9]* [0-9]*/{
if ($1 == $2) print $1, "is equal to", $2
if ($1 < $2) print $1, "is less than", $2
if ($1 > $2) print $1, "is greater than", $2
} |
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
| #Batch_File | Batch File |
call file2.bat
|
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
| #BBC_BASIC | BBC BASIC | CALL filepath$ |
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
| #Bracmat | Bracmat | get$"<i>module</i>" |
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... | #Java | Java | public class Animal{
//functions go here...
} |
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #JavaScript | JavaScript | function 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... | #Julia | Julia |
abstract type Animal end
abstract type Dog <: Animal end
abstract type Cat <: Animal end
struct Lab <: Dog end
struct Collie <: Dog end
|
http://rosettacode.org/wiki/Hunt_the_Wumpus | Hunt the Wumpus | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Create a simple implementation of the classic textual game Hunt The Wumpus.
The rules are:
The game is set in a cave that consists ... | #Ada | Ada | package Wumpus is
procedure Start_Game;
end Wumpus;
|
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #F.23 | F# |
seq{(char)0..(char)127} |> Seq.filter(System.Char.IsUpper) |> Seq.iter (string >> printf "%s"); printfn ""
seq{(char)0..(char)127} |> Seq.filter(System.Char.IsLower) |> Seq.iter (string >> printf "%s"); printfn ""
|
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Factor | Factor |
USE: math.ranges
CHAR: A CHAR: Z [a,b] >string print
CHAR: a CHAR: z [a,b] >string print
|
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #FreeBASIC | FreeBASIC | enum chartypes
LOWER = -1, UPPER = 1, NOTLETTER = 0
end enum
function letter_case( ch as string ) as byte
'exploits the fact that ucase and lcase consider non-letters to be
'both upper and lower case
if ucase(ch)=lcase(ch) then return NOTLETTER
if ch = ucase(ch) then return UPPER
return LOWER
e... |
http://rosettacode.org/wiki/Imaginary_base_numbers | Imaginary base numbers | Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.
The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]
Other imagi... | #D | D | import std.algorithm;
import std.array;
import std.complex;
import std.conv;
import std.format;
import std.math;
import std.stdio;
import std.string;
Complex!double inv(Complex!double v) {
auto denom = v.re*v.re + v.im*v.im;
return v.conj / denom;
}
QuaterImaginary toQuaterImaginary(Complex!double v) {
... |
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, ... | #Scala | Scala | object IdiomaticallyDetermineSymbols extends App {
private def print(msg: String, limit: Int, p: Int => Boolean, fmt: String) =
println(msg + (0 to 0x10FFFF).filter(p).take(limit).map(fmt.format(_)).mkString + "...")
print("Java Identifier start: ", 72, cp => Character.isJavaIdentifierStart(cp), "%c")
... |
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, ... | #Tcl | Tcl | for {set c 0;set printed 0;set special {}} {$c <= 0xffff} {incr c} {
set ch [format "%c" $c]
set v "_${ch}_"
#puts "testing variable named $v"
if {[catch {set $v $c; set $v} msg] || $msg ne $c} {
puts [format "\\u%04x illegal in names" $c]
incr printed
} elseif {[catch {subst $$v} msg] == 0 && $ms... |
http://rosettacode.org/wiki/Image_noise | Image noise | Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle... |
http://rosettacode.org/wiki/Image_convolution | Image convolution | One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square
K
k
l
{\displaystyle K_{kl}}
, where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine... | #D | D | import std.string, std.math, std.algorithm, grayscale_image;
struct ConvolutionFilter {
double[][] kernel;
double divisor, offset_;
string name;
}
Image!Color convolve(Color)(in Image!Color im,
in ConvolutionFilter filter)
pure nothrow in {
assert(im !is null);
asse... |
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... | #zkl | zkl | fcn check(number){ // a list of digits: 13 is L(0,0,0,0,0,0,1,3)
candidate:=number.reduce(fcn(sum,n){ sum*10 + n },0); // digits to int
while(candidate != 89 and candidate != 1) // repeatedly sum squares of digits
{ candidate = candidate.split().reduce(fcn(sum,c){ sum + c*c },0); }
if(candidate ==... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET n=0
20 FOR i=1 TO 1000
30 LET j=i
40 LET k=0
50 LET k=INT (k+FN m(j,10)^2)
60 LET j=INT (j/10)
70 IF j<>0 THEN GO TO 50
80 LET j=k
90 IF j=89 OR j=1 THEN GO TO 100
95 GO TO 40
100 IF j>1 THEN LET n=n+1
110 NEXT i
120 PRINT "Version 1: ";n
200 DEF FN m(a,b)=a-INT (a/b)*b: REM modulo |
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... | #Python | Python | def rank(x): return int('a'.join(map(str, [1] + x)), 11)
def unrank(n):
s = ''
while n: s,n = "0123456789a"[n%11] + s, n//11
return map(int, s.split('a'))[1:]
l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l |
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... | #Quackery | Quackery | [ $ "" swap
witheach
[ number$
char A join join ]
11 base put
$->n drop
base release ] is rank ( [ --> n )
[ 11 base put
number$
base release
[] $ "" rot
witheach
[ dup char A = iff
[ drop
$->n drop join
$ "" ]
... |
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... | #Racket | Racket | #lang racket/base
(require (only-in racket/string string-join string-split))
(define (integer->octal-string i)
(number->string i 8))
(define (octal-string->integer s)
(string->number s 8))
(define (rank is)
(string->number (string-join (map integer->octal-string is) "8")))
(define (unrank ranking)
(map ... |
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... | #DWScript | DWScript |
var i: Integer;
for i:=1 to High(i) do
PrintLn(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... | #Dyalect | Dyalect | var n = 0
while true {
n += 1
print(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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "crt/math.bi"
#Print Typeof(1.5) ' Prints DOUBLE at compile time
Dim d As Typeof(1.5) = INFINITY
Print d; " (String representation of Positive Infinity)"
Sleep
|
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | # Floating point infinity
inf := FLOAT_INT(1) / FLOAT_INT(0);
IS_FLOAT(inf);
#true;
# GAP has also a formal ''infinity'' value
infinity in Cyclotomics;
# 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... | #GAP | GAP | # Floating point infinity
inf := FLOAT_INT(1) / FLOAT_INT(0);
IS_FLOAT(inf);
#true;
# GAP has also a formal ''infinity'' value
infinity in Cyclotomics;
# true |
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... | #Scala | Scala | trait Camera
trait MobilePhone
class CameraPhone extends Camera with MobilePhone |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Self | Self | camera = () |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Sidef | Sidef | class Camera {};
class MobilePhone {};
class CameraPhone << Camera, MobilePhone {}; |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Slate | Slate | define: #Camera.
define: #MobilePhone.
define: #CameraPhone &parents: {Camera. MobilePhone}. |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Swift | Swift | protocol Camera {
}
protocol Phone {
}
class CameraPhone: Camera, Phone {
} |
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... | #Ruby | Ruby | nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} }
cur_gap = 0
puts 'Gap Index of gap Starting Niven'
nivens.each_cons(2).with_index(1) do |(n1, n2), i|
break if i > 10_000_000
if n2-n1 > cur_gap then
printf "%3d %15s %15s\n", n2-n1, i, n1
cur_gap = n2-n1
end... |
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... | #Rust | Rust | // [dependencies]
// num-format = "0.4"
// Returns the sum of the digits of n given the
// sum of the digits of n - 1
fn digit_sum(mut n: u64, mut sum: u64) -> u64 {
sum += 1;
while n > 0 && n % 10 == 0 {
sum -= 9;
n /= 10;
}
sum
}
fn divisible(n: u64, d: u64) -> bool {
if (d & 1... |
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... | #Wren | Wren | import "/fmt" for Fmt
var newSum // recursive
newSum = Fn.new {
var ms // also recursive
ms = Fn.new {
ms = newSum.call()
return ms.call()
}
var msd = 0
var d = 0
return Fn.new {
if (d < 9) {
d = d + 1
} 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... | #Pike | Pike | 100H: /* SHOW INTEGER OVERFLOW */
/* CP/M SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CONSOLE I/O ROUTINES */
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); 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.
| #FutureBasic | FutureBasic | include "NSLog.incl"
local fn ReadTextFile
CFURLRef url
CFStringRef string
url = openpanel 1, @"Select text file..."
if ( url )
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
if ( string )
NSLog(@"%@",string)
end if
else
// user cancelled
end if
end fn
... |
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.
| #gnuplot | gnuplot | !cat |
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... | #Scheme | Scheme | (import (scheme base))
(import (scheme write))
(import (format)) ;; Common Lisp formatting for CHICKEN Scheme.
(define (find-a-power-of-4-greater-than-x x)
(let loop ((q 1))
(if (< x q)
q
(loop (* 4 q)))))
(define (isqrt+remainder x)
(let loop ((q (find-a-power-of-4-greater-than-x x))
... |
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... | #Phix | Phix | -- demo\rosetta\Inverted_index.exw
without js -- (file i/o)
integer word_count = 0
sequence filenames = {}
function is_ascii(string txt)
for i=1 to length(txt) do
integer ch = txt[i]
if ch='\0' or ch>=#7F then return 0 end if
end for
return 1
end function
procedure add_words(string name, s... |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #OxygenBasic | OxygenBasic |
$ rtlversion "0.4.0"
'
#if not match(rtlversion,o2version)
#error "This RTL version mismatches o2 version "+o2version
#else
print o2version
#endif
float bloop=-1618
#ifdef bloop
#ifdef abs
print abs(bloop)
#endif
#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... | #Oz | Oz | declare
Version = {Property.get 'oz.version'}
%% Version is an atom like '1.4.0'. So we can not compare it directly.
%% Extract the version components:
[Major Minor Release] = {Map {String.tokens {Atom.toString Version} &.} String.toInt}
in
if Major >= 1 andthen Minor >= 4 then
%% check whether module N... |
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... | #Oforth | Oforth | : josephus(n, k)
| prisoners killed i |
n seq asListBuffer ->prisoners
ListBuffer newSize(n) ->killed
0 n 1- loop: i [
k 1- + prisoners size mod dup 1+ prisoners removeAt
killed add
] drop
System.Out "Killed : " << killed << "\nSurvivor : " << prisoners << cr
;
|
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... | #Raku | Raku | $ rakudo/perl6
> sub f($str1,$str2,$sep) { $str1~$sep x 2~$str2 };
f
> f("Rosetta","Code",":");
Rosetta::Code
>
|
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #REBOL | REBOL | $ rebol -q
>> f: func [a b s] [print rejoin [a s s b]]
>> f "Rosetta" "Code" ":"
Rosetta::Code
>> q |
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)
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isISBN13 (in var string: input) is func
result
var boolean: isbn is FALSE;
local
var char: c is ' ';
var integer: digit is 0;
var integer: i is 1;
var integer: sum is 0;
begin
input := replace(input, " ", "");
input := replace(input, "-",... |
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)
... | #Standard_ML | Standard ML | local
fun check (c, p as (m, n)) =
if Char.isDigit c then
(not m, (if m then 3 * (ord c - 48) else ord c - 48) + n)
else
p
in
fun checkISBN s =
Int.rem (#2 (CharVector.foldl check (false, 0) s), 10) = 0
end
val test = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]... |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program incstring.s */
/* Constantes */
.equ BUFFERSIZE, 100
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data *... |
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 |... | #Axe | Axe | Lbl FUNC
If r₁<r₂
Disp "LESS THAN",i
End
If r₁=r₂
Disp "EQUAL TO",i
End
If r₁>r₂
Disp "GREATER THAN",i
End
Return |
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
| #C_.2F_C.2B.2B | C / C++ | /* Standard and other library header names are enclosed between chevrons */
#include <stdlib.h>
/* User/in-project header names are usually enclosed between double-quotes */
#include "myutil.h"
|
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
| #C.23 | C# | /* The C# language specification does not give a mechanism for 'including' one source file within another,
* likely because there is no need - all code compiled within one 'assembly' (individual IDE projects
* are usually compiled to separate assemblies) can 'see' all other code within that assembly.
*/ |
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... | #Kite | Kite | class Animal [
#Method goes here
];
class Dog from Animal [
#Method goes here
];
class Lab from Dog [
#Method goes here
];
class collie from Dog [
#Method goes here
];
|
http://rosettacode.org/wiki/Inheritance/Single | Inheritance/Single | This task is about derived types; for implementation inheritance, see Polymorphism.
Inheritance is an operation of type algebra that creates a new type from one or several parent types.
The obtained type is called derived type.
It inherits some of the properties of its parent types.
Usually inherited properties... | #Kotlin | Kotlin | // version 1.0.6
open class Animal {
override fun toString() = "animal"
}
open class Dog : Animal() {
override fun toString() = "dog"
}
class Cat : Animal() {
override fun toString() = "cat"
}
class Labrador : Dog() {
override fun toString() = "labrador"
}
class Collie : Dog() {
override f... |
http://rosettacode.org/wiki/Hunt_the_Wumpus | Hunt the Wumpus | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Create a simple implementation of the classic textual game Hunt The Wumpus.
The rules are:
The game is set in a cave that consists ... | #BASIC | BASIC | 10 DEFINT A-Z: DIM R(19,3),P(1),B(1)
20 FOR I=0 TO 19: READ R(I,0),R(I,1),R(I,2): NEXT
30 INPUT "Enter a number";X: X=RND(-ABS(X))
40 PRINT: PRINT "*** HUNT THE WUMPUS ***"
50 PRINT "-----------------------": PRINT
60 FOR I=0 TO 1: GOSUB 500: P(I)=X: GOSUB 500: B(I)=X: NEXT
70 GOSUB 500: W=X: GOSUB 500: P=X
80 A=5
90 I... |
http://rosettacode.org/wiki/Hunt_the_Wumpus | Hunt the Wumpus | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Create a simple implementation of the classic textual game Hunt The Wumpus.
The rules are:
The game is set in a cave that consists ... | #APL | APL |
// constant value 2d array to represent the dodecahedron
// room structure
const static int adjacentRooms[20][3] = {
{1, 4, 7}, {0, 2, 9}, {1, 3, 11}, {2, 4, 13}, {0, 3, 5},
{4, 6, 14}, {5, 7, 16}, {0, 6, 8}, {7, 9, 17}, {1, 8, 10},
{9, 11, 18}, {2, 10, 12}, {11, 13, 19}, {3, 12, 14}, {5, 13,... |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Go | Go | package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
f... |
http://rosettacode.org/wiki/Imaginary_base_numbers | Imaginary base numbers | Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.
The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]
Other imagi... | #Go | Go | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
const (
twoI = 2.0i
invTwoI = 1.0 / twoI
)
type quaterImaginary struct {
b2i string
}
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j],... |
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, ... | #Wren | Wren | for (i in 97..122) System.write(String.fromByte(i))
for (i in 65..90) System.write(String.fromByte(i))
System.print("_") |
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, ... | #XPL0 | XPL0 | char C, C1;
[Text(0, "First character set: ");
for C:= 0 to 255 do
if C>=^A then if C<=^Z ! C=^_ then
ChOut(0, C);
CrLf(0);
Text(0, "Next characters set: ");
for C:= 0 to 255 do
[if C>=^a & C<=^z then C1:= C & $DF \to uppercase
else C1:= C;
case of
... |
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, ... | #zkl | zkl | [0..255].filter(fcn(n){
try{ Compiler.Compiler.compileText("var "+n.text) }
catch{ False }
}).apply("text").concat() |
http://rosettacode.org/wiki/Image_noise | Image noise | Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| #C.2B.2B | C++ |
#include <windows.h>
#include <sstream>
#include <tchar.h>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const unsigned int BMP_WID = 320, ... |
http://rosettacode.org/wiki/Image_convolution | Image convolution | One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square
K
k
l
{\displaystyle K_{kl}}
, where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine... | #Go | Go | package main
import (
"fmt"
"image"
"image/color"
"image/jpeg"
"math"
"os"
)
// kf3 is a generic convolution 3x3 kernel filter that operatates on
// images of type image.Gray from the Go standard image library.
func kf3(k *[9]float64, src, dst *image.Gray) {
for y := src.Rect.Min.Y; y < ... |
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... | #Raku | Raku | sub rank(*@n) { :11(@n.join('A')) }
sub unrank(Int $n) { $n.base(11).split('A') }
say my @n = (1..20).roll(12);
say my $n = rank(@n);
say unrank $n; |
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... | #REXX | REXX | /*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */
parse arg $ /*obtain optional argument (int list).*/
if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/
... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | 1
while /= -- dup dup:
!. dup
++
drop |
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... | #E | E | for i in int > 0 { println(i) } |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #Go | Go | package main
import (
"fmt"
"math"
)
// function called for by task
func posInf() float64 {
return math.Inf(1) // argument specifies positive infinity
}
func main() {
x := 1.5 // type of x determined by literal
// that this compiles demonstrates that PosInf returns same type as x,
// the t... |
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... | #Tcl | Tcl | package require TclOO
oo::class create Camera
oo::class create MobilePhone
oo::class create CameraPhone {
superclass Camera MobilePhone
} |
http://rosettacode.org/wiki/Inheritance/Multiple | Inheritance/Multiple | Multiple inheritance allows to specify that one class is a subclass of several other classes.
Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.
Task
Write two classes (or interfaces) Camera and MobilePhone, then write a class Camer... | #Wren | Wren | class Camera {
construct new() {}
snap() { System.print("taking a photo") }
}
class Phone {
construct new() {}
call() { System.print("calling home") }
}
class CameraPhone is Camera {
construct new(phone) { _phone = phone } // uses composition for the Phone part
// inherits Camera's snap() me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.