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/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...
#OCaml
OCaml
let get_rgb img x y = let _, r_channel,_,_ = img in let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in if (x < 0) || (x >= width) then (0,0,0) else if (y < 0) || (y >= height) then (0,0,0) else (* feed borders with black *) get_pixel img x y     let convolve_get_value...
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...
#Forth
Forth
: ints ( -- ) 0 begin 1+ dup cr u. dup -1 = until 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...
#Fortran
Fortran
program Intseq implicit none   integer, parameter :: i64 = selected_int_kind(18) integer(i64) :: n = 1   ! n is declared as a 64 bit signed integer so the program will display up to ! 9223372036854775807 before overflowing to -9223372036854775808 do print*, n n = n + 1 end do end program
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...
#MATLAB_.2F_Octave
MATLAB / Octave
a = +Inf; isinf(a)  
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...
#Maxima
Maxima
/* Maxima has inf (positive infinity) and minf (negative infinity) */   declare(x, real)$   is(x < inf); /* true */   is(x > minf); /* true */   /* However, it is an error to try to divide by zero, even with floating-point numbers */ 1.0/0.0; /* expt: undefined: 0 to a negative exponent. -- an error. To debug this t...
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...
#Metafont
Metafont
infinity := 4095.99998;
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...
#MiniScript
MiniScript
posInfinity = 1/0 print posInfinity
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...
#Sidef
Sidef
var (a, b, c) = (9223372036854775807, 5000000000000000000, 3037000500); [-(-a - 1), b + b, -a - a, c * c, (-a - 1)/-1].each { say _ };
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...
#Smalltalk
Smalltalk
2147483647 + 1. -> 2147483648 2147483647 add_32: 1 -> -2147483648 4294967295 + 1. -> 4294967296 16rFFFFFFFF add_32u: 1. -> 0 ... simular stuff for sub32/mul32 ...
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.
#LIL
LIL
# # canread test (note that canread is not available in LIL/FPLIL itself # but provided by the command line interfaces in main.c/lil.pas) # # You can either call this and enter lines directly (use Ctrl+Z/Ctrl+D # to finish) or a redirect (e.g. lil canread.lil < somefile.txt) # # Normally this is how you are supposed to...
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.
#Logo
Logo
while [not eof?] [print readline]
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...
#Rust
Rust
// Part 1: Inverted index structure   use std::{ borrow::Borrow, collections::{BTreeMap, BTreeSet}, };   #[derive(Debug, Default)] pub struct InvertedIndex<T> { indexed: BTreeMap<String, BTreeSet<usize>>, sources: Vec<T>, }   impl<T> InvertedIndex<T> { pub fn add<I, V>(&mut self, source: T, tokens: ...
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...
#Retro
Retro
@Version #201906 lt+ &bye if
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...
#REXX
REXX
/*output from parse version (almost all REXX versions) */ /* theREXXinterpreterName level mm Mon yyyy */ parse version . level . if level<4 then exit
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...
#Processing
Processing
void setup() { println("Survivor: " + execute(41, 3)); println("Survivors: " + executeAllButM(41, 3, 3)); }   int execute(int n, int k) { int killIdx = 0; IntList prisoners = new IntList(n); for (int i = 0; i < n; i++) { prisoners.append(i); } println("Prisoners executed in order:"); while (prisoner...
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...
#Wren
Wren
$ ./wren \\/"- \_/ wren v0.2.0 > var f = Fn.new { |s1, s2, sep| s1 + sep + sep + s2 } > f.call("Rosetta", "Code", ":") Rosetta::Code > ^C $
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...
#zkl
zkl
$ zkl zkl 1.12.8, released 2014-04-01 zkl: fcn f(a,b,c){String(a,c,c,b)} Void zkl: f("Rosetta", "Code", ":") Rosetta::Code zkl:
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#BASIC
BASIC
10 DEFINT A-Z 20 OPEN "I",1,"UNIXDICT.TXT": GOTO 60 30 LINE INPUT #1,W$ 40 IF INSTR(W$,"ie") THEN IF INSTR(W$,"cie") THEN CI=CI+1 ELSE XI=XI+1 50 IF INSTR(W$,"ei") THEN IF INSTR(W$,"cei") THEN CE=CE+1 ELSE XE=XE+1 60 IF NOT EOF(1) GOTO 30 ELSE CLOSE #1 70 PRINT "CIE:";CI 80 PRINT "xIE:";XI 90 PRINT "CEI:";CE 100 PRINT ...
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Burlesque
Burlesque
  ri?ish  
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   /* Constraints: input is in the form of (\+|-)?[0-9]+ * and without leading zero (0 itself can be as "0" or "+0", but not "-0"); * input pointer is realloc'able and may change; * if input has leading + sign, return may or may not keep it. * The const...
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 |...
#C.2B.2B
C++
#include <iostream>   int main() { int a, b;   if (!(std::cin >> a >> b)) { std::cerr << "could not read the numbers\n"; return 1; }   // test for less-than if (a < b) std::cout << a << " is less than " << b << "\n";   // test for equality if (a == b) std::cout << a << " is equal to " << b...
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
#FreeBASIC
FreeBASIC
' person.bi file Type Person name As String age As UInteger Declare Operator Cast() As String End Type   Operator Person.Cast() As String Return "[" + This.name + ", " + Str(This.age) + "]" End Operator
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
#Frink
Frink
  include resources "SomeImage.png" include resources "SomeMovie.mpeg" include resources "SomeSound.aiff" include resources "SomeIcon.icns" include resources "Info.plist" //Custom preference file to replace FB's generic app preferences  
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...
#Perl
Perl
package Animal; #functions go here... 1;
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...
#Phix
Phix
without js -- (class) class Animal private string species end class class Dog extends Animal public procedure bark() puts(1,"woof\n") end procedure end class class Lab extends Dog end class class Collie extends Dog end class class Cat extends Animal end class
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...
#PHP
PHP
class Animal { // functions go here... }   class Dog extends Animal { // functions go here... }   class Cat extends Animal { // functions go here... }   class Lab extends Dog { // functions go here... }   class Collie extends Dog { // functions go here... }
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#BBC_BASIC
BBC BASIC
REM Used the following as official standard: REM http://www.cnb.cz/cs/platebni_styk/iban/download/EBS204.pdf   REM Pairs of ISO 3166 country code & expected IBAN length for this country COULEN$="AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 CR21 HR21 CY28 CZ24 DK18 DO28 EE20 "+\ \ "F...
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <map> #include <sstream>   bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false;...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Arturo
Arturo
identityM: function [n][ result: array.of: @[n n] 0 loop 0..dec n 'i -> result\[i]\[i]: 1 return result ]   loop 4..6 'sz [ print sz loop identityM sz => print print "" ]
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 ...
#JavaScript
JavaScript
const starttxt = """   ATTENTION ALL WUMPUS LOVERS!!! THERE ARE NOW TWO ADDITIONS TO THE WUMPUS FAMILY OF PROGRAMS.   WUMP2: SOME DIFFERENT CAVE ARRANGEMENTS WUMP3: DIFFERENT HAZARDS   """   const helptxt = """ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. ...
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 ...
#Julia
Julia
const starttxt = """   ATTENTION ALL WUMPUS LOVERS!!! THERE ARE NOW TWO ADDITIONS TO THE WUMPUS FAMILY OF PROGRAMS.   WUMP2: SOME DIFFERENT CAVE ARRANGEMENTS WUMP3: DIFFERENT HAZARDS   """   const helptxt = """ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. ...
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...
#Z80_Assembly
Z80 Assembly
printChar equ &bb5a ;amstrad cpc bios call, prints the ascii code in accumulator to screen and increments text cursor. org &8000   ld a,'A'   UpperLoop: call PrintChar ;print accumulator inc a ;next letter cp 'Z'+1 ;is it whatever comes after Z? jr nz,upperLoop ;if not, print the next letter   l...
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...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR x=CODE "a" TO CODE "z" 20 PRINT CHR$ x; 30 NEXT x 40 PRINT 50 FOR x=CODE "A" TO CODE "Z" 60 PRINT CHR$ x; 70 NEXT x
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...
#Phix
Phix
with javascript_semantics include complex.e function base2(atom num, integer radix, precision = -8) if radix<-36 or radix>-2 then throw("radix out of range (-2..-36)") end if sequence result if num=0 then result = {"0",""} else integer place = 0 result = "" atom v = num...
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
#JavaScript
JavaScript
<body> <canvas id='c'></canvas>   <script> var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d');   var w = canvas.width = 320; var h = canvas.height = 240; var t1 = new Date().getTime(); var frame_count = 0; ctx.font = 'normal 400 24px/2 Unknown Font, sans-serif'; var img = ctx.createImageData(w...
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...
#Octave
Octave
function [r, g, b] = rgbconv2(a, c) r = im2uint8(mat2gray(conv2(a(:,:,1), c))); g = im2uint8(mat2gray(conv2(a(:,:,2), c))); b = im2uint8(mat2gray(conv2(a(:,:,3), c))); endfunction   im = jpgread("Lenna100.jpg"); emboss = [-2, -1, 0; -1, 1, 1; 0, 1, 2 ]; sobel = [-1., -2., -1.; 0., 0., 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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' FB does not natively support arbitrarily large integers though support can be added ' by using an external library such as GMP. For now we will just use an unsigned integer (32bit).   Print "Press Ctrl + C to stop the program at any time" Dim i As UInteger = 1   Do Print i i += 1 Loop Until 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...
#Frink
Frink
  i=0 while true { println[i] i = i + 1 }  
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Modula-2
Modula-2
MODULE inf;   IMPORT InOut;   BEGIN InOut.WriteReal (1.0 / 0.0, 12, 12); InOut.WriteLn END inf.
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Modula-3
Modula-3
MODULE Inf EXPORTS Main;   IMPORT IO, IEEESpecial;   BEGIN IO.PutReal(IEEESpecial.RealPosInf); IO.Put("\n"); END Inf.
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Nemerle
Nemerle
def posinf = double.PositiveInfinity; def a = IsInfinity(posinf); // a = true def b = IsNegativeInfinity(posinf); // b = false def c = IsPositiveInfinity(posinf); // c = 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...
#Nim
Nim
Inf
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...
#Swift
Swift
// By default, all overflows in Swift result in a runtime exception, which is always fatal // However, you can opt-in to overflow behavior with the overflow operators and continue with wrong results   var int32:Int32 var int64:Int64 var uInt32:UInt32 var uInt64:UInt64   println("signed 32-bit int:") int32 = -1 &* (-214...
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...
#Standard_ML
Standard ML
~(~9223372036854775807-1) ; poly: : error: Overflow exception raised while converting ~9223372036854775807 to int Int.maxInt ; val it = SOME 4611686018427387903: int option ~(~4611686018427387903 - 1); Exception- Overflow raised (~4611686018427387903 - 1) div ~1; Exception- Overflow raised 2147483648 * 2147483648 ; Ex...
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...
#Tcl
Tcl
proc tcl::mathfunc::clamp32 {x} { expr {$x<0 ? -((-$x) & 0x7fffffff) : $x & 0x7fffffff} } puts [expr { clamp32(2000000000 + 2000000000) }]; # ==> 1852516352
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.
#LSL
LSL
string sNOTECARD = "Input_Loop_Data_Source.txt"; default { integer iNotecardLine = 0; state_entry() { llOwnerSay("Reading '"+sNOTECARD+"'"); llGetNotecardLine(sNOTECARD, iNotecardLine); } dataserver(key kRequestId, string sData) { if(sData==EOF) { llOwnerSay("EOF"); } else { llOwnerSay((string)iNotec...
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.
#Lua
Lua
lines = {} str = io.read() while str do table.insert(lines,str) str = io.read() end
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...
#Scala
Scala
object InvertedIndex extends App { import java.io.File   // indexer val WORD = raw"(\w+)".r def parse(s: String) = WORD.findAllIn(s).map(_.toString.toLowerCase) def invertedIndex(files: Seq[File]): Map[String,Set[File]] = { var i = Map[String,Set[File]]() withDefaultValue Set.empty files.foreach{f => ...
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...
#Ring
Ring
  # Project: Introspection   if version() < 1.8 see "Version is too old" + " (" + version() + ")" + nl else see "Version is uptodate" + " (" + version() + ")" + nl ok bloop = 5 if isglobal("bloop") = 1 see "Variable " + "'bloop'" + " exists" + nl else see "Variable " + "'bloop'" + " doesn't exist" + nl ok i...
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...
#Ruby
Ruby
exit if RUBY_VERSION < '1.8.6' puts bloop.abs if defined?(bloop) and bloop.respond_to?(: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...
#PureBasic
PureBasic
NewList prisoners.i()   Procedure f2l(List p.i()) FirstElement(p())  : tmp.i=p() DeleteElement(p(),1) : LastElement(p()) AddElement(p())  : p()=tmp EndProcedure   Procedure l2f(List p.i()) LastElement(p())  : tmp.i=p() DeleteElement(p()) : FirstElement(p()) InsertElement(p()) : p()=tmp EndProcedur...
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#BASIC256
BASIC256
CI = 0 : XI = 0 : CE = 0 : XE = 0 open 1, "unixdict.txt"   do pal$ = readline (1) if instr(pal$, "ie") then if instr(pal$, "cie") then CI += 1 else XI += 1 endif if instr(pal$, "ei") then if instr(pal$, "cei") then CE += 1 else XE += 1 endif until eof(1) close 1   print "CIE: "; CI print "xIE: "; XI print "CEI...
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#C.23
C#
string s = "12345"; s = (int.Parse(s) + 1).ToString(); // The above functions properly for strings >= Int32.MinValue and // < Int32.MaxValue. ( -2147483648 to 2147483646 )   // The following will work for any arbitrary-length integer string. // (Assuming that the string fits in memory, leaving enough space // for th...
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 |...
#CFEngine
CFEngine
  bundle agent __main__ { vars: # Change the values to test: "first_integer" int => "10"; "second_integer" int => "9";   reports: "The first integer ($(first_integer)) is less than the second integer ($(second_integer))." if => islessthan( "$(first_integer)", "$(second_integer)" ); ...
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 |...
#ChucK
ChucK
  fun void intComparison (int one, int two) { if(one < two) <<< one, " is less than ", two >>>; if(one == two) <<< one, " is equal than ", two >>>; if(one > two) <<< one, " is greater than ", two >>>; } // uncomment next line and change values to test // intComparison (2,4);  
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
#Furryscript
Furryscript
  include resources "SomeImage.png" include resources "SomeMovie.mpeg" include resources "SomeSound.aiff" include resources "SomeIcon.icns" include resources "Info.plist" //Custom preference file to replace FB's generic app preferences  
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
#FutureBasic
FutureBasic
  include resources "SomeImage.png" include resources "SomeMovie.mpeg" include resources "SomeSound.aiff" include resources "SomeIcon.icns" include resources "Info.plist" //Custom preference file to replace FB's generic app preferences  
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
#Gambas
Gambas
Public Sub Form_Open() Dim sFile As String   sFile = File.Load("FileToLoad")   End  
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#PicoLisp
PicoLisp
(class +Animal)   (class +Dog +Animal)   (class +Cat +Animal)   (class +Lab +Dog)   (class +Collie +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...
#PowerShell
PowerShell
  class Animal {} class Dog : Animal {} class Cat: Animal {} class Lab : Dog {} class Collie : 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...
#PureBasic
PureBasic
Interface Animal Eat() Sleep() EndInterface   Interface Cat Extends Animal ChaseMouse() EndInterface   Interface Dog Extends Animal Bark() WagTail() EndInterface   Interface Lab Extends Dog Swim() EndInterface   Interface Collie Extends Dog HeardSheep() EndInterface
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Befunge
Befunge
>>" :NABI">:#,_>:~:"`"`48**-:55+-#v_$0::6g0>>8g-!\7g18g-!*!v>v>> <<_#v:#78#`8#+<^+!!*-*84\-9:g8:p8\<oo>1#$-#<0$>>>#v_"dilav" ^#<< >>^ >*-:20p9`9*1+55+**20g+"a"%10g1+00g%:4-!|^g6::_v#-*88:+1_vv>> <<^+`"Z"\+`\"0"\*`\"A"\`"9":::\-*86:g8p01:<<40p00_v#!--+99g5<v<< >>" si rebmun tahT">:#,_ 55+".",,@ >0"dilavni...
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Crystal
Crystal
def humble?(i) return true if (i < 2) return humble?(i // 2) if (i % 2 == 0) return humble?(i // 3) if (i % 3 == 0) return humble?(i // 5) if (i % 5 == 0) return humble?(i // 7) if (i % 7 == 0) false end   count, num = 0, 0_i64 digits = 10 # max digits for humble numbers limit = 10_i...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#BASIC
BASIC
  100 INPUT "MATRIX SIZE:"; SIZE% 110 GOSUB 200"IDENTITYMATRIX 120 FOR R = 0 TO SIZE% 130 FOR C = 0 TO SIZE% 140 LET S$ = CHR$(13) 150 IF C < SIZE% THEN S$ = " " 160 PRINT IM(R, C) S$; : NEXT C, R 170 END   200 REMIDENTITYMATRIX SIZE% 210 LET SIZE% = SIZE% - 1 220 DIM IM(SIZE%, SIZE%) 230 FO...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module WumpusGame { Print "Game: Hunt The Wumpus" Arrows=5 Dim Room(1 to 20) Room(1)=(2,6,5),(3,8,1),(4,10,2),(5,2,3),(1,14,4) Room(6)=(15,1,7),(17,6,8),(7,2,9),(18,8,10),(9,3,11) Room(11)=(19,10,12),(11,4,13),(20,12,14),(5,11,13), (6,16,14) Room(16)=(20,15,17),(16,7,18),(17,...
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 ...
#MiniScript
MiniScript
exits = [[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,15], [14,16,19], [6,15,17], [8,16,18], [10,17,19], [12,15,18]] hazard = [null] * 20 emptyRoom = function() while true room = floor(rnd * 20) if not hazar...
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...
#Python
Python
import math import re   def inv(c): denom = c.real * c.real + c.imag * c.imag return complex(c.real / denom, -c.imag / denom)   class QuaterImaginary: twoI = complex(0, 2) invTwoI = inv(twoI)   def __init__(self, str): if not re.match("^[0123.]+$", str) or str.count('.') > 1: rai...
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
#Julia
Julia
using Gtk, GtkUtilities   function randbw(ctx, w, h) pic = zeros(Int64, w, h) for i in 1:length(pic) pic[i] = rand([1, 0]) end copy!(ctx, pic) end   const can = @GtkCanvas() const win = GtkWindow(can, "Image Noise", 320, 240)   @guarded draw(can) do widget ctx = getgc(can) h = height(ca...
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
#Kotlin
Kotlin
// version 1.2.10   import java.awt.* import java.awt.event.* import java.awt.image.* import java.util.Random import javax.swing.*   class ImageNoise { var framecount = 0 var fps = 0 lateinit var image: BufferedImage val kernel: Kernel lateinit var cop: ConvolveOp val frame = JFrame("Java Image ...
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...
#Perl
Perl
use strict; use warnings;   use PDL; use PDL::Image2D;   my $kernel = pdl [[-2, -1, 0],[-1, 1, 1], [0, 1, 2]]; # emboss   my $image = rpic 'pythagoras_tree.png'; my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'}; wpic $smoothed, 'pythagoras_convolution.png';
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...
#Phix
Phix
-- -- demo\rosetta\Image_convolution.exw -- ================================== -- without js -- imImage, im_width, im_height, im_pixel, IupImageRGB, allocate, -- imFileImageLoadBitmap, peekNS, wait_key, IupImageFromImImage include pGUI.e constant filters = {-- Emboss {{-2.0, -1.0, 0.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...
#FunL
FunL
for i <- 1.. 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...
#Futhark
Futhark
  fun main(n: int): [n]int = iota 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...
#NS-HUBASIC
NS-HUBASIC
10 PRINT 1/0
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#OCaml
OCaml
infinity
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Oforth
Oforth
10 1000.0 powf dup println dup neg println 1 swap / println
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...
#Ol
Ol
+inf.0 ; positive infinity -inf.0 ; negative infinity
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...
#True_BASIC
True BASIC
PRINT "Signed 32-bit:" PRINT -(-2147483647-1)  !-2147483648 PRINT 2000000000 + 2000000000  !4000000000 PRINT -2147483647 - 2147483647  !-4294967294 PRINT 46341 * 46341  !2147488281 !PRINT (-2147483647-1) / -1  !ERROR: Illegal expression WHEN ERROR IN PRINT maxnum * 2  !...
http://rosettacode.org/wiki/Integer_overflow
Integer overflow
Some languages support one or more integer types of the underlying processor. This integer types have fixed size;   usually   8-bit,   16-bit,   32-bit,   or   64-bit. The integers supported by such a type can be   signed   or   unsigned. Arithmetic for machine level integers can often be done by single CPU instruct...
#VBScript
VBScript
'Binary Integer overflow - vbs i=(-2147483647-1)/-1 wscript.echo i i0=32767 '=32767 Integer (Fixed) type=2 i1=2147483647 '=2147483647 Long (Fixed) type=3 i2=-(-2147483647-1) '=2147483648 Double (Float) type=5 wscript.echo Cstr(i0) & " : " & typename(i0) & " , " & vartype(i0) & vbcrlf _ ...
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.
#M2000_Interpreter
M2000 Interpreter
  Document A$={1st Line 2nd line 3rd line } Save.Doc A$, "test.txt", 0 ' 0 for utf16-le \\ we use Wide for utf16-le \\ without it we open using ANSI Open "test.txt" For Wide Input Exclusive as #N While Not Eof(#N) { Line Input #N, ThisLine$ Print ThisLine$ } Close...
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.
#Maple
Maple
  readinput:=proc(filename) local line,file; file:=""; line:=readline(filename); while line<>0 do line:=readline(filename); file:=cat(file,line); end do; end proc;  
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.
#MACRO-10
MACRO-10
  TITLE Input Loop   COMMENT ! Input-loop example, PDP-10 assembly language, kjx 2022. Assembler: MACRO-10 Operating system: TOPS-20   This program opens the file "test.txt" and prints it's contents.   Note that the PDP-10 is a word-addressable machine with 36bit words, and text-fil...
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...
#Tcl
Tcl
package require Tcl 8.5 proc wordsInString str { # We define "words" to be "maximal sequences of 'word' characters". # The other possible definition is to use 'non-space' characters. regexp -all -inline {\w+} $str }   # Adds a document to the index. The index is a map from words to a map # from filenames to...
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...
#Scala
Scala
object VersCheck extends App { val minimalVersion = 1.7   val vers = System.getProperty("java.specification.version"); println(if (vers.toDouble >= minimalVersion) "YAY!" else s"Must use Java >= $minimalVersion");   val bloop = Option(-42) if (bloop.isDefined) bloop.get.abs }
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...
#Slate
Slate
Platform run: StartupArguments first ; ' --version'.
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Python
Python
>>> def j(n, k): p, i, seq = list(range(n)), 0, [] while p: i = (i+k-1) % len(p) seq.append(p.pop(i)) return 'Prisoner killing order: %s.\nSurvivor: %i' % (', '.join(str(i) for i in seq[:-1]), seq[-1])   >>> print(j(5, 2)) Prisoner killing order: 1, 3, 0, 4. Survivor: 2 >>> print(j(41, 3)) Prisoner killing order...
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#BCPL
BCPL
get "libhdr"   // Read word from selected input let readword(v) = valof $( let ch = ? v%0 := 0 $( ch := rdch() if ch = endstreamch then resultis false if ch = '*N' then resultis true v%0 := v%0 + 1 v%(v%0) := ch $) repeat $)   // Does s1 contain s2? let contains(s1, s2) = ...
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#C.2B.2B
C++
// standard C++ string stream operators #include <cstdlib> #include <string> #include <sstream>   // inside a function or method... std::string s = "12345";   int i; std::istringstream(s) >> i; i++; //or: //int i = std::atoi(s.c_str()) + 1;   std::ostringstream oss; if (oss << i) s = oss.str();
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Ceylon
Ceylon
shared void run() {   "Increments a numeric string by 1. Returns a float or integer depending on the string. Returns null if the string isn't a number." function inc(String string) => if(exists integer = parseInteger(string)) then integer + 1 else if(exists float = parseFloat(string)) then float + 1.0 el...
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 |...
#Clean
Clean
import StdEnv   compare a b | a < b = "A is less than B" | a > b = "A is more than B" | a == b = "A equals B"   Start world # (console, world) = stdio world (_, a, console) = freadi console (_, b, console) = freadi console = compare a b
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
#GAP
GAP
Read("file");
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
#Gnuplot
Gnuplot
load "filename.gnuplot"
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
#Go
Go
// main.go package main   import "fmt"   func hello() { fmt.Println("Hello from main.go") }   func main() { hello() hello2() }
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...
#Python
Python
class Animal: pass #functions go here...   class Dog(Animal): pass #functions go here...   class Cat(Animal): pass #functions go here...   class Lab(Dog): pass #functions go here...   class Collie(Dog): pass #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...
#R
R
aCollie <- "woof" class(aCollie) <- c("Collie", "Dog", "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...
#Racket
Racket
  #lang racket   (define animal% (class object% (super-new))) (define dog% (class animal% (super-new))) (define cat% (class animal% (super-new))) (define lab% (class dog% (super-new))) (define collie% (class dog% (super-new)))   ;; unit tests (require rackunit)   (check-true (is-a? (new dog%) animal%)) (check-...
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Bracmat
Bracmat
( ( IBAN-check = table country cd len N c . (AL.28) (AD.24) (AT.20) (AZ.28) (BE.16) (BH.22) (BA.20) (BR.29) (BG.22) (CR.21) (HR.21) (CY.28) (CZ.24) (DK.18) (DO.28) (EE.20) (FO.18) (FI.18) (FR.27) (GE.22) (DE.22) (GI.23) (GR.27) (GL.18) (GT.28) (HU.28) (IS.26) (IE.22) (I...
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#D
D
import std.conv; import std.stdio;   bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false; }   void main() { auto limit = sh...
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#ATS
ATS
  (* ****** ****** *) // // How to compile: // // patscc -DATS_MEMALLOC_LIBC -o idmatrix idmatrix.dats // (* ****** ****** *) // #include "share/atspre_staload.hats" // (* ****** ****** *)   extern fun idmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n) implement idmatrix(n) = matrixref_tabulate_cloref<int> (n, n, lam(...
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 ...
#Nim
Nim
import random, strformat, strutils   type Adjacent = array[3, int]   const Cave: array[1..20, Adjacent] = [ 1: [2, 3, 4], 2: [1, 5, 6], 3: [1, 7, 8], 4: [1, 9, 10], 5: [2, 9, 11], 6: [2, 7, 12], 7: [3, 6, 13], 8: [3, 10, 14], 9: [4, 5, 15], 10: [4, 8, 16], 11: [5, 12, 17], 12: ...