task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Inheritance/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...
#Nemerle
Nemerle
class Animal { // ... }   class Dog: Animal { // ... }   class Lab: Dog { // ... }   class Collie: Dog { // ... }   class Cat: Animal { // ... }
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...
#11l
11l
F mod97(numberstring) V segstart = 0 V step = 9 V prepended = ‘’ V number = 0 L segstart < numberstring.len - step number = Int(prepended‘’numberstring[segstart .< segstart + step]) V remainder = number % 97 prepended = String(remainder) I remainder < 10 prepended = ‘0’pr...
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...
#11l
11l
F is_humble(i) I i <= 1 R 1B I i % 2 == 0 {R is_humble(i I/ 2)} I i % 3 == 0 {R is_humble(i I/ 3)} I i % 5 == 0 {R is_humble(i I/ 5)} I i % 7 == 0 {R is_humble(i I/ 7)} R 0B   DefaultDict[Int, Int] humble V limit = 7F'FF V count = 0 V num = 1   L count < limit I is_humble(num) humble[St...
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 ⋮ ⋮ ⋮ ⋱ ...
#Action.21
Action!
PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size) CARD pos BYTE i,j   pos=0 FOR i=1 TO size DO FOR j=1 TO size DO IF i=j THEN mat(pos)=1 ELSE mat(pos)=0 FI pos==+1 OD OD RETURN   PROC PrintMatrix(BYTE ARRAY mat,BYTE size) CARD pos BYTE i,j,v   pos...
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 ...
#C.2B.2B
C++
  // 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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringJoin[CharacterRange["a", "z"]] StringJoin[CharacterRange["A", "Z"]]
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...
#MiniScript
MiniScript
toChars = function(seq) for i in seq.indexes seq[i] = char(seq[i]) end for return seq.join("") end function   print toChars(range(code("a"), code("z"))) print toChars(range(code("A"), code("Z")))
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...
#Nim
Nim
import sequtils, strutils   echo "Lowercase characters:" echo toSeq('a'..'z').join() echo "" echo "Uppercase characters:" echo toSeq('A'..'Z').join()
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...
#PARI.2FGP
PARI/GP
apply(Strchr, concat([65..90], [97..122]))
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...
#Java
Java
public class ImaginaryBaseNumber { private static class Complex { private Double real, imag;   public Complex(double r, double i) { this.real = r; this.imag = i; }   public Complex(int r, int i) { this.real = (double) r; this.imag = (do...
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
#Delphi
Delphi
  unit Main;   interface   uses Winapi.Windows, System.SysUtils, Vcl.Forms, Vcl.Graphics, Vcl.Controls, System.Classes, Vcl.ExtCtrls;   type TfmNoise = class(TForm) tmr1sec: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject);...
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...
#Julia
Julia
  using FileIO, Images   img = load("image.jpg")   sharpenkernel = reshape([-1.0, -1.0, -1.0, -1.0, 9.0, -1.0, -1.0, -1.0, -1.0], (3,3))   imfilt = imfilter(img, sharpenkernel)   save("imagesharper.png", imfilt)  
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...
#zkl
zkl
var BN=Import("zklBigNum"); fcn rank(ns) { BN(ns.concat("A"),11) } fcn unrank(bn) { bn.toString(11).split("a").apply("toInt") } fcn unrankS(bn){ bn.toString(11).split("a") }
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...
#Elixir
Elixir
Stream.iterate(1, &(&1+1)) |> Enum.each(&(IO.puts &1))
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Emacs_Lisp
Emacs Lisp
(dotimes (i most-positive-fixnum) (message "%d" (1+ 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...
#J
J
  _ * 5 NB. multiplying infinity to 5 results in infinity _ 5 % _ NB. dividing 5 by infinity results in 0 0 5 % 0 NB. dividing 5 by 0 results in 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...
#Java
Java
double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0 Double.isInfinite(infinity); //true
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...
#Python
Python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> for calc in ''' -(-2147483647-1) 2000000000 + 2000000000 -2147483647 - 2147483647 46341 * 46341 (-2147483647-1) / -1'''.split('\n'): ans = eval(calc) pr...
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...
#Quackery
Quackery
#lang racket (require racket/unsafe/ops)   (fixnum? -1073741824) ;==> #t (fixnum? (- -1073741824)) ;==> #f   (- -1073741824) ;==> 1073741824 (unsafe-fx- 0 -1073741824) ;==> -1073741824   (+ 1000000000 1000000000) ;==> 2000000000 (unsafe-fx+ 1000000000 1000000000) ;==> -147483648   (- -1073741823 1073741823) ;==> -21474...
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.
#J
J
#!/Applications/j602/bin/jconsole NB. read input until EOF ((1!:1) 3)(1!:2) 4 exit ''
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.
#Java
Java
import java.io.InputStream; import java.util.Scanner;   public class InputLoop { public static void main(String args[]) { // To read from stdin: InputStream source = System.in;   /* Or, to read from a file: InputStream source = new FileInputStream(filename);   Or, to ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger   Module Module1 Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += ...
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Python
Python
''' This implements: http://en.wikipedia.org/wiki/Inverted_index of 28/07/10 '''   from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input     def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for ...
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...
#PL.2FI
PL/I
  S = SYSVERSION(); if substr(S, 6, 6) < '050000' then do; put skip list ('Version of compiler is too old'); stop; end;  
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...
#Pop11
Pop11
;;; Exit if version below 15.00 if pop_internal_version < 150000 then sysexit() endif;
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...
#Phix
Phix
function skipping(sequence prisoners, integer step, survivors=1) integer n = length(prisoners), nn = n, p = 0 while n>survivors do integer found = 0 while found<step do p = iff(p=nn?1:p+1) found += prisoners[p]!=-1 end while prisoners[p] = -1 n -= ...
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...
#Scheme
Scheme
> scheme Scheme Microcode Version 14.9 MIT Scheme running under FreeBSD Type `^C' (control-C) followed by `H' to obtain information about interrupts. Scheme saved on Monday June 17, 2002 at 10:03:44 PM Release 7.7.1 Microcode 14.9 Runtime 15.1   1 ]=> (define (f string-1 string-2 separator) (string-append...
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)   ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function CheckISBN13(code As String) As Boolean code = code.Replace("-", "").Replace(" ", "") If code.Length <> 13 Then Return False End If Dim sum = 0 For Each i_d In code.Select(Function(digit, index) (index, digit)) Dim index = i_d....
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...
#ALGOL_68
ALGOL 68
# tests the plausibility of "i before e except after c" using unixdict.txt #   # implements the plausibility test specified by the task # # returns TRUE if with > 2 * without # PROC plausible = ( INT with, without )BOOL: with > 2 * without;   # shows the plausibil...
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#AWK
AWK
$ awk 'BEGIN{s="42"; s++; print s"("length(s)")" }' 43(2)
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#BASIC
BASIC
s$ = "12345" s$ = STR$(VAL(s$) + 1)
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Befunge
Befunge
v v ">" $< >&&"=A",,\:."=B ",,,\: .55+,-:0`| v "<" _v#< @,+55,," B",,,"A " < "=" <
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 |...
#BQN
BQN
Comp ← ⊑·/⟜"Greater than"‿"Equal To"‿"Lesser Than"(>∾=∾<) ⊑(/⟜⟨ "Greater than" "Equal To" "Lesser Than" ⟩>∾=∾<)   4 Comp 5 "Lesser Than" 5 Comp 5 "Equal To" 6 Comp 5 "Greater than"
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#D
D
import std.stdio;
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
#Delphi
Delphi
uses SysUtils; // Lets you use the contents of SysUtils.pas from the current unit   {$Include Common} // Inserts the contents of Common.pas into the current unit {$I Common} // Same as the previous line, but in a shorter form
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   class RInheritSingle public method main(args = String[]) public static animals = [ - RInheritSingle_Animal(), - RInheritSingle_Cat(), - RInheritSingle_Dog(), - RInheritSingle_Lab(), - RInheritSingle_Collie()...
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...
#Nim
Nim
type Animal = object of RootObj Dog = object of Animal Cat = object of Animal Lab = object of Dog Collie = object of Dog
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...
#Ada
Ada
package Iban_Code is function Is_Legal(Iban : String) return Boolean; end Iban_Code;
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...
#Ada
Ada
with Ada.Text_IO;   procedure Show_Humble is   type Positive is range 1 .. 2**63 - 1; First : constant Positive := Positive'First; Last  : constant Positive := 999_999_999;   function Is_Humble (I : in Positive) return Boolean is begin if I <= 1 then return True; elsif I mod 2 = 0 th...
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 ⋮ ⋮ ⋮ ⋱ ...
#Ada
Ada
-- As prototyped in the Generic_Real_Arrays specification: -- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix; -- For the task: mat : Real_Matrix := Unit_Matrix(5);
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 ...
#Common_Lisp
Common Lisp
  ;;; File: HuntTheWumpus.lisp     (setf *random-state* (make-random-state t)) (defvar numRooms 20) (defparameter Cave #2A((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) ...
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 ...
#FORTRAN
FORTRAN
Makefile
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...
#Perl
Perl
for $i (0..2**8-1) { $c = chr $i; $lower .= $c if $c =~ /[[:lower:]]/; $upper .= $c if $c =~ /[[:upper:]]/; }   print "$lower\n"; print "$upper\n";
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...
#Phix
Phix
sequence lc = {}, uc = {} for ch=1 to 255 do if islower(ch) then lc &= ch end if if isupper(ch) then uc &= ch end if end for lc = utf32_to_utf8(lc)&"\n" uc = utf32_to_utf8(uc)&"\n" puts(1,lc) puts(1,uc)
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...
#Python
Python
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle)   for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString cla...
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...
#Julia
Julia
import Base.show, Base.parse, Base.+, Base.-, Base.*, Base./, Base.^   function inbase4(charvec::Vector) if (!all(x -> x in ['-', '0', '1', '2', '3', '.'], charvec)) || ((x = findlast(x -> x == '-', charvec)) != nothing && x > findfirst(x -> x != '-', charvec)) || ((x = findall(x -> x == '.', charve...
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
#Euler_Math_Toolbox
Euler Math Toolbox
  >function noiseimg () ... $aspect(320,240); clg; $count=0; now=time; $repeat $ plotrgb(intrandom(240,420,2)-1,[0,0,1024,1024]); $ wait(0); $ count=count+1; $ until testkey(); $end; $return count/(time-now); $endfunction >noiseimg 2.73544353263  
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
#F.23
F#
open System.Windows.Forms open System.Drawing open System.Drawing.Imaging open System.Runtime.InteropServices open System.Diagnostics open Microsoft.FSharp.NativeInterop #nowarn "9"   let rnd = System.Random()   // Draw pixels using unsafe native pointer accessor. // This updates the bitmap as fast as possible. let dra...
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...
#Kotlin
Kotlin
// version 1.2.10   import kotlin.math.round import java.awt.image.* import java.io.File import javax.imageio.*   class ArrayData(val width: Int, val height: Int) { var dataArray = IntArray(width * height)   operator fun get(x: Int, y: Int) = dataArray[y * width + x]   operator fun set(x: Int, y: Int, 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...
#Erlang
Erlang
F = fun(FF, I) -> io:format("~p~n", [I]), FF(FF, I + 1) end, F(F,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...
#ERRE
ERRE
  ............. A%=0 LOOP A%=A%+1 PRINT(A%;) END LOOP .............  
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...
#JavaScript
JavaScript
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...
#jq
jq
def infinite: 1e1000;
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...
#Julia
Julia
  julia> julia> Inf32 == Inf64 == Inf16 == Inf true  
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#K
K
/ Integer infinities / 0I is just 2147483647 / -0I is just -2147483647 / -2147483648 is a special "null integer"(NaN) 0N 0I*0I 1 0I-0I 0 0I+1 0N 0I+2 -0I 0I+3 / -0I+1 -2147483646 0I-1 2147483646 0I%0I 1 0I^2 4.611686e+18 0I^0I 0i 0I^-0I 0.0 1%0 0I 0%0 0 0i^2 0i 0i^0...
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...
#Racket
Racket
#lang racket (require racket/unsafe/ops)   (fixnum? -1073741824) ;==> #t (fixnum? (- -1073741824)) ;==> #f   (- -1073741824) ;==> 1073741824 (unsafe-fx- 0 -1073741824) ;==> -1073741824   (+ 1000000000 1000000000) ;==> 2000000000 (unsafe-fx+ 1000000000 1000000000) ;==> -147483648   (- -1073741823 1073741823) ;==> -21474...
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...
#Raku
Raku
my int64 ($a, $b, $c) = 9223372036854775807, 5000000000000000000, 3037000500; .say for -(-$a - 1), $b + $b, -$a - $a, $c * $c, (-$a - 1)/-1;
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.
#JavaScript
JavaScript
$ js -e 'while (line = readline()) { do_something_with(line); }' < inputfile
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.
#jq
jq
.
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...
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var isqrt = Fn.new { |x| if (!(x is BigInt && x >= BigInt.zero)) { Fiber.abort("Argument must be a non-negative big integer.") } var q = BigInt.one while (q <= x) q = q * 4 var z = x var r = BigInt.zero while (q > BigInt.one) { ...
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...
#Racket
Racket
  #!/usr/bin/env racket #lang racket (command-line #:args (term . files) (define rindex (make-hasheq)) (for ([file files]) (call-with-input-file file (λ(in) (let loop () (define w (regexp-match #px"\\w+" in)) (when w (let* ([w (bytes->string/utf-8 (car w))] ...
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...
#PowerBASIC
PowerBASIC
#COMPILER PBWIN 9 #COMPILER PBWIN, PBCC 5
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...
#PowerShell
PowerShell
# version is found in $PSVersionTable if ($PSVersionTable['PSVersion'] -lt '2.0') { exit }   if ((Test-Path Variable:bloop) -and ([Math]::Abs)) { [Math]::Abs($bloop) }   # find integer variables and their sum Get-Variable -Scope global ` | Where-Object { $_.Value -is [int] } ` | Measure-Object -Sum Valu...
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...
#PHP
PHP
<?php //Josephus.php function Jotapata($n=41,$k=3,$m=1){$m--; $prisoners=array_fill(0,$n,false);//make a circle of n prisoners, store false ie: dead=false $deadpool=1;//count to next execution $order=0;//death order and *dead* flag, ie. deadpool while((array_sum(array_count_values($prisoners))<$n)){//while sum of 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...
#Sidef
Sidef
$ sidef -i >>> func f(s1, s2, sep) { s1 + sep*2 + s2 }; 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...
#Slate
Slate
slate[1]> s@(String traits) rosettaWith: s2@(String traits) and: s3@(String traits) [s ; s3 ; s3 ; s2]. [rosettaWith:and:] slate[2]> 'Rosetta' rosettaWith: 'Code' and: ':'. '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...
#Smalltalk
Smalltalk
$ gst GNU Smalltalk ready   st> |concat| st> concat := [ :a :b :c | (a,c,c,b) displayNl ]. a BlockClosure st> concat value: 'Rosetta' value: 'Code' value: ':'. Rosetta::Code 'Rosetta::Code' st>
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)   ...
#Vlang
Vlang
fn check_isbn13(isbn13 string) bool { // remove any hyphens or spaces isbn := isbn13.replace('-','').replace(' ','') // check length == 13 le := isbn.len if le != 13 { return false } // check only contains digits and calculate weighted sum mut sum := 0 for i, c in isbn.split('') ...
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)   ...
#Wren
Wren
var isbn13 = Fn.new { |s| var cps = s.codePoints var digits = [] // extract digits for (i in 0...cps.count) { var c = cps[i] if (c >= 48 && c <= 57) digits.add(c) } // do calcs var sum = 0 for (i in 0...digits.count) { var d = digits[i] - 48 sum = sum + ((...
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...
#AppleScript
AppleScript
on ibeeac() script o property wordList : words of (read file ((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as «class utf8»)   -- Subhandler called if thisWord contains either "ie" or "ei". Checks if there's an instance not preceded by "c". on testWithoutC(thisWord, letterP...
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Batch_File
Batch File
set s=12345 set /a s+=1
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Bracmat
Bracmat
get$:?A & get$:?B & (!A:!B&out$"A equals B"|) & (!A:<!B&out$"A is less than B"|) & (!A:>!B&out$"A is greater than 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
#Dragon
Dragon
func my(){ showln "hello" //this is program.dgn }
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
#DWScript
DWScript
  {$INCLUDE Common} // Inserts the contents of Common.pas into the current unit {$I Common} // Same as the previous line, but in a shorter form {$INCLUDE_ONCE Common} // Inserts the contents of Common.pas into the current unit only if not included already {$FILTER Common} // Inserts the contents o...
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...
#Oberon
Oberon
MODULE Animals;   TYPE Animal = RECORD END; Dog = RECORD (Animal) END; Cat = RECORD (Animal) END; Lab = RECORD (Dog) END; Collie = RECORD (Dog) END;   END Animals.  
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...
#Oberon-2
Oberon-2
  MODULE Animals; TYPE Animal = POINTER TO AnimalDesc; AnimalDesc = RECORD END;   Cat = POINTER TO CatDesc; CatDesc = RECORD (AnimalDesc) END;   Dog = POINTER TO DogDesc; DogDesc = RECORD (AnimalDesc) END;   Lab = POINTER TO LabDesc; LabDesc = RECORD (DogDesc) END;   Collie = POINTER TO CollieDesc; ...
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...
#AppleScript
AppleScript
on countryCodes() -- A list of 34 lists. The nth list (1-indexed) contains country codes for countries having n-character IBANS. return {{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {"NO"}, {"BE"}, ¬ {}, {"DK", "FO", "FI", "GL", "NL"}, {"MK", "SI"}, {"AT", "BA", "EE", "KZ", "XK", "LT", "LU"},...
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...
#ALGOL_68
ALGOL 68
BEGIN # find some Humble numbers - numbers with no prime factors above 7 # INT max humble = 2048; INT max shown humble = 49; PROC min = ( INT a, b )INT: IF a < b THEN a ELSE b FI; [ 1 : max humble ]INT h; [ 0 : 6 ]INT h count; FOR i FROM LWB h count TO UPB h count DO h count[ i ] := 0...
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 ⋮ ⋮ ⋮ ⋱ ...
#ALGOL_68
ALGOL 68
#!/usr/bin/a68g --script # # -*- coding: utf-8 -*- #   # Define some generic vector initialisation and printing operations #   COMMENT REQUIRES: MODE SCAL = ~ # a scalar, eg REAL #; FORMAT scal fmt := ~; END COMMENT   INT vec lwb := 1, vec upb := 0; MODE VECNEW = [vec lwb:vec upb]SCAL; MODE VEC = REF VECNEW; FORMAT...
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 ...
#FreeBASIC
FreeBASIC
data 7,13,19,12,18,20,16,17,19,11,14,18,13,15,18,9,14,16,1,15,17,10,16,20,6,11,19,8,12,17 data 4,9,13,2,10,15,1,5,11,4,6,20,5,7,12,3,6,8,3,7,10,2,4,5,1,3,9,2,8,14 data 1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1   randomize timer   dim shared as ubyte i, j, tunnel(1 to 20, 1 to 3), lost(1 to 6, 1 to 3), targ dim as ubyte playe...
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...
#Quackery
Quackery
[ dup upper != ] is islower ( c --> b )   [ dup lower != ] is isupper ( c --> b )   say "Lower case: " 127 times [ i^ islower if [ i^ emit ] ] cr say "Upper case: " 127 times [ i^ isupper if [ i^ emit ] ]
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...
#Racket
Racket
#lang racket (require srfi/14) (printf "System information: ~a~%" (map system-type (list 'os 'word 'machine))) (printf "All lowercase characters: ~a~%" (char-set->string char-set:lower-case)) (newline) (printf "All uppercase characters: ~a~%" (char-set->string char-set:upper-case))
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...
#Prolog
Prolog
chars :- findall(Lower, maplist(char_type(Lower), [alpha, ascii, lower]), Lowers),   writeln('-- Lower Case Characters --'), writeln(Lowers), nl,   findall(Upper, maplist(char_type(Upper), [alpha, ascii, upper]), Uppers), writeln('-- Upper Case Characters --'), writeln(Uppers).
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...
#R
R
LETTERS # [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" letters # [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
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...
#Kotlin
Kotlin
// version 1.2.10   import kotlin.math.ceil   class Complex(val real: Double, val imag: Double) {   constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())   operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)   operator fun times(other: Complex) = Complex( real ...
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
#Factor
Factor
USING: accessors calendar images images.viewer kernel math math.parser models models.arrow random sequences threads timers ui ui.gadgets ui.gadgets.labels ui.gadgets.packs ; IN: rosetta-code.image-noise   : bits>pixels ( bits -- bits' pixels ) [ -1 shift ] [ 1 bitand ] bi 255 * ; inline   : ?generate-more-bits ( a ...
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
#FreeBASIC
FreeBASIC
' version 13-07-2018 ' compile with: fbc -s console ' or: fbc -s gui   ' hit any to key to stop program   Randomize Timer Screen 13   If ScreenPtr = 0 Then Print "Error setting video mode!" End End If   Palette 0, 0 ' black Palette 1, RGB(255, 255, 255) ' white   Dim As UInteger c, x,...
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...
#Liberty_BASIC
Liberty BASIC
  dim result( 300, 300), image( 300, 300), mask( 100, 100) w =128 h =128   nomainwin   WindowWidth = 460 WindowHeight = 210   open "Convolution" for graphics_nsb_nf as #w   #w "trapclose [quit]"   #w "down ; fill darkblue"   hw = hwnd( #w) calldll #user32,"GetDC", hw as ulon...
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...
#Euphoria
Euphoria
integer i i = 0 while 1 do ? i i += 1 end while
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...
#F.23
F#
// lazy sequence of integers starting with i let rec integers i = seq { yield i yield! integers (i+1) }   Seq.iter (printfn "%d") (integers 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...
#Klingphix
Klingphix
1e300 dup mult tostr "inf" equal ["Infinity" print] if   " " input
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...
#Kotlin
Kotlin
fun main(args: Array<String>) { val p = Double.POSITIVE_INFINITY // +∞ println(p.isInfinite()) // true println(p.isFinite()) // false println("${p < 0} ${p > 0}") // false true   val n = Double.NEGATIVE_INFINITY // -∞ println(n.isInfinite()) // true println(n.isFinite()) // false printl...
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...
#REXX
REXX
/*REXX program displays values when integers have an overflow or underflow. */ numeric digits 9 /*the REXX default is 9 decimal digits.*/ call showResult( 999999997 + 1 ) call showResult( 999999998 + 1 ) call showResult( 999999999 + 1 ) call showResult( -999999998 - 2 ...
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.
#Jsish
Jsish
/* Input loop in Jsish */   var line; var cs = 0, ls = 0;   while (line = console.input()) { cs += line.length; ls += 1; }   printf("%d lines, %d characters\n", ls, cs);
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.
#Julia
Julia
stream = IOBuffer("1\n2\n3\n4\n\n6")   while !eof(stream) line = readline(stream) println(line) end
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...
#Yabasic
Yabasic
// Rosetta Code problem: https://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X // by Jjuanhdez, 06/2022   print "Integer square root of first 65 numbers:" for n = 1 to 65 print isqrt(n) using("##"); next n print : print print "Integer square root of odd powers of 7" print " n | 7^n | isq...
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...
#Raku
Raku
sub MAIN (*@files) { my %norm; do for @files -> $file { %norm.push: $file X=> slurp($file).lc.words; } (my %inv).push: %norm.invert.unique;   while prompt("Search terms: ").words -> @words { for @words -> $word { say "$word => {%inv.{$word.lc}//'(not found)'}"; } ...
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...
#PureBasic
PureBasic
CompilerIf #PB_Compiler_Version<441 CompilerError "You failed the version check!" CompilerEndIf   CompilerIf Defined(bloop,#PB_Variable) CompilerIf Defined(Abs(),#PB_Function) Abs(bloop) CompilerEndIf CompilerEndIf
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...
#Python
Python
# Checking for system version import sys major, minor, bugfix = sys.version_info[:3] if major < 2: sys.exit('Python 2 is required')     def defined(name): # LBYL (Look Before You Leap) return name in globals() or name in locals() or name in vars(__builtins__)   def defined2(name): # EAFP (Easier to Ask F...
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...
#PicoLisp
PicoLisp
  #general solution (de jo (N K) (if (=1 N) 1 (inc (% (+ (dec K) (jo (dec N) K)) N ) ) ) )   #special case when K is 2; much faster than general version. (de jo2(N) (let P 1 (while (<= P N) (setq P (* 2 P)) (+ (- (* 2 N) P) 1) ) ) )   # find the...