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/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 ...
#Oz
Oz
{System.showInfo {Reverse "!dlroW olleH"}}
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)
#Pascal
Pascal
program RandomNumberDevice; var byteFile: file of byte; randomByte: byte; begin assign(byteFile, '/dev/urandom'); reset (byteFile); read (byteFile, randomByte); close (byteFile); writeln('The random byte is: ', randomByte); end.  
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)
#Perl
Perl
use Crypt::Random::Seed; my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values
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)
#Phix
Phix
integer res -- 1=failure, 0=success atom rint = 0 -- random 32-bit int #ilASM{ mov eax,1 cpuid bt ecx,30 mov edi,1 -- exit code: failure jnc :exit -- rdrand sets CF=0 if no random number -- was available. Intel documentation -- recommends 10 retries...
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...
#Julia
Julia
using Random   shufflerows(mat) = mat[shuffle(1:end), :] shufflecols(mat) = mat[:, shuffle(1:end)]   function addatdiagonal(mat) n = size(mat)[1] + 1 newmat = similar(mat, size(mat) .+ 1) for j in 1:n, i in 1:n newmat[i, j] = (i == n && j < n) ? mat[1, j] : (i == j) ? n - 1 : (i < j) ? m...
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...
#Kotlin
Kotlin
typealias matrix = MutableList<MutableList<Int>>   fun printSquare(latin: matrix) { for (row in latin) { println(row) } println() }   fun latinSquare(n: Int) { if (n <= 0) { println("[]") return }   val latin = MutableList(n) { MutableList(n) { it } } // first row ...
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...
#R
R
point_in_polygon <- function(polygon, p) { count <- 0 for(side in polygon) { if ( ray_intersect_segment(p, side) ) { count <- count + 1 } } if ( count %% 2 == 1 ) "INSIDE" else "OUTSIDE" }   ray_intersect_segment <- function(p, side) { eps <- 0.0001 a <- side$A b <- side$B if ( a...
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...
#Action.21
Action!
DEFINE MAXSIZE="200" BYTE ARRAY queue(MAXSIZE) BYTE queueFront=[0],queueRear=[0]   BYTE FUNC IsEmpty() IF queueFront=queueRear THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE v) BYTE rear   rear=queueRear+1 IF rear=MAXSIZE THEN rear=0 FI IF rear=queueFront THEN PrintE("Error: queue is full!") ...
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...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   DEFINE A_="+0" DEFINE B_="+6" DEFINE C_="+12" DEFINE D_="+18"   TYPE Quaternion=[CARD a1,a2,a3,b1,b2,b3,c1,c2,c3,d1,d2,d3] REAL neg   PROC Init() ValR("-1",neg) RETURN   BYTE FUNC Positive(REAL POINTER x) BYTE ARRAY tmp   tmp=x IF (tmp(0)&$80)=$00 THEN RETURN (1) FI RETURN (0) ...
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      ...
#ALGOL_68
ALGOL 68
STRINGa="STRINGa=,q=REPR34;print(a[:8]+q+a+q+a[9:])",q=REPR34;print(a[:8]+q+a+q+a[9:])
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...
#BBC_BASIC
BBC BASIC
FIFOSIZE = 1000   FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END   DEF PROCenqueue(n) : LOCAL f% 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...
#Bracmat
Bracmat
( queue = (list=) (enqueue=.(.!arg) !(its.list):?(its.list)) ( dequeue = x .  !(its.list):?(its.list) (.?x) & !x ) (empty=.!(its.list):) ) & new$queue:?Q & ( (Q..enqueue)$1 & (Q..enqueue)$2 & (Q..enqueue)$3 & out$((Q..dequeue)$) & (Q..enqueue)...
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...
#REXX
REXX
/*REXX program reads a specific line from a file (and displays the length and content).*/ parse arg FID n . /*obtain optional arguments from the CL*/ if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/ if n=='' | n=="," then n=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 ...
#C.23
C#
// ---------------------------------------------------------------------------------------------- // // Program.cs - QuickSelect // // ----------------------------------------------------------------------------------------------   using System; using System.Collections.Generic; using System.Linq;   namespace Quic...
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...
#Nim
Nim
import math   type Point = tuple[x, y: float64]   proc pointLineDistance(pt, lineStart, lineEnd: Point): float64 = var n, d, dx, dy: float64 dx = lineEnd.x - lineStart.x dy = lineEnd.y - lineStart.y n = abs(dx * (lineStart.y - pt.y) - (lineStart.x - pt.x) * dy) d = sqrt(dx * dx + dy * dy) n / d   proc rdp...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. extract-range-task.   DATA DIVISION. WORKING-STORAGE SECTION. 01 data-str PIC X(200) VALUE "0, 1, 2, 4, 6," & " 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, " & "24, 25, 27, 28, 29, 30, 31, 32, 33...
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
#Euphoria
Euphoria
include misc.e   function RandomNormal() atom x1, x2 x1 = rand(999999) / 1000000 x2 = rand(999999) / 1000000 return sqrt(-2*log(x1)) * cos(2*PI*x2) end function   constant n = 1000 sequence s s = repeat(0,n) for i = 1 to n do s[i] = 1 + 0.5 * RandomNormal() end for
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...
#Julia
Julia
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...
#Kotlin
Kotlin
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
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...
#Gambas
Gambas
Public Sub Form_Open() Dim fullname As String = Settings["fullname", "Foo Barber"] 'If fullname is empty then use the default "Foo Barber" Dim favouritefruit As String = Settings["favouritefruit", "banana"] Dim needspeeling As String = Settings["needspeling", True] Dim seedsremoved As String = Settings["seedsremoved...
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  ...
#REXX
REXX
/*REXX program calculates and displays a specified amount of rare numbers. */ numeric digits 20; w= digits() + digits() % 3 /*use enough dec. digs for calculations*/ parse arg many . /*obtain optional argument from the CL.*/ if many=='' | many=="," then many= 5 ...
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...
#Delphi
Delphi
  program Range_expansion;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const input = '-6,-3--1,3-5,7-11,14,15,17-20';   var r: TArray<Integer>; last, i, n: Integer;   begin for var part in input.Split([',']) do begin i := part.Substring(1).IndexOf('-'); if i = -1 then begin if not TrySt...
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.
#Draco
Draco
\util.g proc nonrec main() void: /* first we need to declare a file buffer and an input channel */ file() infile; channel input text in_ch;   /* a buffer to store the line in is also handy */ [256] char line; word counter; /* to count the lines */   /* open the file, and exit if it fails */...
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 ...
#Perl
Perl
my %scores = ( 'Solomon' => 44, 'Jason' => 42, 'Errol' => 42, 'Garry' => 41, 'Bernard' => 41, 'Barry' => 41, 'Stephen' => 39 );   sub tiers { my(%s) = @_; my(%h); push @{$h{$s{$_}}}, $_ for keys %s; @{\%h}{reverse sort keys %h}; }   sub standard { my(%s) = @_; my($res...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Yabasic
Yabasic
sub sort(tabla()) local items, i, t1, t2, s   items = arraysize(tabla(), 1)   repeat s = true for i = 1 to items-1 if tabla(i, 1) > tabla(i+1, 1) then t1 = tabla(i, 1) : t2 = tabla(i, 2) tabla(i, 1) = tabla(i + 1, 1) : tabla(i, 2) = tabla(i + 1, 2)...
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 ...
#PARI.2FGP
PARI/GP
reverse(s)=concat(Vecrev(s))
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)
#PicoLisp
PicoLisp
: (in "/dev/urandom" (rd 4)) -> 2917110327
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)
#PowerShell
PowerShell
  function Get-RandomInteger { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateScript({$_ -ge 4})] [int[]] $InputObject = 64 )   Begin ...
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...
#M2000_Interpreter
M2000 Interpreter
  Module FastLatinSquare { n=5 For k=1 To 2 latin() Next n=40 latin() Sub latin() Local i,a, a(1 To n), b, k Profiler flush Print "latin square ";n;" by ";n For i=1 To n Push i Next i For i=1 To n div 2 Shiftback random(2, n) Next i a=[] Push ! stack(a) a=array(a) ' change a from st...
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...
#Racket
Racket
  #lang racket   (module pip racket (require racket/contract)   (provide point) (provide seg) (provide (contract-out [point-in-polygon? (-> point? list? boolean?)]))   (str...
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...
#Ada
Ada
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private typ...
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...
#Ada
Ada
generic type Real is digits <>; package Quaternions is type Quaternion is record A, B, C, D : Real; end record; function "abs" (Left : Quaternion) return Real; function Conj (Left : Quaternion) return Quaternion; function "-" (Left : Quaternion) return Quaternion; function "+" (Left, Right : ...
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      ...
#APL
APL
1⌽,⍨9⍴'''1⌽,⍨9⍴''' ⍝ Author: Nikolay Nikolov; Source: https://dfns.dyalog.com/n_quine.htm
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>   #include <sys/queue.h>   /* #include "fifolist.h" */   int main() { int i; FIFOList head;   TAILQ_INIT(&head);   /* insert 20 integer values */ for(i=0; i < 20; i++) { m_enqueue(i, &head); }   /* dequeue and print */ while( m_dequeue(&i, ...
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...
#Ring
Ring
  fp = fopen("C:\Ring\ReadMe.txt","r") n = 0   r = "" while isstring(r) while n < 8 r = fgetc(fp) if r = char(10) n++ see nl else see r ok end end fclose(fp)  
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 ...
#C.2B.2B
C++
#include <algorithm> #include <iostream>   int main() { for (int i = 0; i < 10; i++) { int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); std::cout << a[i]; if (i < 9) std::cout << ", "; } std::cout << std::endl;   return 0; }
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...
#Openscad
Openscad
function slice(a, v) = [ for (i = v) a[i] ];   // Find the distance from the point to the line function perpendicular_distance(pt, start, end) = let ( d = end - start, dn = d / norm(d), dp = pt - start, // Dot-product of two vectors ddot = dn * dp, ds = dn * ddot ...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::MoreUtils qw(firstidx minmax);   my $epsilon = 1;   sub norm { my(@list) = @_; my $sum; $sum += $_**2 for @list; sqrt($sum) }   sub perpendicular_distance { our(@start,@end,@point); local(*start,*end,*point) = (shift, shift, shift); retu...
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...
#Common_Lisp
Common Lisp
(defun format-with-ranges (list) (unless list (return "")) (with-output-to-string (s) (let ((current (first list)) (list (rest list)) (count 1)) (princ current s) (dolist (next list) (if (= next (1+ current)) (incf count) (progn (princ (if (> ...
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
#F.23
F#
  let n = MathNet.Numerics.Distributions.Normal(1.0,0.5) List.init 1000 (fun _->n.Sample())  
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
#Factor
Factor
USING: random ; 1000 [ 1.0 0.5 normal-random-float ] replicate
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...
#Lua
Lua
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
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...
#MATLAB
MATLAB
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...
#Maxima
Maxima
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
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...
#Go
Go
package config   import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" )   var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") )   type varError struct { err error n stri...
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  ...
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl see "the first 5 rare numbers are:" + nl   num = 0   for n = 1 to 2042832002 strn = string(n) nrev = "" for m = len(strn) to 1 step -1 nrev = nrev + strn[m] next nrev = number(nrev) sum = n + nrev diff = n - nrev if diff < 1 loo...
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...
#DWScript
DWScript
  function ExpandRanges(ranges : String) : array of Integer; begin for var range in ranges.Split(',') do begin var separator = range.IndexOf('-', 2); if separator > 0 then begin for var i := range.Left(separator-1).ToInteger to range.Copy(separator+1).ToInteger do Result.Add(i); ...
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.
#Elena
Elena
import system'io; import extensions; import extensions'routines;   public program() { File.assign:"file.txt".forEachLine(printingLn) }
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.
#Elixir
Elixir
  defmodule FileReader do # Create a File.Stream and inspect each line def by_line(path) do File.stream!(path) |> Stream.map(&(IO.inspect(&1))) |> Stream.run end   def bin_line(path) do # Build the stream in binary instead for performance increase case File.open(path) do ...
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 ...
#Phix
Phix
with javascript_semantics function ties(sequence scores) sequence t = {}, -- {start,num} pairs tdx = repeat(0,length(scores)) integer last = -1 for i=1 to length(scores) do integer curr = scores[i][1] if curr=last then t[$][2] += 1 else t = append...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#zkl
zkl
fcn consolidate(rs){ (s:=List()).append( normalize(rs).reduce('wrap(ab,cd){ if(ab[1]>=cd[0]) L(ab[0],ab[1].max(cd[1])); // consolidate else{ s.append(ab); cd } // no overlap }) ) } fcn normalize(s){ s.apply("sort").sort(fcn(a,b){ a[0]<b[0] }) }
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 ...
#Pascal
Pascal
{ the result array must be at least as large as the original array } procedure reverse(s: array[min .. max: integer] of char, var result: array[min1 .. max1: integer] of char); var i, len: integer; begin len := max-min+1; for i := 0 to len-1 do result[min1 + len-1 - i] := s[min + i] end;
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)
#ProDOS
ProDOS
printline -random-
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)
#PureBasic
PureBasic
If OpenCryptRandom() MyRandom = CryptRandom(#MAXLONG) CloseCryptRandom() EndIf
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)
#Python
Python
import random rand = random.SystemRandom() rand.randint(1,10)
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Clear[RandomLatinSquare] RandomLatinSquare[n_] := Module[{out, ord}, out = Table[RotateLeft[Range[n], i], {i, n}]; out = RandomSample[out]; ord = RandomSample[Range[n]]; out = out[[All, ord]]; out ] RandomLatinSquare[5] // Grid
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...
#Nim
Nim
import random, sequtils, strutils   type LatinSquare = seq[seq[char]]   proc get[T](s: set[T]): T = ## Return the first element of a set. for n in s: return n   proc letterAt(n: Natural): char {.inline.} = chr(ord('A') - 1 + n)     proc latinSquare(n: Positive): LatinSquare = result = newSeqWith(n, toSeq(lett...
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...
#Raku
Raku
constant ε = 0.0001;   sub ray-hits-seg([\Px,\Py], [[\Ax,\Ay], [\Bx,\By]] --> Bool) { Py += ε if Py == Ay | By;   if Py < Ay or Py > By or Px > (Ax max Bx) { False; } elsif Px < (Ax min Bx) { True; } else { my \red = Ax == Bx ?? Inf !! (By - Ay) / (Bx - Ax); my \blue = Ax == Px ?? Inf !! (P...
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...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJLINK = STRUCT( REF OBJLINK next, REF OBJLINK prev, OBJVALUE value # ... etc. required # ); PROC obj link new = REF OBJLINK: ~; PROC obj link free = (REF OBJLINK free)VOID: ~ END CO   # actually a pointer to the last LINK, there ITEMs are ADDED/get # MOD...
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...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRES: MODE QUATSCAL = REAL; # Scalar # QUATSCAL quat small scal = small real; END COMMENT   # PROVIDES: # FORMAT quat scal fmt := $g(-0, 4)$; FORMAT signed fmt = $b("+", "")f(quat scal fmt)$;   FORMAT quat fmt = $f(quat scal fmt)"+"f(quat scal fmt)"i+"f(quat scal fmt)"j+"f(qu...
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      ...
#Applesoft_BASIC
Applesoft BASIC
10 LIST
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...
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode { class Program { static void Main() { // Create a queue and "push" items into it Queue<int> queue = new Queue<int>(); queue.Enqueue(1); queue.Enqueue(3); queue.En...
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...
#Ruby
Ruby
seventh_line = open("/etc/passwd").each_line.take(7).last  
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...
#Run_BASIC
Run BASIC
fileName$ = "f:\sample.txt" requiredLine = 7 open fileName$ for input as #f   for i = 1 to requiredLine if not(eof(#f)) then line input #f, a$ next i close #f print a$ end
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 ...
#CLU
CLU
quick = cluster [T: type] is select where T has lt: proctype (T,T) returns (bool) aT = array[T] sT = sequence[T] rep = null   swap = proc (list: aT, a, b: int) temp: T := list[a] list[a] := list[b] list[b] := temp end swap   partition = proc (list: aT, left, right...
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...
#Phix
Phix
with javascript_semantics function rdp(sequence l, atom e) if length(l)<2 then crash("not enough points to simplify") end if integer idx := 0 atom dMax := -1, {p1x,p1y} := l[1], {p2x,p2y} := l[$], x21 := p2x - p1x, y21 := p2y - p1y for i=1 to length(l) do atom {px,py} = l[i], ...
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...
#D
D
import std.stdio, std.conv, std.string, std.algorithm, std.range;   string rangeExtraction(in int[] items) in { assert(items.isSorted); } body { if (items.empty) return null; auto ranges = [[items[0].text]];   foreach (immutable x, immutable y; items.zip(items[1 .. $])) if (x + 1 == y) ...
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
#Falcon
Falcon
a = [] for i in [0:1000] : a+= norm_rand_num()   function norm_rand_num() pi = 2*acos(0) return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2 end
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...
#Modula-3
Modula-3
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...
#Nanoquery
Nanoquery
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...
#Nemerle
Nemerle
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...
#NetRexx
NetRexx
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
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...
#Groovy
Groovy
def config = [:] def loadConfig = { File file -> String regex = /^(;{0,1})\s*(\S+)\s*(.*)$/ file.eachLine { line -> (line =~ regex).each { matcher, invert, key, value -> if (key == '' || key.startsWith("#")) return parts = value ? value.split(/\s*,\s*/) : (invert ? [false] : [tru...
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  ...
#Ruby
Ruby
Term = Struct.new(:coeff, :ix1, :ix2) do end   MAX_DIGITS = 16   def toLong(digits, reverse) sum = 0 if reverse then i = digits.length - 1 while i >=0 sum = sum *10 + digits[i] i = i - 1 end else i = 0 while i < digits.length sum =...
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...
#Dyalect
Dyalect
func main() { let input = "-6,-3--1,3-5,7-11,14,15,17-20" print("range: \(input)") var r = [] var last = 0 for part in input.Split(',') { var i = part[1..].IndexOf('-') if i == -1 { var n = Integer(part) if r.Length() > 0 { return print("dupli...
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...
#EchoLisp
EchoLisp
  ;; parsing [spaces][-]digit(s)-[-]digit(s)[spaces] (define R (make-regexp "^ *(\-?\\d+)\-(\-?\\d+) *$" ))   ;; the native (range a b) is [a ... b[ ;; (range+ a b) is [a ... b] (define (range+ a b) (if (< a b) (range a (1+ b)) (if (> a b) (range a (1- b) -1) (list a))))   ;; in : string : "number" or "number-number...
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.
#Erlang
Erlang
  -module( read_a_file_line_by_line ).   -export( [into_list/1] ).   into_list( File ) -> {ok, IO} = file:open( File, [read] ), into_list( io:get_line(IO, ''), IO, [] ).     into_list( eof, _IO, Acc ) -> lists:reverse( Acc ); into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc ); into_list( Lin...
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 ...
#PowerShell
PowerShell
  function Get-Ranking { [CmdletBinding(DefaultParameterSetName="Standard")] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string] ...
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 ...
#Peloton
Peloton
<# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#>
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)
#Racket
Racket
  #lang racket ;; Assuming a device to provide random bits: (call-with-input-file* "/dev/random" (λ(i) (integer-bytes->integer (read-bytes 4 i) #f)))  
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)
#Raku
Raku
use experimental :pack; my $UR = open("/dev/urandom", :bin) orelse .die; my @random-spigot = $UR.read(1024).unpack("L*") ... *;   .say for @random-spigot[^10];
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)
#REXX
REXX
/*REXX program generates and displays a random 32-bit number using the RANDOM BIF.*/ numeric digits 10 /*ensure REXX has enough decimal digits*/ _=2**16 /*a handy─dandy constant to have around*/ r#= random(0, _-1) * _ + random(0, _-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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'shuffle';   sub random_ls { my($n) = @_; my(@cols,@symbols,@ls_sym);   # build n-sized latin square my @ls = [0,]; for my $i (1..$n-1) { @{$ls[$i]} = @{$ls[0]}; splice(@{$ls[$_]}, $_, 0, $i) for 0..$i; }   # shuffle...
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...
#REXX
REXX
/*REXX program verifies if a horizontal ray from point P intersects a polygon. */ call points 5 5, 5 8, -10 5, 0 5, 10 5, 8 5, 10 10 A= 2.5; B= 7.5 /* ◄───── used for shorter arguments (below).*/ call poly 0 0, 10 0, 10 10, 0 10 ...
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...
#ALGOL_W
ALGOL W
begin  % define a Queue type that will hold StringQueueElements % record StringQueue ( reference(StringQueueElement) front, back );  % define the StringQueueElement type % record StringQueueElement ( string(8) element  ; reference(StringQueueElement) next ...
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...
#ALGOL_W
ALGOL W
begin  % Quaternion record type  % record Quaternion ( real a, b, c, d );    % returns the norm of the specified quaternion  % real procedure normQ ( reference(Quaternion) value q ) ; sqrt( (a(q) * a(q)) + (b(q) * b(q)) + (c(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      ...
#Arturo
Arturo
block: [print ["block:" as .code block "do block"]] do block
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...
#C.2B.2B
C++
#include <queue> #include <cassert> // for run time assertions   int main() { std::queue<int> q; assert( q.empty() ); // initially the queue is empty   q.push(1); // add an element assert( !q.empty() ); // now the queue isn't empty any more assert( q.front() == 1 ); // the firs...
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...
#Rust
Rust
use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::Error; use std::path::Path;   fn main() { let path = Path::new("file.txt"); let line_num = 7usize; let line = get_line_at(&path, line_num - 1); println!("{}", line.unwrap()); }   fn get_line_at(path: &Path, line_num: usize) ->...
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...
#Scala
Scala
val lines = io.Source.fromFile("input.txt").getLines val seventhLine = lines drop(6) next
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 ...
#COBOL
COBOL
CLASS-ID MainProgram.   METHOD-ID Partition STATIC USING T. CONSTRAINTS. CONSTRAIN T IMPLEMENTS type IComparable.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 pivot-val T.   PROCEDURE DIVISION USING VALUE arr AS T OCCURS ANY, left-id...
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...
#PHP
PHP
function perpendicular_distance(array $pt, array $line) { // Calculate the normalized delta x and y of the line. $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; }   // Calculate dot product, projecting ...
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...
#Delphi
Delphi
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
#Fantom
Fantom
  class Main { static const Float PI := 0.0f.acos * 2 // we need to precompute PI   static Float randomNormal () { return (Float.random * PI * 2).cos * (Float.random.log * -2).sqrt }   public static Void main () { mean := 1.0f sd := 0.5f Float[] values := [,] // this is the collection to fi...
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
#Forth
Forth
require random.fs here to seed   -1. 1 rshift 2constant MAX-D \ or s" MAX-D" ENVIRONMENT? drop   : frnd ( -- f ) \ uniform distribution 0..1 rnd rnd dabs d>f MAX-D d>f f/ ;   : frnd-normal ( -- f ) \ centered on 0, std dev 1 frnd pi f* 2e f* fcos frnd fln -2e f* fsqrt f* ;   : ,normals ( n -- ) \ store many, ...
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...
#Nim
Nim
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...
#OCaml
OCaml
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...
#Octave
Octave
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...
#Oz
Oz
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.