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/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... | #Fortran | Fortran | module Q_mod
implicit none
type quaternion
real :: a, b, c, d
end type
public :: norm, neg, conj
public :: operator (+)
public :: operator (*)
private :: q_plus_q, q_plus_r, r_plus_q, &
q_mult_q, q_mult_r, r_mult_q, &
norm_q, neg_q, conj_q
interface norm
modu... |
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 ... | #C1R | C1R | Quine |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Oz | Oz | declare
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
MyQueue = {Queue.new}
in
{MyQueue.isEmpty} = true
{MyQueue.put foo}
{MyQueue.put bar}
{MyQueue.put baz}
{MyQueue.isEmpty} = false
{Show {MyQueue.get}} %% foo
{Show {MyQueue.get}} %% bar
{Show {MyQueue.get}} %% baz |
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... | #Perl | Perl | @queue = (); # we will simulate a queue in a array
push @queue, (1..5); # enqueue numbers from 1 to 5
print shift @queue,"\n"; # dequeue
print "array is empty\n" unless @queue; # is empty ?
print $n while($n = shift @queue); # dequeue all
print "\n";
print "array is empty\n" unless @queue; # is empty ? |
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
... | #OCaml | OCaml | let rec quickselect k = function
[] -> failwith "empty"
| x :: xs -> let ys, zs = List.partition ((>) x) xs in
let l = List.length ys in
if k < l then
quickselect k ys
else if k > l then
quickselect (k-l-1) zs
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
... | #PARI.2FGP | PARI/GP | part(list, left, right, pivotIndex)={
my(pivotValue=list[pivotIndex],storeIndex=left,t);
t=list[pivotIndex];
list[pivotIndex]=list[right];
list[right]=t;
for(i=left,right-1,
if(list[i] <= pivotValue,
t=list[storeIndex];
list[storeIndex]=list[i];
list[i]=t;
storeIndex++
)
);
... |
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... | #Java | Java | public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {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};
int len = arr.length;
int idx = 0, idx2 =... |
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
| #NewLISP | NewLISP | (normal 1 .5 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
| #Nim | Nim | import random, stats, strformat
var rs: RunningStat
randomize()
for _ in 1..5:
for _ in 1..1000: rs.push gauss(1.0, 0.5)
echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}"
|
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... | #Phix | Phix | integer fn = open("RCTEST.INI","r")
sequence lines = get_text(fn,GT_LF_STRIPPED)
close(fn)
constant dini = new_dict()
for i=1 to length(lines) do
string li = trim(lines[i])
if length(li)
and not find(li[1],"#;") then
integer k = find(' ',li)
if k!=0 then
string rest = li[k+1..$]
... |
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... | #MiniScript | MiniScript | pullInt = function(chars)
numstr = chars.pull
while chars and chars[0] != "," and chars[0] != "-"
numstr = numstr + chars.pull
end while
return val(numstr)
end function
expandRange = function(s)
result = []
chars = s.split("")
while chars
num = pullInt(chars)
if not... |
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... | #MUMPS | MUMPS | RANGEXP(X) ;Integer range expansion
NEW Y,I,J,X1,H SET Y=""
FOR I=1:1:$LENGTH(X,",") DO
.S X1=$PIECE(X,",",I) FOR Q:$EXTRACT(X1)'=" " S X1=$EXTRACT(X1,2,$LENGTH(X1)) ;clean up leading spaces
.SET H=$FIND(X1,"-")-1
.IF H=1 SET H=$FIND(X1,"-",(H+1))-1 ;If the first value is negative ignore that "-"
.IF H<0 SET Y=... |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
parse arg inFileName .
if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'
lines = scanFile(inFileName)
loop l_ = 1 to lines[0]
say l_.right(4)':' lines[l_]
end l_
return
-- Read a file and return contents ... |
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.
| #NewLISP | NewLISP |
(set 'in-file (open "filename" "read"))
(while (read-line in-file)
(write-line))
(close in-file) |
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
... | #RapidQ | RapidQ |
print reverse$("This is a test")
|
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... | #EchoLisp | EchoLisp |
;; put info string in permanent storage for later use
(info 'make-Q
"usage: (define q (make-Q)) ; (q '[top | empty? | pop | push value | to-list | from-list list])")
;; make-Q
(define (make-Q)
(let ((q (make-vector 0)))
(lambda (message . args)
(case message
((empty?) (vector-empty? q))
... |
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... | #FreeBASIC | FreeBASIC |
Dim Shared As Integer q(3) = {1, 2, 3, 4}
Dim Shared As Integer q1(3) = {2, 3, 4, 5}
Dim Shared As Integer q2(3) = {3, 4, 5, 6}
Dim Shared As Integer i, r = 7, t(3)
Function q_norm(q() As Integer) As Double
' medida o valor absoluto de un cuaternión
Dim As Double a = 0
For i = 0 To 3
a += q(i)... |
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 ... | #Ceylon | Ceylon | shared void run() {print(let (x = """shared void run() {print(let (x = $) x.replaceFirst("$", "\"\"\"" + x + "\"\"\""));}""") x.replaceFirst("$", "\"\"\"" + x + "\"\"\""));} |
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... | #Phix | Phix | with javascript_semantics
printf(1,"empty:%t\n",empty()) -- true
push_item(5)
printf(1,"empty:%t\n",empty()) -- false
push_item(6)
printf(1,"pop_item:%v\n",pop_item()) -- 5
printf(1,"pop_item:%v\n",pop_item()) -- 6
printf(1,"empty:%t\n",empty()) -- true
|
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #PHP | PHP | <?php
$queue = new SplQueue;
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true
// $queue->dequeue(); // would raise RuntimeException
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
echo $queue->dequeue(), "\n"; // returns 1
echo $q... |
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
... | #Perl | Perl | my @list = qw(9 8 7 6 5 0 1 2 3 4);
print join ' ', map { qselect(\@list, $_) } 1 .. 10 and print "\n";
sub qselect
{
my ($list, $k) = @_;
my $pivot = @$list[int rand @{ $list } - 1];
my @left = grep { $_ < $pivot } @$list;
my @right = grep { $_ > $pivot } @$list;
if ($k <= @left)
{
r... |
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... | #JavaScript | JavaScript | function rangeExtraction(list) {
var len = list.length;
var out = [];
var i, j;
for (i = 0; i < len; i = j + 1) {
// beginning of range or single
out.push(list[i]);
// find end of range
for (var j = i + 1; j < len && list[j] == list[j-1] + 1; j++);
j--;
if (i == j) {
// singl... |
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
| #Objeck | Objeck | bundle Default {
class RandomNumbers {
function : Main(args : String[]) ~ Nil {
rands := Float->New[1000];
for(i := 0; i < rands->Size(); i += 1;) {
rands[i] := 1.0 + 0.5 * RandomNormal();
};
each(i : rands) {
rands[i]->PrintLine();
};
}
function : native ... |
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... | #Phixmonti | Phixmonti | def optionValue
2 get "," find
if
" " "-" subst "," " " subst split
len for
var i
i get "-" " " subst
rot 1 get "(" chain print i print ") = " print swap trim print nl swap
endfor
drop drop
else
swap 1 get print " = " print swap pr... |
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... | #NetRexx | NetRexx | /*NetRexx program to expand a range of integers into a list. *************
* 09.08.2012 Walter Pachl derived from my Rexx version
* Changes: translate(old,' ',',') -> old.translate(' ',',')
* dashpos=pos('-',x,2) -> dashpos=x.pos('-',2)
* Do -> Loop
* Parse Var a x a ... |
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.
| #Nim | Nim | for line in lines "input.txt":
echo line |
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
... | #Rascal | Rascal | import String;
reverse("string") |
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... | #Elena | Elena | import extensions;
template queue<T>
{
T[] theArray;
int theTop;
int theTale;
constructor()
{
theArray := new T[](8);
theTop := 0;
theTale := 0;
}
bool empty()
= theTop == theTale;
push(T object)
{
if (theTale > theArray.Length)
... |
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... | #GAP | GAP | # GAP has built-in support for quaternions
A := QuaternionAlgebra(Rationals);
# <algebra-with-one of dimension 4 over Rationals>
b := BasisVectors(Basis(A));
# [ e, i, j, k ]
q := [1, 2, 3, 4]*b;
# e+(2)*i+(3)*j+(4)*k
# Conjugate
ComplexConjugate(q);
# e+(-2)*i+(-3)*j+(-4)*k
# Division
1/q;
# (1/30)*e+(-1/15)... |
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 ... | #Clojure | Clojure | ((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x))))) |
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... | #PicoLisp | PicoLisp | (println (fifo 'Queue)) # Retrieve the number '1'
(println (fifo 'Queue)) # Retrieve an internal symbol 'abc'
(println (fifo 'Queue)) # Retrieve a transient symbol "abc"
(println (fifo 'Queue)) # and a list (abc)
(println (fifo 'Queue)) # Queue is empty -> NIL |
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... | #PL.2FI | PL/I |
test: proc options (main);
/* To implement a queue. */
define structure
1 node,
2 value fixed,
2 link handle(node);
declare (head, tail, t) handle (node);
declare null builtin;
declare i fixed binary;
head, tail = bind(:node, null:);
do i = 1 to 10; /* Add ten item... |
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... | #PostScript | PostScript |
[1 2 3 4 5] 6 exch tadd
= [1 2 3 4 5 6]
uncons
= 1 [2 3 4 5 6]
[] empty?
=true
|
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
... | #Phix | Phix | sequence s = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
function quick_select(integer k)
integer left = 1, right = length(s)
while left<right do
object pivotv = s[k];
{s[k], s[right]} = {s[right], s[k]}
integer pos = left
for i=left to right do
if s[i]<pivotv then
... |
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... | #jq | jq | # Input should be an array
def extract:
reduce .[] as $i
# state is an array with integers or [start, end] ranges
([];
if length == 0 then [ $i ]
else ( .[-1]) as $last
| if ($last|type) == "array" then
if ($last[1] + 1) == $i then setpath([-1,1]; $i)
el... |
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
| #OCaml | OCaml | let pi = 4. *. atan 1.;;
let random_gaussian () =
1. +. sqrt (-2. *. log (Random.float 1.)) *. cos (2. *. pi *. Random.float 1.);;
let a = Array.init 1000 (fun _ -> random_gaussian ());; |
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... | #PHP | PHP | <?php
$conf = file_get_contents('parse-conf-file.txt');
// Add an "=" after entry name
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
// Replace multiple parameters separated by commas :
// name = value1, value2
// by multiple lines :
// name[] = value1
// name[] = value2
$conf = preg_replace_callbac... |
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... | #Nim | Nim | import parseutils, strutils
proc expandRange(input: string): string =
var output: seq[string]
for range in input.split(','):
var sep = range.find('-', 1)
if sep > 0: # parse range
var first = -1
if range.substr(0, sep-1).parseInt(first) == 0:
break
var last = -1
if range.su... |
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... | #Oberon-2 | Oberon-2 |
MODULE LIVector;
IMPORT SYSTEM;
TYPE
LIPool = POINTER TO ARRAY OF LONGINT;
LIVector*= POINTER TO LIVectorDesc;
LIVectorDesc = RECORD
cap-: INTEGER;
len-: INTEGER;
LIPool: LIPool;
END;
PROCEDURE (v: LIVector) Init*(cap: INTEGER);
BEGIN
v.cap := cap;
v.len := 0;
NEW(v.LIPool,cap);
END Init;
PROC... |
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.
| #Objeck | Objeck |
bundle Default {
class ReadFile {
function : Main(args : String[]) ~ Nil {
f := IO.FileReader->New("in.txt");
if(f->IsOpen()) {
string := f->ReadString();
while(f->IsEOF() = false) {
string->PrintLine();
string := f->ReadString();
};
f->Close();
... |
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
... | #Raven | Raven | "asdf" reverse |
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... | #Elisa | Elisa |
component GenericQueue ( Queue, Element );
type Queue;
Queue (MaxLength = integer) -> Queue;
Length( Queue ) -> integer;
Empty ( Queue ) -> boolean;
Full ( Queue ) -> boolean;
Push ( Queue, Element) -> nothing;
Pull ( Queue ) -> Element... |
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... | #Elixir | Elixir | defmodule Queue do
def new, do: {Queue, [], []}
def push({Queue, input, output}, x), do: {Queue, [x|input], output}
def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue")
def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)})
def pop({Queue, input, [h|t]}), do: {h, {Que... |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
type qtn struct {
r, i, j, k float64
}
var (
q = &qtn{1, 2, 3, 4}
q1 = &qtn{2, 3, 4, 5}
q2 = &qtn{3, 4, 5, 6}
r float64 = 7
)
func main() {
fmt.Println("Inputs")
fmt.Println("q:", q)
fmt.Println("q1:", q1)
fmt.Println("q2:", q2... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #CLU | CLU | q="start_up=proc()\n"||
" po:stream:=stream$primary_output()\n"||
" stream$puts(po,\"q=\\\"\")\n"||
" for c:char in string$chars(q) do\n"||
" if c='\\n' then stream$puts(po,\"\\\\n\\\"||\\n\\\"\")\n"||
" elseif c='\\\\' then stream$puts(po,\"\\\\\\\\\")\n"||
" elseif c='\\\"' then stream$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... | #PowerShell | PowerShell |
[System.Collections.ArrayList]$queue = @()
# isEmpty?
if ($queue.Count -eq 0) {
"isEmpty? result : the queue is empty"
} else {
"isEmpty? result : the queue is not empty"
}
"the queue contains : $queue"
$queue += 1 # push
"push result : $queue"
$queue += 2 # push
$queue +... |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Prolog | Prolog | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% definitions of queue
empty(U-V) :-
unify_with_occurs_check(U, V).
push(Queue, Value, NewQueue) :-
append_dl(Queue, [Value|X]-X, NewQueue).
pop([X|V]-U, X, V-U) :-
\+empty([X|V]-U).
append_dl(X-Y, Y-Z, X-Z).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%... |
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
... | #Picat | Picat | main =>
L = [9,8,7,6,5,0,1,2,3,4],
Len = L.len,
println([select(L,1,Len,I) : I in 1..Len]),
nl.
select(List, Left, Right, K) = Select =>
if Left = Right then
Select = List[Left]
else
PivotIndex = partition(List, Left, Right, random(Left,Right)),
if K == PivotIndex then
Select = List[K]... |
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
... | #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(de swapL (Lst X Y)
(let L (nth Lst Y)
(swap
L
(swap (nth Lst X) (car L)) ) ) )
(de partition (Lst L R P)
(let V (get Lst P)
(swapL Lst R P)
(for I (range L R)
(and
(> V (get Lst I))
(swapL Lst 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... | #Jsish | Jsish | /* Range Extraction, in Jsish */
function rangeExtraction(list) {
var len = list.length;
var out = [];
var i, j;
for (i = 0; i < len; i = j + 1) {
// beginning of range or single
out.push(list[i]);
// find end of range
for (j = i + 1; j < len && list[j] == list[j-1] + 1; j++);
j--;
... |
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
| #Octave | Octave | p = normrnd(1.0, 0.5, 1000, 1);
disp(mean(p));
disp(sqrt(sum((p - mean(p)).^2)/numel(p))); |
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
| #ooRexx | ooRexx | /*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/
pi=RxCalcPi() /* get value of pi */
Parse Arg n seed . /* allow specification of N & seed*/
If n==''|n==',' Then
n=1000 /* N is the size of the array. */
I... |
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... | #Picat | Picat | go =>
Vars = ["fullname","favouritefruit","needspeeling","seedsremoved","otherfamily"],
Config = read_config("read_a_configuration_file_config.cfg"),
foreach(Key in Vars)
printf("%w = %w\n", Key, Config.get(Key,false))
end,
nl.
% Read configuration file
read_config(File) = Config =>
Config = new_map()... |
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... | #OCaml | OCaml | #load "str.cma"
let range a b =
if b < a then invalid_arg "range";
let rec aux i acc =
if i = b then List.rev (i::acc)
else aux (succ i) (i::acc)
in
aux a []
let parse_piece s =
try Scanf.sscanf s "%d-%d" (fun a b -> range a b)
with _ -> [int_of_string s]
let range_expand rng =
let ps = Str.... |
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.
| #Objective-C | Objective-C | NSString *path = [NSString stringWithString:@"/usr/share/dict/words"];
NSError *error = nil;
NSString *words = [[NSString alloc] initWithContentsOfFile:path
encoding:NSUTF8StringEncoding error:&error];
|
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
... | #REBOL | REBOL | print reverse "asdf" |
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... | #Erlang | Erlang | -module(fifo).
-export([new/0, push/2, pop/1, empty/1]).
new() -> {fifo, [], []}.
push({fifo, In, Out}, X) -> {fifo, [X|In], Out}.
pop({fifo, [], []}) -> erlang:error('empty fifo');
pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)});
pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}.
empty({fifo, [], []}) -> ... |
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... | #Haskell | Haskell | import Control.Monad (join)
data Quaternion a =
Q a a a a
deriving (Show, Eq)
realQ :: Quaternion a -> a
realQ (Q r _ _ _) = r
imagQ :: Quaternion a -> [a]
imagQ (Q _ i j k) = [i, j, k]
quaternionFromScalar :: (Num a) => a -> Quaternion a
quaternionFromScalar s = Q s 0 0 0
listFromQ :: Quaternion 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 ... | #COBOL | COBOL | cobc -x -free -frelax quine.cob
|
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... | #PureBasic | PureBasic | NewList MyStack()
Procedure Push(n)
Shared MyStack()
LastElement(MyStack())
AddElement(MyStack())
MyStack()=n
EndProcedure
Procedure Pop()
Shared MyStack()
Protected n
If FirstElement(MyStack()) ; e.g. Stack not empty
n=MyStack()
DeleteElement(MyStack(),1)
EndIf
ProcedureReturn n
EndProce... |
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... | #Python | Python | import Queue
my_queue = Queue.Queue()
my_queue.put("foo")
my_queue.put("bar")
my_queue.put("baz")
print my_queue.get() # foo
print my_queue.get() # bar
print my_queue.get() # baz |
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
... | #PL.2FI | PL/I |
quick: procedure options (main); /* 4 April 2014 */
partition: procedure (list, left, right, pivot_Index) returns (fixed binary);
declare list (*) fixed binary;
declare (left, right, pivot_index) fixed binary;
declare (store_index, pivot_value) fixed binary;
declare I fixed binary;
pivot_Value = ... |
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
... | #PowerShell | PowerShell |
function partition($list, $left, $right, $pivotIndex) {
$pivotValue = $list[$pivotIndex]
$list[$pivotIndex], $list[$right] = $list[$right], $list[$pivotIndex]
$storeIndex = $left
foreach ($i in $left..($right-1)) {
if ($list[$i] -lt $pivotValue) {
$list[$storeIndex],$list... |
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... | #Julia | Julia |
function sprintfrange{T<:Integer}(a::Array{T,1})
len = length(a)
0 < len || return ""
dropme = falses(len)
dropme[2:end-1] = Bool[a[i-1]==a[i]-1 && a[i+1]==a[i]+1 for i in 2:(len-1)]
s = [string(i) for i in a]
s[dropme] = "X"
s = join(s, ",")
replace(s, r",[,X]+,", "-")
end
testa = [... |
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
| #PARI.2FGP | PARI/GP | rnormal()={
my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296)),u1=random(2^pr)*1.>>pr,u2=random(2^pr)*1.>>pr);
sqrt(-2*log(u1))*cos(2*Pi*u2) \\ in previous version "u1" instead of "u2" was used --> has given crap distribution
\\ Could easily be extended with a second normal at very little cost.
};
vector... |
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
| #Pascal | Pascal |
function rnorm (mean, sd: real): real;
{Calculates Gaussian random numbers according to the Box-Müller approach}
var
u1, u2: real;
begin
u1 := random;
u2 := random;
rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd);
/* error !?! Shouldn't it be "mean +" instead of "mean *" ? */
end... |
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... | #PicoLisp | PicoLisp | (de rdConf (File)
(in File
(while (read)
(set @ (or (pack (clip (line))) T)) ) ) )
(rdConf "conf.txt")
(println FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY)
(bye) |
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... | #Oforth | Oforth | : addRange( s res -- )
| i n |
s asInteger dup ifNotNull: [ res add return ] drop
s indexOfFrom('-', 2) ->i
s left( i 1- ) asInteger s right( s size i - ) asInteger
for: n [ n res add ]
;
: rangeExpand ( s -- [ n ] )
ArrayBuffer new s wordsWith( ',' ) apply( #[ over addRange ] ) ; |
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... | #ooRexx | ooRexx |
list = '-6,-3--1,3-5,7-11,14,15,17-20'
expanded = expandRanges(list)
say "Original list: ["list"]"
say "Expanded list: ["expanded~tostring("l", ",")"]"
-- expand a string expression a range of numbers into a list
-- of values for the range. This returns an array
::routine expandRanges
use strict arg list
val... |
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.
| #OCaml | OCaml | let () =
let ic = open_in "input.txt" in
try
while true do
let line = input_line ic in
print_endline line
done
with End_of_file ->
close_in ic |
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.
| #Oforth | Oforth | : readFile(fileName)
| line | File new(fileName) forEach: line [ line println ] ; |
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
... | #Red | Red | >> reverse "asdf"
== "fdsa" |
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... | #ERRE | ERRE | PROGRAM CLASS_DEMO
CLASS QUEUE
LOCAL SP
LOCAL DIM STACK[100]
FUNCTION ISEMPTY()
ISEMPTY=(SP=0)
END FUNCTION
PROCEDURE INIT
SP=0
END PROCEDURE
PROCEDURE POP(->XX)
XX=STACK[SP]
SP=SP-1
END PROCEDURE
PROCEDURE PUSH(XX)
SP=SP+1
STACK[SP]=XX
END 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... | #Factor | Factor | USING: accessors kernel ;
IN: rosetta-code.queue-definition
TUPLE: queue head tail ;
TUPLE: node value next ;
: <queue> ( -- queue ) queue new ;
: <node> ( obj -- node ) node new swap >>value ;
: empty? ( queue -- ? ) head>> >boolean not ;
: enqueue ( obj queue -- )
[ <node> ] dip 2dup dup empty?
[ head... |
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... | #Icon_and_Unicon | Icon and Unicon |
class Quaternion(a, b, c, d)
method norm ()
return sqrt (a*a + b*b + c*c + d*d)
end
method negative ()
return Quaternion(-a, -b, -c, -d)
end
method conjugate ()
return Quaternion(a, -b, -c, -d)
end
method add (n)
if type(n) == "Quaternion__state"
then return Quaternion(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 ... | #CoffeeScript | CoffeeScript | s="s=#&# ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '#';;" ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '"';; |
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... | #Quackery | Quackery | [ [] ] is queue ( --> q )
[ nested join ] is push ( q x --> q )
[ behead ] is pop ( q --> q x )
[ [] = ] is empty? ( q --> b ) |
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... | #Racket | Racket | #lang racket
(require data/queue)
(define queue (make-queue))
(enqueue! queue 'black)
(queue-empty? queue) ; #f
(enqueue! queue 'red)
(enqueue! queue 'green)
(dequeue! queue) ; 'black
(dequeue! queue) ; 'red
(dequeue! queue) ; 'green
(queue-empty? queue) ; #t |
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
... | #PureBasic | PureBasic |
Procedure QuickPartition (Array L(1), left, right, pivotIndex)
pivotValue = L(pivotIndex)
Swap L(pivotIndex) , L(right); Move pivot To End
storeIndex = left
For i=left To right-1
If L(i) < pivotValue
Swap L(storeIndex),L(i)
storeIndex+1
EndIf
Next 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... | #K | K | grp : {(&~1=0,-':x)_ x}
fmt : {:[1=#s:$x;s;(*s),:[3>#s;",";"-"],*|s]}
erng: {{x,",",y}/,//'fmt'grp x} |
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
| #Perl | Perl | my $PI = 2 * atan2 1, 0;
my @nums = map {
1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand)
} 1..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
| #Phix | Phix | function RandomNormal()
return sqrt(-2*log(rnd())) * cos(2*PI*rnd())
end function
sequence s = repeat(0,1000)
for i=1 to length(s) do
s[i] = 1 + 0.5 * RandomNormal()
end for
|
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... | #PL.2FI | PL/I |
set: procedure options (main);
declare text character (100) varying;
declare (fullname, favouritefruit) character (100) varying initial ('');
declare needspeeling bit (1) static initial ('0'b);
declare seedsremoved bit (1) static initial ('0'b);
declare otherfamily(10) character (100) varying;
decla... |
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... | #Oz | Oz | declare
fun {Expand RangeDesc}
{Flatten
{Map {ParseDesc RangeDesc}
ExpandRange}}
end
fun {ParseDesc Txt}
{Map {String.tokens Txt &,} ParseRange}
end
fun {ParseRange R}
if {Member &- R.2} then
First Second
in
{String.token R.2 &- ?First ?Second}
{Str... |
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.
| #PARI.2FGP | PARI/GP | FILE *f = fopen(name, "r");
if (!f) {
pari_err(openfiler, "input", name);
}
while(fgets(line, MAX_LINELEN, f) != NULL) {
// ...
} |
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.
| #Pascal | Pascal | (* Read a text-file line by line *)
program ReadFileByLine;
var
InputFile,OutputFile: text;
TextLine: String;
begin
Assign(InputFile, 'testin.txt');
Reset(InputFile);
Assign(OutputFile, 'testout.txt');
Rewrite(OutputFile);
while not Eof(InputFile) do
begin
... |
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
... | #ReScript | ReScript | let rev_string = (s) => {
let len = Js.String2.length(s)
let arr = []
for i in 0 to (len-1) {
let c = Js.String2.get(s, len - 1 - i)
let _ = Js.Array2.push(arr, c)
}
Js.String2.concatMany("", arr)
}
Js.log(rev_string("abcdefg")) |
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... | #Fantom | Fantom |
class Queue
{
List queue := [,]
public Void push (Obj obj)
{
queue.add (obj) // add to right of list
}
public Obj pop ()
{
if (queue.isEmpty)
throw (Err("queue is empty"))
else
{
return queue.removeAt(0) // removes left-most item
}
}
public Bool isEmpty ()
{
... |
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... | #Forth | Forth | 1024 constant size
create buffer size cells allot
here constant end
variable head buffer head !
variable tail buffer tail !
variable used 0 used !
: empty? used @ 0= ;
: full? used @ size = ;
: next ( ptr -- ptr )
cell+ dup end = if drop buffer then ;
: put ( n -- )
full? abort" buffer full"
\ b... |
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... | #Idris | Idris |
module CayleyDickson
data CD : Nat -> Type -> Type where
CDBase : a -> CD 0 a
CDProd : CD n a -> CD n a -> CD (S n) a
pairTy : Nat -> Type -> Type
pairTy Z a = a
pairTy (S n) a = let b = pairTy n a in (b, b)
fromPair : (n : Nat) -> pairTy n a -> CD n a
fromPair Z x = CDBase x
fromPair (S m) (x, y) = CDP... |
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 ... | #Commodore_BASIC | Commodore BASIC | 10 DATA 49,54,48,32,78,61,51,51,48,13,49,55,48,32,68,73,77,32,65,40,78,41,13
20 DATA 49,56,48,32,70,79,82,32,73,61,48,32,84,79,32,78,13,49,57,48,32,58,32
30 DATA 82,69,65,68,32,65,40,73,41,13,50,48,48,32,78,69,88,84,32,73,13,50,49
40 DATA 48,32,70,79,82,32,73,61,48,32,84,79,32,49,52,32,13,50,50,48,32,58,32
50 DATA 80,8... |
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 ... | #Common_Lisp | Common Lisp | ((lambda (s) (print (list s (list 'quote s))))
'(lambda (s) (print (list s (list 'quote s))))) |
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... | #Raku | Raku | push (aka enqueue) -- @list.push
pop (aka dequeue) -- @list.shift
empty -- !@list.elems |
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... | #REBOL | REBOL | ; Create and populate a FIFO:
q: make fifo []
q/push 'a
q/push 2
q/push USD$12.34 ; Did I mention that REBOL has 'money!' datatype?
q/push [Athos Porthos Aramis] ; List elements pushed on one by one.
q/push [[Huey Dewey Lewey]] ; This list is preserved as a list.
; Dump it out, with narrative:
prin... |
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
... | #Python | Python | import random
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] # Move pivot to end
storeIndex = left
for i in range(left, right):
if vector[i] < pivotValue:
vector[storeIndex], vec... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun extractRange(list: List<Int>): String {
if (list.isEmpty()) return ""
val sb = StringBuilder()
var first = list[0]
var prev = first
fun append(index: Int) {
if (first == prev) sb.append(prev)
else if (first == prev - 1) sb.append(first, ",", prev)
el... |
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
def RandomNormal
drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 +
enddef
1000 var n
0 n repeat
getid RandomNormal map
dup
sum n / var mean
"Mean: " print mean print nl
0 swap n for
get mean - 2 power rot + swap
endfor
swap n / sqrt "Standard deviation: " print print |
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
| #PHP | PHP | function random() {
return mt_rand() / mt_getrandmax();
}
$pi = pi(); // Set PI
$a = array();
for ($i = 0; $i < 1000; $i++) {
$a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);
} |
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... | #PowerShell | PowerShell |
function Read-ConfigurationFile
{
[CmdletBinding()]
Param
(
# Path to the configuration file. Default is "C:\ConfigurationFile.cfg"
[Parameter(Mandatory=$false, Position=0)]
[string]
$Path = "C:\ConfigurationFile.cfg"
)
[string]$script:fullName = ""
[string]$... |
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... | #Perl | Perl | sub rangex {
map { /^(.*\d)-(.+)$/ ? $1..$2 : $_ } split /,/, shift
}
# Test and display
print join(',', rangex('-6,-3--1,3-5,7-11,14,15,17-20')), "\n"; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.