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/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Haskell
Haskell
  import Data.Char import Data.List import Data.List.Split   main :: IO () main = readFile "config" >>= (print . parseConfig)   parseConfig :: String -> Config parseConfig = foldr addConfigValue defaultConfig . clean . lines where clean = filter (not . flip any ["#", ";", "", " "] . (==) . take 1)   addConfigValue ...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Rust
Rust
  use itertools::Itertools; use std::collections::HashMap; use std::convert::TryInto; use std::fmt; use std::time::Instant;   #[derive(Debug)] struct RareResults { digits: u8, time_to_find: u128, counter: u32, number: u64, }   impl fmt::Display for RareResults { fn fmt(&self, f: &mut fmt::Formatter)...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Elixir
Elixir
defmodule RC do def expansion(range) do Enum.flat_map(String.split(range, ","), fn part -> case Regex.scan(~r/^(-?\d+)-(-?\d+)$/, part) do [[_,a,b]] -> Enum.to_list(String.to_integer(a) .. String.to_integer(b)) [] -> [String.to_integer(part)] end end) end end   IO.inspect RC.expa...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Erlang
Erlang
  -module( range ).   -export( [expansion/1, task/0] ).   expansion( String ) -> lists:flatten( [expansion_individual(io_lib:fread("~d", X)) || X <- string:tokens(String, ",")] ).   task() -> io:fwrite( "~p~n", [expansion("-6,-3--1,3-5,7-11,14,15,17-20")] ).       expansion_individual( {ok, [N], []} ) -> N;...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#ERRE
ERRE
  PROGRAM LETTURA   EXCEPTION FERROR%=TRUE  ! si e' verificata l'eccezione ! PRINT("Il file richiesto non esiste .....") END EXCEPTION   BEGIN FERROR%=FALSE PRINT("Nome del file";) INPUT(FILE$)  ! chiede il nome del file OPEN("I",1,FILE$) ! apre un file sequenziale in lettura IF ...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Euphoria
Euphoria
constant cmd = command_line() constant filename = cmd[2] constant fn = open(filename,"r") integer i i = 1 object x while 1 do x = gets(fn) if atom(x) then exit end if printf(1,"%2d: %s",{i,x}) i += 1 end while close(fn)
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Python
Python
def mc_rank(iterable, start=1): """Modified competition ranking""" lastresult, fifo = None, [] for n, item in enumerate(iterable, start-1): if item[0] == lastresult: fifo += [item] else: while fifo: yield n, fifo.pop(0) lastresult, fifo = i...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Perl
Perl
use utf8; binmode STDOUT, ":utf8";   # to reverse characters (code points): print reverse('visor'), "\n";   # to reverse graphemes: print join("", reverse "José" =~ /\X/g), "\n";   $string = 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'; print join("", reverse $string =~ /\X/g), "\n";
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Ring
Ring
  nr = 10 for i = 1 to nr see random(i) + nl next  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Ruby
Ruby
require 'securerandom' SecureRandom.random_number(1 << 32)   #or specifying SecureRandom as the desired RNG: p (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Rust
Rust
extern crate rand;   use rand::{OsRng, Rng};   fn main() { // because `OsRng` opens files, it may fail let mut rng = match OsRng::new() { Ok(v) => v, Err(e) => panic!("Failed to obtain OS RNG: {}", e) };   let rand_num: u32 = rng.gen(); println!("{}", rand_num); }
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Phix
Phix
with javascript_semantics string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" function ls(integer n) if n>length(aleph) then ?9/0 end if -- too big... atom t1 = time()+1 sequence tn = tagset(n), -- {1..n} vcs = repeat(tn,n), -- valid for cols res = ...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Rust
Rust
use std::f64;   const _EPS: f64 = 0.00001; const _MIN: f64 = f64::MIN_POSITIVE; const _MAX: f64 = f64::MAX;   #[derive(Clone)] struct Point { x: f64, y: f64, }   #[derive(Clone)] struct Edge { pt1: Point, pt2: Point, }   impl Edge { fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge { Edge { ...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Applesoft_BASIC
Applesoft BASIC
0 DEF FN E(MPTY) = SP = FIRST 10 GOSUB 150EMPTY 20 LET A$ = "A": GOSUB 100PUSH 30 LET A$ = "B": GOSUB 100PUSH 40 GOSUB 150EMPTY 50 GOSUB 120PULL FIRST 60 GOSUB 120PULL FIRST 70 GOSUB 150EMPTY 80 GOSUB 120PULL FIRST 90 END 100 PRINT "PUSH "A$ 110 LET S$(SP) = A$:SP = SP + 1: RETURN 120 GOSUB 1...
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#AutoHotkey
AutoHotkey
q := [1, 2, 3, 4] q1 := [2, 3, 4, 5] q2 := [3, 4, 5, 6] r := 7   MsgBox, % "q = " PrintQ(q) . "`nq1 = " PrintQ(q1) . "`nq2 = " PrintQ(q2) . "`nr = " r . "`nNorm(q) = " Norm(q) . "`nNegative(q) = " PrintQ(Negative(q)) . "`nConjugate(q) = " PrintQ(Conjugate(q)) . "`nq + r = " PrintQ(AddR(q, r)) . "`nq1 + q2 = " ...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#AutoHotkey
AutoHotkey
FileRead, quine, %A_ScriptFullPath% MsgBox % quine
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Clojure
Clojure
(def q (make-queue))   (enqueue q 1) (enqueue q 2) (enqueue q 3)   (dequeue q) ; 1 (dequeue q) ; 2 (dequeue q) ; 3   (queue-empty? q) ; true
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#CoffeeScript
CoffeeScript
  # We build a Queue on top of an ordinary JS array, which supports push # and shift. For simple queues, it might make sense to just use arrays # directly, but this code shows how to encapsulate the array behind a restricted # API. For very large queues, you might want a more specialized data # structure to implement...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#sed
sed
sed -n 7p
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: getLine (inout file: aFile, in var integer: lineNum) is func result var string: line is ""; begin while lineNum > 1 and hasNext(aFile) do readln(aFile); decr(lineNum); end while; line := getln(aFile); end func;   const proc: main is func ...
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
  (defun quickselect (n _list) (let* ((ys (remove-if (lambda (x) (< (car _list) x)) (cdr _list))) (zs (remove-if-not (lambda (x) (< (car _list) x)) (cdr _list))) (l (length ys)) ) (cond ((< n l) (quickselect n ys)) ((> n l) (quickselect (- n l 1) zs)) (t (car _list))...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Python
Python
from __future__ import print_function from shapely.geometry import LineString   if __name__=="__main__": line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)]) print (line.simplify(1.0, preserve_topology=False))
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#DWScript
DWScript
procedure ExtractRanges(const values : array of Integer); begin var i:=0; while i<values.Length do begin if i>0 then Print(','); Print(values[i]); var j:=i+1; while (j<values.Length) and (values[j]=values[j-1]+1) do Inc(j); Dec(j); if j>i then begin i...
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Fortran
Fortran
PROGRAM Random   INTEGER, PARAMETER :: n = 1000 INTEGER :: i REAL :: array(n), pi, temp, mean = 1.0, sd = 0.5   pi = 4.0*ATAN(1.0) CALL RANDOM_NUMBER(array) ! Uniform distribution   ! Now convert to normal distribution DO i = 1, n-1, 2 temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean ...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PARI.2FGP
PARI/GP
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Pascal
Pascal
function Random(l: LongInt) : LongInt; function Random : Real; procedure Randomize;
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Perl
Perl
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Phix
Phix
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) ws := ' \t' vars := table() every line := !&input do { line ? { tab(many(ws)) if any('#;') | pos(0) then next vars[map(tab(upto(ws)\1|0))] := getValue() } } show(vars) end   procedure getValue() ws := ' \t' a := []...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Imports DT = System.DateTime Imports Lsb = System.Collections.Generic.List(Of SByte) Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte)) Imports UI = System.UInt64   Module Module1 Const MxD As SByte = 15   Public Structure term Public coeff...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#F.23
F#
open System.Text.RegularExpressions   // simplify regex matching with an active pattern let (|Regexp|_|) pattern txt = match Regex.Match(txt, pattern) with | m when m.Success -> [for g in m.Groups -> g.Value] |> List.tail |> Some | _ -> None   // Parse and expand a single range description. /...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#F.23
F#
open System.IO   [<EntryPoint>] let main argv = File.ReadLines(argv.[0]) |> Seq.iter (printfn "%s") 0
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Factor
Factor
"path/to/file" utf8 [ [ readln dup [ print ] when* ] loop ] with-file-reader
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Racket
Racket
#lang racket ;; Tim-brown 2014-09-11   ;; produces a ranking according to ranking function: rfn ;; INPUT: ;; lst : (list (score . details)) ;; rfn : (length-scores) ;; -> (values ;; ranks-added  ; how many ranks to add for the next iteration ;; (idx . rest -> rank-off...
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Raku
Raku
my @scores = Solomon => 44, Jason => 42, Errol => 42, Garry => 41, Bernard => 41, Barry => 41, Stephen => 39;   sub tiers (@s) { @s.classify(*.value).pairs.sort.reverse.map: { .value».key } }   sub standard (@s) { my $rank = 1; gather for tiers @s -> @players { take $rank =>...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Pharo
Pharo
'123' reversed
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Scala
Scala
import java.security.SecureRandom   object RandomExample extends App { new SecureRandom { val newSeed: Long = this.nextInt().toLong * this.nextInt() this.setSeed(newSeed) // reseed using the previous 2 random numbers println(this.nextInt()) // get random 32-bit number and print it } }
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Sidef
Sidef
func urandom() { const device = %f'/dev/urandom';   device.open('<:raw', \var fh, \var err) -> || die "Can't open `#{device}': #{err}";   fh.sysread(\var noise, 4); 'L'.unpack(noise); }   say urandom(); # sample: 3517432564
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Standard_ML
Standard ML
fun sysRand32 () = let val strm = BinIO.openIn "/dev/urandom" in PackWord32Big.subVec (BinIO.inputN (strm, 4), 0) before BinIO.closeIn strm end   val () = print (LargeWord.fmt StringCvt.DEC (sysRand32 ()) ^ "\n")
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Picat
Picat
main => _ = random2(), % random seed N = 5, foreach(_ in 1..2) latin_square(N, X), pretty_print(X) end,  % A larger random instance latin_square(62,X), pretty_print(X).   % Latin square latin_square(N, X) => X = new_array(N,N), X :: 1..N, foreach(I in 1..N) all_different([X[I,J] : J in 1....
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Python
Python
from random import choice, shuffle from copy import deepcopy   def rls(n): if n <= 0: return [] else: symbols = list(range(n)) square = _rls(symbols) return _shuffle_transpose_shuffle(square)     def _shuffle_transpose_shuffle(matrix): square = deepcopy(matrix) shuffle(sq...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Scala
Scala
package scala.ray_casting   case class Edge(_1: (Double, Double), _2: (Double, Double)) { import Math._ import Double._   def raySegI(p: (Double, Double)): Boolean = { if (_1._2 > _2._2) return Edge(_2, _1).raySegI(p) if (p._2 == _1._2 || p._2 == _2._2) return raySegI((p._1, p._2 + epsilon)) if (p._2 ...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program defqueue.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBMAXIELEMENTS, 100   /*******************************************/ /* Structures ...
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Axiom
Axiom
qi := quatern$Quaternion(Integer);   Type: ((Integer,Integer,Integer,Integer) -> Quaternion(Integer)) q  := qi(1,2,3,4);   Type: Quaternion(Integer) q1 := qi(2,3,4,5);   Type: Quaternion(Integer) q2 := q...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#AWK
AWK
BEGIN{c="BEGIN{c=%c%s%c;printf(c,34,c,34);}";printf(c,34,c,34);}
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Common_Lisp
Common Lisp
(let ((queue (make-queue))) (enqueue 38 queue) (assert (not (queue-empty-p queue))) (enqueue 23 queue) (assert (eql 38 (dequeue queue))) (assert (eql 23 (dequeue queue))) (assert (queue-empty-p queue)))
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Component_Pascal
Component Pascal
  MODULE UseQueue; IMPORT Queue, Boxes, StdLog;   PROCEDURE Do*; VAR q: Queue.Instance; b: Boxes.Box; BEGIN q := Queue.New(10); q.Push(Boxes.NewInteger(1)); q.Push(Boxes.NewInteger(2)); q.Push(Boxes.NewInteger(3)); b := q.Pop(); b := q.Pop(); q.Push(Boxes.NewInteger(4)); b := q.Pop(); b := q...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#SenseTalk
SenseTalk
put line 7 of file "example.txt" into theLine  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Sidef
Sidef
func getNthLine(filename, n) { var file = File.new(filename); file.open_r.each { |line| Num($.) == n && return line; } warn "file #{file} does not have #{n} lines, only #{$.}\n"; return nil; }   var line = getNthLine("/etc/passwd", 7); print line if defined line;
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Crystal
Crystal
def quickselect(a, k) arr = a.dup # we will be modifying it loop do pivot = arr.delete_at(rand(arr.size)) left, right = arr.partition { |x| x < pivot } if k == left.size return pivot elsif k < left.size arr = left else k = k - left.size - 1 arr = right end end end  ...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Racket
Racket
#lang racket (require math/flonum) ;; points are lists of x y (maybe extensible to z) ;; x+y gets both parts as values (define (x+y p) (values (first p) (second p)))   ;; https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line (define (⊥-distance P1 P2) (let*-values ([(x1 y1) (x+y P1)] [(x2 y2) (x+...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Raku
Raku
sub norm (*@list) { @list»².sum.sqrt }   sub perpendicular-distance (@start, @end where @end !eqv @start, @point) { return 0 if @point eqv any(@start, @end); my ( $Δx, $Δy ) = @end «-» @start; my ($Δpx, $Δpy) = @point «-» @start; ($Δx, $Δy) «/=» norm $Δx, $Δy; norm ($Δpx, $Δpy) «-» ($Δx, $Δy) «*» ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Dyalect
Dyalect
func rangeFormat(a) { if a.Length() == 0 { return "" } var parts = [] var n1 = 0 while true { var n2 = n1 + 1 while n2 < a.Length() && a[n2] == a[n2-1]+1 { n2 += 1 } var s = a[n1].ToString() if n2 == n1+2 { s += "," + a[n2-1] ...
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Free_Pascal
Free Pascal
  function randg(mean,stddev: float): float;  
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793 Randomize   ' Generates normally distributed random numbers with mean 0 and standard deviation 1 Function randomNormal() As Double Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd)) End Function   Dim r(0 To 999) As Double Dim sum As Double = 0.0   ' Generate...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PHP
PHP
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PicoLisp
PicoLisp
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PL.2FI
PL/I
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PL.2FSQL
PL/SQL
DBMS_RANDOM.RANDOM --produces integers in [-2^^31, 2^^31). DBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision. DBMS_RANDOM.NORMAL --produces normal distributed numbers with a mean of 0 and a variance of 1
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PowerShell
PowerShell
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#J
J
require'regex' set=:4 :'(x)=:y'   cfgString=:4 :0 y set '' (1;&,~'(?i:',y,')\s*(.*)') y&set rxapply x )   cfgBoolean=:4 :0 y set 0 (1;&,~'(?i:',y,')\s*(.*)') y&set rxapply x if.-.0-:y do.y set 1 end. )   taskCfg=:3 :0 cfg=: ('[#;].*';'') rxrplc 1!:1<y cfg cfgString 'fullname' cfg cfgString 'favouritefru...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   class Term { construct new(coeff, ix1, ix2) { _coeff = coeff _ix1 = ix1 _ix2 = ix2 } coeff { _coeff } ix1 { _ix1 } ix2 { _ix2 } }   var maxDigits = 15   var toInt = Fn.new { |digits, reverse| var sum = 0 if (!reverse) { ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Factor
Factor
USING: kernel math.parser math.ranges prettyprint regexp sequences sequences.extras splitting ;   : expand ( str -- seq ) "," split [ R/ (?<=\d)-/ re-split [ string>number ] map dup length 2 = [ first2 [a,b] ] when ] map-concat ;   "-6,-3--1,3-5,7-11,14,15,17-20" expand .
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Fantom
Fantom
  class Main { Void main () { File (`data.txt`).eachLine |Str line| { echo ("Line: $line") } } }  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Forth
Forth
4096 constant max-line   : third ( A b c -- A b c A ) >r over r> swap ;   : read-lines ( fileid -- ) begin pad max-line third read-line throw while pad swap ( fileid c-addr u ) \ string excludes the newline 2drop repeat 2drop ;
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#REXX
REXX
/************************** 44 Solomon 1 1 1 1 1 42 Jason 2 3 2 2 2.5 42 Errol 2 3 2 3 2.5 41 Garry 4 6 3 4 5 41 Bernard 4 6 3 5 5 41 Barry 4 6 3 6 5 39 Stephen 7 7 4 7 7 **************************/ Do i=1 To 7 Parse Value sourceline(i+1) With rank.i name.i . /* say rank.i name.i */ End pool=0 cran...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Phix
Phix
?reverse("asdf")
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Tcl
Tcl
package require Tcl 8.5   # Allow override of device name proc systemRandomInteger {{device "/dev/random"}} { set f [open $device "rb"] binary scan [read $f 4] "I" x close $f return $x }
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#UNIX_Shell
UNIX Shell
od -An -N 4 -t u4 /dev/urandom
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Wee_Basic
Wee Basic
let keycode=0 let number=1 print 1 "Press any key to generate a random number from 1 to 10. while keycode=0 let number=number+1 let keycode=key() rem The maximum number is the number in the "if number=" line with 1 taken away. For example, if this number was 11, the maximum number would be 10. * if number=11 let number...
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Raku
Raku
sub latin-square { [[0],] };   sub random ( @ls, :$size = 5 ) {   # Build for 1 ..^ $size -> $i { @ls[$i] = @ls[0].clone; @ls[$_].splice($_, 0, $i) for 0 .. $i; }   # Shuffle @ls = @ls[^$size .pick(*)]; my @cols = ^$size .pick(*); @ls[$_] = @ls[$_][@cols] for ^@ls;   # So...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Smalltalk
Smalltalk
Object subclass: Segment [ |pts| Segment class >> new: points [ |a| a := super new. ^ a init: points ] init: points [ pts := points copy. ^self ] endPoints [ ^pts ] "utility methods" first [ ^ pts at: 1] second [ ^ pts at: 2] leftmostEndPoint [ ^ (self first x > se...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   (*------------------------------------------------------------------*)   vtypedef queue_vt (vt : vt@ype+, n : int) = (* A list that form...
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#BASIC256
BASIC256
  dim q(4) dim q1(4) dim q2(4) q[0] = 1: q[1] = 2: q[2] = 3: q[3] = 4 q1[0] = 2: q1[1] = 3: q1[2] = 4: q1[3] = 5 q2[0] = 3: q2[1] = 4: q2[2] = 5: q2[3] = 6 r = 7   function printq(q) return "("+q[0]+", "+q[1]+", "+q[2]+", "+q[3]+")" end function   function q_equal(q1, q2) return q1[0]=q2[0] and q1[1]=q2[1] and q1[2]=...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Babel
Babel
% bin/babel quine.sp { "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }% % % cat quine.sp { "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] d...
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Cowgol
Cowgol
include "cowgol.coh";   typedef QueueData is uint8; # the queue will contain bytes include "queue.coh"; # from the Queue/Definition task   var queue := MakeQueue();   # enqueue bytes 0 to 20 print("Enqueueing: "); var n: uint8 := 0; while n < 20 loop print_i8(n); print_char(' '); Enqueue(queue, n); n :...
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#D
D
class LinkedQueue(T) { private static struct Node { T data; Node* next; }   private Node* head, tail;   bool empty() { return head is null; }   void push(T item) { if (empty()) head = tail = new Node(item); else { tail.next = new Node(item); ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Smalltalk
Smalltalk
  line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#SPL
SPL
lines = #.readlines("test.txt") #.output("Seventh line of text:") ? #.size(lines,1)<7 #.output("is absent") ! #.output(lines[7]) .
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
void main() { import std.stdio, std.algorithm;   auto a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]; foreach (immutable i; 0 .. a.length) { a.topN(i); write(a[i], " "); } }
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#REXX
REXX
/*REXX program uses the Ramer─Douglas─Peucker (RDP) line simplification algorithm for*/ /*───────────────────────────── reducing the number of points used to define its shape. */ parse arg epsilon pts /*obtain optional arguments from the CL*/ if epsilon='' | epsilon="," then epsilon= 1 ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#E
E
def rex(numbers :List[int]) { var region := 0..!0 for n in numbers { region |= n..n } var ranges := [] for interval in region.getSimpleRegions() { def a := interval.getOptStart() def b := interval.getOptBound() - 1 ranges with= if (b > a + 1) { `$a-$b` ...
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Frink
Frink
a = new array[[1000], {|x| randomGaussian[1, 0.5]}]
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#FutureBasic
FutureBasic
window 1   local fn RandomZeroToOne as double double result cln result = (double)( (rand() % 100000 ) * 0.00001 ); end fn = result   local fn RandomGaussian as double double r = fn RandomZeroToOne end fn = 1 + .5 * ( sqr( -2 * log(r) ) * cos( 2 * pi * r ) )   long i double mean, std, a(1000)   for i = 1 to 1000 ...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PureBasic
PureBasic
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Python
Python
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Java
Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Forth
Forth
: >snumber ( str len -- 'str 'len n ) 0. 2swap over c@ [char] - = if 1 /string >number 2swap drop negate else >number 2swap drop then ;   : expand ( str len -- ) begin dup while >snumber >r dup if over c@ [char] - = if 1 /string >snumber r> over >r do i . loop the...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Fortran
Fortran
  INTEGER ENUFF !A value has to be specified beforehand,. PARAMETER (ENUFF = 2468) !Provide some provenance. CHARACTER*(ENUFF) ALINE !A perfect size? CHARACTER*66 FNAME !What about file name sizes? INTEGER LINPR,IN !I/O unit numbers. INTEGER L,N !A length, and a record counter. ...
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ruby
Ruby
ar = "44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen".lines.map{|line| line.split} grouped = ar.group_by{|pair| pair.shift.to_i} s_rnk = 1 m_rnk = o_rnk = 0 puts "stand.\tmod.\tdense\tord.\tfract."   grouped.each.with_index(1) do |(score, names), d_rnk| m_rnk += names.flatten!.size f_rnk = (s_...
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#PHP
PHP
strrev($string);
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Wren
Wren
import "io" for File   File.open("/dev/urandom") { |file| var b = file.readBytes(4).bytes.toList var n = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24 System.print(n) }
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#X86_Assembly
X86 Assembly
L: rdrand eax jnc L
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#REXX
REXX
/*REXX program generates and displays a randomized Latin square. */ parse arg N seed . /*obtain the optional argument from CL.*/ if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/ if datatype(seed, 'W') then call random ,,seed...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Tcl
Tcl
package require Tcl 8.5   proc point_in_polygon {point polygon} { set count 0 foreach side [sides $polygon] { if {[ray_intersects_line $point $side]} { incr count } } expr {$count % 2} ;#-- 1 = odd = true, 0 = even = false } proc sides polygon { lassign $polygon x0 y0 ...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#AutoHotkey
AutoHotkey
push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST   MsgBox % "Len = " len("qu") ; Number of entries While !empty("qu") ; Repeat until queue is not empty MsgBox % pop("qu") ; Print popped values (2, 44, xyz) MsgBox Error = %ErrorLevel% ; ErrorLevel = 0: OK MsgBox % pop("qu") ; Empty Msg...
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#BBC_BASIC
BBC BASIC
DIM q(3), q1(3), q2(3), t(3) q() = 1, 2, 3, 4 q1() = 2, 3, 4, 5 q2() = 3, 4, 5, 6 r = 7   PRINT "q = " FNq_show(q()) PRINT "q1 = " FNq_show(q1()) PRINT "q2 = " FNq_show(q2()) PRINT "r = "; r PRINT "norm(q) = "; FNq_norm(q()) t() = q() : PROCq_neg(t()) : ...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#bash
bash
#!/bin/bash mapfile < $0 printf "%s" "${MAPFILE[@]}"
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Delphi
Delphi
program QueueUsage;   {$APPTYPE CONSOLE}   uses Generics.Collections;   var lStringQueue: TQueue<string>; begin lStringQueue := TQueue<string>.Create; try lStringQueue.Enqueue('First'); lStringQueue.Enqueue('Second'); lStringQueue.Enqueue('Third');   Writeln(lStringQueue.Dequeue); Writeln(lStr...
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :Q queue !. empty Q enqueue Q "HELLO" enqueue Q 123 enqueue Q "It's a magical place" !. empty Q !. dequeue Q !. dequeue Q !. dequeue Q !. empty Q !. dequeue Q