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_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...
#Stata
Stata
* Read rows 20 to 30 from somedata.dta . use somedata in 20/30, clear   * Read rows for which the variable x is positive . use somedata if x>0, clear
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...
#Tcl
Tcl
proc getNthLineFromFile {filename n} { set f [open $filename] while {[incr n -1] > 0} { if {[gets $f line] < 0} { close $f error "no such line" } } close $f return $line }   puts [getNthLineFromFile example.txt 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 ...
#Delphi
Delphi
  program Quickselect_algorithm;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function quickselect(list: TArray<Integer>; k: Integer): Integer;   procedure Swap(i, j: Integer); var tmp: Integer; begin tmp := list[i]; list[i] := list[j]; list[j] := tmp; end;   begin repeat var px := len...
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...
#Rust
Rust
#[derive(Copy, Clone)] struct Point { x: f64, y: f64, }   use std::fmt;   impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } }   // Returns the distance from point p to the line between p1 and p2 fn perpendicular_dista...
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...
#Sidef
Sidef
func perpendicular_distance(Arr start, Arr end, Arr point) { ((point == start) || (point == end)) && return 0 var (Δx, Δy ) = ( end »-« start)... var (Δpx, Δpy) = (point »-« start)... var h = hypot(Δx, Δy) [\Δx, \Δy].map { *_ /= h } (([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).su...
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...
#EchoLisp
EchoLisp
  (define task '(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 35 36 37 38 39))   ;; 1- GROUPING (define (group-range item acc) (if (or (empty? acc) (!= (caar acc) (1- item))) (cons (cons item item) acc) (begin (set-car! (car acc) item) acc)))   ;; intermediate result ;; ...
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
#Go
Go
package main   import ( "fmt" "math" "math/rand" "strings" "time" )   const mean = 1.0 const stdv = .5 const n = 1000   func main() { var list [n]float64 rand.Seed(time.Now().UnixNano()) for i := range list { list[i] = mean + stdv*rand.NormFloat64() } // show computed mea...
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...
#Quackery
Quackery
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...
#R
R
?RNG help.search("Distribution", package="stats")
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...
#Racket
Racket
import util::Math; arbInt(int limit); // generates an arbitrary integer below limit arbRat(int limit, int limit); // generates an arbitrary rational number between the limits arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0] arbSeed(int seed);
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...
#JavaScript
JavaScript
function parseConfig(config) { // this expression matches a line starting with an all capital word, // and anything after it var regex = /^([A-Z]+)(.*)$/mg; var configObject = {};   // loop until regex.exec returns null var match; while (match = regex.exec(config)) { // values will ...
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...
#Fortran
Fortran
MODULE HOMEONTHERANGE CONTAINS !The key function. CHARACTER*200 FUNCTION ERANGE(TEXT) !Expands integer ranges in a list. Can't return a character value of variable size. CHARACTER*(*) TEXT !The list on input. CHARACTER*200 ALINE !Scratchpad for output. INTEGER N,N1,N2 !Nu...
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Open "input.txt" For Input As #1 Dim line_ As String While Not Eof(1) Line Input #1, line_ '' read each line Print line_ '' echo it to the console Wend Close #1 Print Print "Press any key to quit" Sleep
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 ...
#Scala
Scala
object RankingMethods extends App { case class Score(score: Int, name: String) // incoming data case class Rank[Precision](rank: Precision, names: List[String]) // outgoing results (can be int or double) case class State[Precision](n: Int, done: List[Rank[Precision]]) { // internal state, no mutable variabl...
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 ...
#PicoLisp
PicoLisp
(pack (flip (chop "äöüÄÖÜß")))
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)
#XPL0
XPL0
code Ran=1; int R; R:= Ran($7FFF_FFFF)
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)
#zkl
zkl
const RANDOM_PATH="/dev/urandom";   fin,buf:=File(RANDOM_PATH,"r"), fin.read(4); fin.close(); // GC would also close the file println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0
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...
#Ring
Ring
  load "stdlib.ring" load "guilib.ring"   ###====================================================================================   size = 10   time1 = 0 bwidth = 0 bheight = 0   a2DSquare = newlist(size,size) a2DFinal = newlist(size,size)   aList = 1:size aList2 = RandomList(aList)   GenerateRows(aLis...
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...
#Ruby
Ruby
N = 5   def generate_square perms = (1..N).to_a.permutation(N).to_a.shuffle square = [] N.times do square << perms.pop perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} } end square end   def print_square(square) cell_size = N.digits.size + 1 strings = square.map!{|row| 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...
#Ursala
Ursala
#import flo   in =   @lrzyCipPX ~|afatPRZaq ~&EZ+fleq~~lrPrbr2G&& ~&B+fleq~~lrPrbl2G!| -& ~&Y+ ~~lrPrbl2G fleq, ^E(fleq@lrrPX,@rl fleq\0.)^/~&lr ^(~&r,times)^/minus@llPrll2X vid+ minus~~rbbI&-
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...
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() }   function push(n) { q[length(q)+1] = n return n }   func...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h>   typedef struct quaternion { double q[4]; } quaternion_t;     quaternion_t *quaternion_new(void) { return malloc(sizeof(quaternion_t)); }   quaternion_t *quaternion_new_set(double q1, double q2, double q3, double q4) { 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      ...
#BASIC
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...
#E
E
def [reader, writer] := makeQueue() require(escape empty { reader.dequeue(empty); false } catch _ { true }) writer.enqueue(1) writer.enqueue(2) require(reader.dequeue(throw) == 1) writer.enqueue(3) require(reader.dequeue(throw) == 2) require(reader.dequeue(throw) == 3) require(escape empty { reader.dequeue(empty); fals...
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...
#Elena
Elena
import system'collections; import extensions;   public program() { // Create a queue and "push" items into it var queue := new Queue();   queue.push:1; queue.push:3; queue.push:5;   // "Pop" items from the queue in FIFO order console.printLine(queue.pop()); // 1 console.printLine(queue.p...
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...
#TorqueScript
TorqueScript
 %file = new fileObject();  %file.openForRead("File/Path.txt"); $seventhLine = ""; while(!%file.isEOF()) { %line++; if(%line == 7) { $seventhLine = %file.readLine(); if($seventhLine $= "") { error("Line 7 of the file is blank!"); } } }  %file.close();  %file.delete(); if(%line < 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...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT file="lines.txt" ERROR/STOP OPEN (file,READ,-std-) line2fetch=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 ...
#EasyLang
EasyLang
func qselect k d[] . res . # subr partition mid = left for i = left + 1 to right if d[i] < d[left] mid += 1 swap d[i] d[mid] . . swap d[left] d[mid] . right = len d[] - 1 repeat call partition until mid = k if mid < k left = mid + 1 else ...
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 ...
#Elixir
Elixir
defmodule Quick do def select(k, [x|xs]) do {ys, zs} = Enum.partition(xs, fn e -> e < x end) l = length(ys) cond do k < l -> select(k, ys) k > l -> select(k - l - 1, zs) true -> x end end   def test do v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] Enum.map(0..length(v)-1, fn i -> s...
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...
#Swift
Swift
struct Point: CustomStringConvertible { let x: Double, y: Double   var description: String { return "(\(x), \(y))" } }   // Returns the distance from point p to the line between p1 and p2 func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double { let dx = p2.x - p1.x let dy = p2....
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...
#Wren
Wren
import "/dynamic" for Tuple   var Point = Tuple.create("Point", ["x", "y"])   var rdp // recursive rdp = Fn.new { |l, eps| var x = 0 var dMax = -1 var p1 = l[0] var p2 = l[-1] var x21 = p2.x - p1.x var y21 = p2.y - p1.y var i = 0 for (p in l[1..-1]) { var d = (y21*p.x - x21*p.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...
#Eiffel
Eiffel
  class RANGE   create make   feature make local extended_range: STRING do extended_range := "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, 35, 36, " + "37, 38, 39" print("Extended range: " + extended_ra...
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
#Groovy
Groovy
rnd = new Random() result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }
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
#Haskell
Haskell
import System.Random   pairs :: [a] -> [(a,a)] pairs (x:y:zs) = (x,y):pairs zs pairs _ = []   gauss mu sigma (r1,r2) = mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)   gaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a] gaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g   re...
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...
#Raku
Raku
import util::Math; arbInt(int limit); // generates an arbitrary integer below limit arbRat(int limit, int limit); // generates an arbitrary rational number between the limits arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0] arbSeed(int seed);
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...
#Rascal
Rascal
import util::Math; arbInt(int limit); // generates an arbitrary integer below limit arbRat(int limit, int limit); // generates an arbitrary rational number between the limits arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0] arbSeed(int seed);
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...
#REXX
REXX
/*(below) returns a random integer between 100 & 200, inclusive.*/   y = random(100, 200)
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...
#Ring
Ring
  nr = 10 for i = 1 to nr see random(i) + nl next  
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...
#Ruby
Ruby
rmd(0)
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...
#jq
jq
def parse:   def uc: .name | ascii_upcase;   def parse_boolean: capture( "(?<name>^[^ ] *$)" ) | { (uc) : true };   def parse_var_value: capture( "(?<name>^[^ ]+)[ =] *(?<value>[^,]+ *$)" ) | { (uc) : .value };   def parse_var_array: capture( "(?<name>^[^ ]+)[ =] *(?<value>.*)" ) | { (uc...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub split (s As Const String, sepList As Const String, result() As String) If s = "" OrElse sepList = "" Then Redim result(0) result(0) = s Return End If Dim As Integer i, j, count = 0, empty = 0, length Dim As Integer position(Len(s) + 1) position(0) = 0   For i = 0 To l...
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.
#Frink
Frink
  for line = lines["file:yourfile.txt"] println[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.
#Gambas
Gambas
Public Sub Main() Dim hFile As File Dim sLine As String   hFile = Open "../InputText.txt" For Input   While Not Eof(hFile) Line Input #hFile, sLine Print sLine Wend   End
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 ...
#Sidef
Sidef
var scores = [ Pair(Solomon => 44), Pair(Jason => 42), Pair(Errol => 42), Pair(Garry => 41), Pair(Bernard => 41), Pair(Barry => 41), Pair(Stephen => 39), ]   func tiers(s) { s.group_by { .value }.kv.sort.flip.map { .value.map{.key} } }   func standard(s) { var rank = 1 ga...
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 ...
#Pike
Pike
reverse("foo");
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...
#Wren
Wren
import "random" for Random   var rand = Random.new()   var printSquare = Fn.new { |latin| for (row in latin) System.print(row) System.print() }   var latinSquare = Fn.new { |n| if (n <= 0) { System.print("[]\n") return } var latin = List.filled(n, null) for (i in 0...n) { ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math   Module RayCasting   Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5...
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...
#Batch_File
Batch File
  @echo off setlocal enableDelayedExpansion ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: FIFO queue usage :: Define the queue call :newQueue myQ :: Populate the queue for %%A in (value1 value2 value3) do call :enqueue myQ %%A :: Test if queue is empty by examining the tail "attribute" if...
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...
#C.23
C#
using System;   struct Quaternion : IEquatable<Quaternion> { public readonly double A, B, C, D;   public Quaternion(double a, double b, double c, double d) { this.A = a; this.B = b; this.C = c; this.D = d; }   public double Norm() { return Math.Sqrt(A * A ...
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      ...
#Batch_File
Batch File
@type %0
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...
#Elisa
Elisa
  defmodule Queue do def empty?([]), do: true def empty?(_), do: false   def pop([h|t]), do: {h,t}   def push(q,t), do: q ++ [t]   def front([h|_]), do: h end  
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...
#Elixir
Elixir
  defmodule Queue do def empty?([]), do: true def empty?(_), do: false   def pop([h|t]), do: {h,t}   def push(q,t), do: q ++ [t]   def front([h|_]), do: h end  
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...
#Erlang
Erlang
1> Q = fifo:new(). {fifo,[],[]} 2> fifo:empty(Q). true 3> Q2 = fifo:push(Q,1). {fifo,[1],[]} 4> Q3 = fifo:push(Q2,2). {fifo,[2,1],[]} 5> fifo:empty(Q3). false 6> fifo:pop(Q3). {1,{fifo,[],[2]}} 7> {Popped, Q} = fifo:pop(Q2). {1,{fifo,[],[]}} 8> fifo:pop(fifo:new()). ** exception error: 'empty fifo' in fun...
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...
#TXR
TXR
@(skip nil 7) @line
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...
#UNIX_Shell
UNIX Shell
get_nth_line() { local file=$1 n=$2 line while ((n-- > 0)); do if ! IFS= read -r line; then echo "No such line $2 in $file" return 1 fi done < "$file" echo "$line" }   get_nth_line filename 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 ...
#Erlang
Erlang
  -module(quickselect).   -export([test/0]).     test() -> V = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4], lists:map( fun(I) -> quickselect(I,V) end, lists:seq(0, length(V) - 1) ).   quickselect(K, [X | Xs]) -> {Ys, Zs} = lists:partition(fun(E) -> E < X end, Xs), L = length(Ys), if...
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...
#Yabasic
Yabasic
sub perpendicularDistance(tabla(), i, ini, fin) local dx, cy, mag, pvx, pvy, pvdot, dsx, dsy, ax, ay   dx = tabla(fin, 1) - tabla(ini, 1) dy = tabla(fin, 2) - tabla(ini, 2)   //Normalise mag = (dx^2 + dy^2)^0.5 if mag > 0 dx = dx / mag : dy = dy / mag   pvx = tabla(i, 1) - tabla(ini, 1) ...
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...
#zkl
zkl
fcn perpendicularDistance(start,end, point){ // all are tuples: (x,y) -->|d| dx,dy  := end .zipWith('-,start); // deltas dpx,dpy := point.zipWith('-,start); mag  := (dx*dx + dy*dy).sqrt(); if(mag>0.0){ dx/=mag; dy/=mag; } p,dsx,dsy := dx*dpx + dy*dpy, p*dx, p*dy; ((dpx - dsx).pow(2) + (dpy - dsy...
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...
#Elixir
Elixir
defmodule RC do def range_extract(list) do max = Enum.max(list) + 2 sorted = Enum.sort([max|list]) candidate_number = hd(sorted) current_number = hd(sorted) extract(tl(sorted), candidate_number, current_number, []) end   defp extract([], _, _, range), do: Enum.reverse(range) |> Enum.join(",") ...
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
#HicEst
HicEst
REAL :: n=1000, m=1, s=0.5, array(n)   pi = 4 * ATAN(1) array = s * (-2*LOG(RAN(1)))^0.5 * COS(2*pi*RAN(1)) + m
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
#Icon_and_Unicon
Icon and Unicon
  procedure main() local L L := list(1000) every L[1 to 1000] := 1.0 + 0.5 * sqrt(-2.0 * log(?0)) * cos(2.0 * &pi * ?0)   every write(!L) 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...
#Run_BASIC
Run BASIC
rmd(0)
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...
#Rust
Rust
import scala.util.Random   /** * Histogram of 200 throws with two dices. */ object Throws extends App { Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2) .take(200).groupBy(identity).toList.sortBy(_._1) .foreach { case (a, b) => println(f"$a%2d:" + "X" * b.size) } }
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...
#Scala
Scala
import scala.util.Random   /** * Histogram of 200 throws with two dices. */ object Throws extends App { Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2) .take(200).groupBy(identity).toList.sortBy(_._1) .foreach { case (a, b) => println(f"$a%2d:" + "X" * b.size) } }
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...
#Julia
Julia
function readconf(file) vars = Dict() for line in eachline(file) line = strip(line) if !isempty(line) && !startswith(line, '#') && !startswith(line, ';') fspace = searchindex(line, " ") if fspace == 0 vars[Symbol(lowercase(line))] = true else ...
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...
#Go
Go
package main   import ( "fmt" "strconv" "strings" )   const input = "-6,-3--1,3-5,7-11,14,15,17-20"   func main() { fmt.Println("range:", input) var r []int var last int for _, part := range strings.Split(input, ",") { if i := strings.Index(part[1:], "-"); i == -1 { n, er...
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.
#GAP
GAP
ReadByLines := function(name) local file, line, count; file := InputTextFile(name); count := 0; while true do line := ReadLine(file); if line = fail then break; fi; count := count + 1; od; CloseStream(file); return count; end;   # With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt] Rea...
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.
#Genie
Genie
[indent=4] /* Read file line by line, in Genie   valac readFileLines.gs ./readFileLines [filename] */   init   fileName:string fileName = (args[1] is null) ? "readFileLines.gs" : args[1] var file = FileStream.open(fileName, "r") if file is null stdout.printf("Error: %s did not open\n", ...
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 ...
#Tcl
Tcl
proc rank {rankingMethod sortedList} { # Extract the groups in the data (this is pointless for ordinal...) set s [set group [set groups {}]] foreach {score who} $sortedList { if {$score != $s} { lappend groups [llength $group] set s $score set group {} } lappend group $who } lappen...
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 ...
#PL.2FI
PL/I
s = reverse(s);
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...
#zkl
zkl
fcn randomLatinSquare(n,symbols=[1..]){ //--> list of lists if(n<=0) return(T); square,syms := List(), symbols.walker().walk(n); do(n){ syms=syms.copy(); square.append(syms.append(syms.pop(0))) } // shuffle rows, transpose & shuffle columns T.zip(square.shuffle().xplode()).shuffle(); } fcn rls2String(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...
#Wren
Wren
import "/fmt" for Fmt   class RayCasting { static intersects(a, b, p) { if (a[1] > b[1]) return intersects(b, a, p) if (p[1] == a[1] || p[1] == b[1]) p[1] = p[1] + 0.0001 if (p[1] > b[1] || p[1] < a[1] || p[0] >= a[0].max(b[0])) return false if (p[0] < a[0].min(b[0])) return true ...
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...
#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/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...
#C.2B.2B
C++
#include <iostream> using namespace std;   template<class T = double> class Quaternion { public: T w, x, y, z;   // Numerical constructor Quaternion(const T &w, const T &x, const T &y, const T &z): w(w), x(x), y(y), z(z) {}; Quaternion(const T &x, const T &y, const T &z): w(T()), x(x), y(y), z(z) {}; // For 3-r...
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      ...
#BBC_BASIC
BBC BASIC
PRINT $(PAGE+22)$(PAGE+21):REM PRINT $(PAGE+22)$(PAGE+21):REM
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...
#Factor
Factor
USING: combinators deques dlists kernel prettyprint ; IN: rosetta-code.queue-usage   DL{ } clone {  ! make new queue [ [ 1 ] dip push-front ] ! push 1 [ [ 2 ] dip push-front ] ! push 2 [ [ 3 ] dip push-front ] ! push 3 [ . ] ! DL{ 3 2 1 } [ pop-back drop ] ! p...
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...
#Fantom
Fantom
  class Main { public static Void main () { q := Queue() q.push (1) q.push ("a") echo ("Is empty? " + q.isEmpty) echo ("Element: " + q.pop) echo ("Element: " + q.pop) echo ("Is empty? " + q.isEmpty) try { q.pop } catch (Err e) { echo (e.msg) } } }  
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...
#Ursa
Ursa
decl string<> lines decl file f f.open "filename.txt" set lines (f.readlines) f.close   if (< (size lines) 7) out "the file has less than seven lines" endl console stop end if   out "the seventh line in the file is:" endl endl console out lines<6> endl console
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...
#VBScript
VBScript
  Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." ...
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 ...
#F.23
F#
  let rec quickselect k list = match list with | [] -> failwith "Cannot take largest element of empty list." | [a] -> a | x::xs -> let (ys, zs) = List.partition (fun arg -> arg < x) xs let l = List.length ys if k < l then quickselect k ys elif k > l then quickselect (k-l...
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...
#Emacs_Lisp
Emacs Lisp
(require 'gnus-range)   (defun rangext (lst) (mapconcat (lambda (item) (if (consp item) (if (= (+ 1 (car item)) (cdr item)) (format "%d,%d" (car item) (cdr item)) (format "%d-%d" (car item) (cdr item))) (format "%d" item))) (gnus-compress-sequence lst)...
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
#IDL
IDL
result = 1.0 + 0.5*randomn(seed,1000)
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
#J
J
urand=: ?@$ 0: zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand   1 + 0.5 * zrand 100
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...
#Seed7
Seed7
say 1.rand # random float in the interval [0,1) say 100.irand # random integer in the interval [0,100)
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...
#Sidef
Sidef
say 1.rand # random float in the interval [0,1) say 100.irand # random integer in the interval [0,100)
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...
#Sparkling
Sparkling
rand
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...
#Standard_ML
Standard ML
rand
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...
#Stata
Stata
rand
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...
#Kotlin
Kotlin
import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths   data class Configuration(val map: Map<String, Any?>) { val fullName: String by map val favoriteFruit: String by map val needsPeeling: Boolean by map val otherFamily: List<String> by map }   fun main(args: Ar...
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...
#Groovy
Groovy
def expandRanges = { compressed -> Eval.me('['+compressed.replaceAll(~/(\d)-/, '$1..')+']').flatten().toString()[1..-2] }
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.
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" )   func init() { log.SetFlags(log.Lshortfile) }   func main() { // Open an input file, exit on error. inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) }   // Closes the file when we leave the scope of the cur...
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 ...
#True_BASIC
True BASIC
  LET n = 7 DIM puntos(7), ptosnom(7), nombre$(7)   SUB MostarTabla FOR i = 1 to n PRINT str$(ptosnom(i)); " "; puntos(i); " "; nombre$(i) NEXT i PRINT END SUB   PRINT "Puntuaciones a clasificar (mejores primero):" FOR i = 1 to n READ puntos(i), nombre$(i) PRINT " "; puntos(i); " ";...
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 ...
#Visual_FoxPro
Visual FoxPro
  #DEFINE CTAB CHR(9) #DEFINE CRLF CHR(13) + CHR(10) LOCAL lcTxt As String, i As Integer CLOSE DATABASES ALL SET SAFETY OFF CLEAR CREATE CURSOR scores (score I, name V(8), rownum I AUTOINC) INDEX ON score TAG score COLLATE "Machine" SET ORDER TO 0 INSERT INTO scores (score, name) VALUES (44, "Solomon") INSERT INTO scor...
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 ...
#Plain_English
Plain English
To run: Start up. Put "asdf" into a string. Reverse the string. Shut down.
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...
#zkl
zkl
const E = 0.0001;   fcn rayHitsSeg([(Px,Py)],[(Ax,Ay)],[(Bx,By)]){ // --> Bool if(Py==Ay or Py==By) Py+=E; if(Py<Ay or Py>By or Px>Ax.max(Bx)) False else if(Px<Ax.min(Bx)) True else try{ ( (Py - Ay)/(Px - Ax) )>=( (By - Ay)/(Bx - Ax) ) } //blue>=red catch(MathError){ Px==Ax } // divide ...
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...
#BQN
BQN
queue ← { data ← ⟨⟩ Push ⇐ {data∾˜↩𝕩} Pop ⇐ { 𝕊𝕩: 0=≠data ? •Show "Cannot pop from empty queue"; (data↓˜↩¯1)⊢⊑⌽data } Empty ⇐ {𝕊𝕩: 0=≠data} Display ⇐ {𝕊𝕩: •Show data} }   q1 ← queue   •Show q1.Empty@ q1.Push 3 q1.Push 4 q1.Display@ •Show q1.Pop@ q1.Display@
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...
#CLU
CLU
quat = cluster is make, minus, norm, conj, add, addr, mul, mulr, equal, get_a, get_b, get_c, get_d, q_form rep = struct[a,b,c,d: real]   make = proc (a,b,c,d: real) returns (cvt) return (rep${a:a, b:b, c:c, d:d}) end make   minus = proc (q: cvt) returns (cvt) return (d...
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      ...
#BCPL
BCPL
get "libhdr"   let start() be $( let x = table 13,10,32,32,32,32,108,101,116,32,110,32,61,32,48, 13,10,32,32,32,32,119,114,105,116,101,115,40,34,103, 101,116,32,42,34,108,105,98,104,100,114,42,34,42,78, 42,78,108,101,116,32,115,116,97,114,116,40,41,32,98, 101,42,78,36,40,32,32,108,101,116,32,120,32...
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...
#Forth
Forth
: cqueue: ( n -- <text>) create \ compile time: build the data structure in memory dup dup 1- and abort" queue size must be power of 2" 0 , \ write pointer "HEAD" 0 , ...
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...
#Fortran
Fortran
module fifo_nodes type fifo_node integer :: datum ! the next part is not variable and must be present type(fifo_node), pointer :: next logical :: valid end type fifo_node end module fifo_nodes   program FIFOTest use fifo implicit none   type(fifo_head) :: thehead type(fifo_node), dimensi...