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_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.
| #Perl | Perl | open(my $fh, '<', 'foobar.txt')
|| die "Could not open file: $!";
while (<$fh>)
{ # each line is stored in $_, with terminating newline
# chomp, short for chomp($_), removes the terminating newline
chomp;
process($_);
}
close $fh; |
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.
| #Phix | Phix | constant fn = open(command_line()[2],"r")
integer lno = 1
object line
while 1 do
line = gets(fn)
if atom(line) then exit end if
printf(1,"%2d: %s",{lno,line})
lno += 1
end while
close(fn)
{} = wait_key()
|
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
... | #Retro | Retro | 'asdf s:reverse s:put |
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... | #Fortran | Fortran | module FIFO
use fifo_nodes
! fifo_nodes must define the type fifo_node, with the two field
! next and valid, for queue handling, while the field datum depends
! on the usage (see [[FIFO (usage)]] for an example)
! type fifo_node
! integer :: datum
! ! the next part is not variable and must be present
! t... |
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... | #J | J | NB. utilities
ip=: +/ .* NB. inner product
T=. (_1^#:0 10 9 12)*0 7 16 23 A.=i.4
toQ=: 4&{."1 :[: NB. real scalars -> quaternion
NB. task
norm=: %:@ip~@toQ NB. | y
neg=: -&toQ NB. - y and x - y
conj=: 1 _1 _1 _1 * toQ NB. + y
add=: +&toQ ... |
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 ... | #Cowgol | Cowgol | include "cowgol.coh";
var i: uint8 := 0;
var c: uint8[] := {
118,97,114,32,100,32,58,61,32,38,99,32,97,115,32,91,117,105,110,116,
56,93,59,10,112,114,105,110,116,40,34,105,110,99,108,117,100,101,32,92,
34,99,111,119,103,111,108,46,99,111,104,92,34,59,92,110,34,41,59,10,
112,114,105,110,116,40,34,118,97,114,32,105,58,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... | #REXX | REXX | /*REXX program demonstrates four queueing operations: push, pop, empty, query. */
say '══════════════════════════════════ Pushing five values to the stack.'
do j=1 for 4 /*a DO loop to PUSH four values. */
call push j * 10 /*PUSH (aka:... |
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... | #Ruby | Ruby | use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back("Hello");
queue.push_back("World");
while let Some(item) = queue.pop_front() {
println!("{}", item);
}
if queue.is_empty() {
println!("Yes, it 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
... | #Racket | Racket | (define (quickselect A k)
(define pivot (list-ref A (random (length A))))
(define A1 (filter (curry > pivot) A))
(define A2 (filter (curry < pivot) A))
(cond
[(<= k (length A1)) (quickselect A1 k)]
[(> k (- (length A) (length A2))) (quickselect A2 (- k (- (length A) (length A2))))]
[else pivot]))
... |
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
... | #Raku | Raku | my @v = <9 8 7 6 5 0 1 2 3 4>;
say map { select(@v, $_) }, 1 .. 10;
sub partition(@vector, $left, $right, $pivot-index) {
my $pivot-value = @vector[$pivot-index];
@vector[$pivot-index, $right] = @vector[$right, $pivot-index];
my $store-index = $left;
for $left ..^ $right -> $i {
if @vector[$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... | #Liberty_BASIC | Liberty BASIC |
s$ = "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 ExtractRange$( s$)
end
function ExtractRange$( range$)
n = 1
count = ItemCount( range$, ",")
while n <= count
startValue = val( word$( range$,... |
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
| #Picat | Picat | main =>
_ = random2(), % random seed
G = [gaussian_dist(1,0.5) : _ in 1..1000],
println(first_10=G[1..10]),
println([mean=avg(G),stdev=stdev(G)]),
nl.
% Gaussian (Normal) distribution, Box-Muller algorithm
gaussian01() = Y =>
U = frand(0,1),
V = frand(0,1),
Y = sqrt(-2*log(U))*sin(2*math.pi... |
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
| #PicoLisp | PicoLisp | (load "@lib/math.l")
(de randomNormal () # Normal distribution, centered on 0, std dev 1
(*/
(sqrt (* -2.0 (log (rand 0 1.0))))
(cos (*/ 2.0 pi (rand 0 1.0) `(* 1.0 1.0)))
1.0 ) )
(seed (time)) # Randomize
(let Result
(make ... |
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... | #Python | Python | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
# Assume whitespace is ignorable
line = line.strip()
if not line or line.startswith('#'): continue
boolval = True
# Assume leading ";" means a false boolean
if line.s... |
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... | #Phix | Phix | with javascript_semantics
function range_expansion(string range)
sequence s = split(range,','),
res = {}
for i=1 to length(s) do
string si = s[i]
integer k = find('-',si,2)
if k=0 then
res = append(res,to_number(si))
else
integer startrange = ... |
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.
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
argument 1 get "r" fopen var f
true
while
f fgets number? if drop f fclose false else print true endif
endwhile |
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.
| #PHP | PHP | <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
} |
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
... | #REXX | REXX | /*REXX program to reverse a string (and show before and after strings).*/
string1 = 'A man, a plan, a canal, Panama!'
string2 = reverse(string1)
say ' original string: ' string1
say ' reversed string: ' string2
/*stick a fork in it, we're done.*/ |
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... | #Free_Pascal | Free Pascal | program queue;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2); ... |
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... | #Java | Java | public class Quaternion {
private final 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 Quaternion(double r) {
this(r, 0.0, 0.0, 0.0);
}
public double norm() {
... |
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 ... | #Crystal | Crystal | ".tap{|s|print s.inspect,s}".tap{|s|print s.inspect,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... | #Rust | Rust | use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back("Hello");
queue.push_back("World");
while let Some(item) = queue.pop_front() {
println!("{}", item);
}
if queue.is_empty() {
println!("Yes, it is empty!");
}
}
|
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... | #Scala | Scala | val q=scala.collection.mutable.Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
q enqueue 1
q enqueue 2
q enqueue 3
println("queue = " + q)
println("front = " + q.front)
println("dequeue = " + q.dequeue)
println("dequeu... |
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
... | #REXX | REXX | /*REXX program sorts a list (which may be numbers) by using the quick select algorithm.*/
parse arg list; if list='' then list= 9 8 7 6 5 0 1 2 3 4 /*Not given? Use default.*/
say right('list: ', 22) list
#= words(list)
do i=1 for #; @.i= word(list, i) /*assign all the items ──► @. (arra... |
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... | #LiveCode | LiveCode | function rangeExtract nums
local prevNum, znums, rangedNums
set itemDelimiter to ", "
put the first item of nums into prevNum
repeat for each item n in nums
if n is (prevNum + 1) then
put n into prevNum
put "#" & n after znums
else
put n into prevNum
... |
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
| #PL.2FI | PL/I |
/* CONVERTED FROM WIKI FORTRAN */
Normal_Random: procedure options (main);
declare (array(1000), pi, temp,
mean initial (1.0), sd initial (0.5)) float (18);
declare (i, n) fixed binary;
n = hbound(array, 1);
pi = 4.0*ATAN(1.0);
array = random(); /* Uniform distribution */
/* Now conver... |
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
| #PL.2FSQL | PL/SQL |
DECLARE
--The desired collection
type t_coll is table of number index by binary_integer;
l_coll t_coll;
c_max pls_integer := 1000;
BEGIN
FOR l_counter IN 1 .. c_max
LOOP
-- dbms_random.normal delivers normal distributed random numbers with a mean of 0 and a variance of 1
-- We just adjust... |
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... | #Racket | Racket |
#lang racket
(require "options.rkt")
(read-options "options-file")
(define-options fullname favouritefruit needspeeling seedsremoved otherfamily)
(printf "fullname = ~s\n" fullname)
(printf "favouritefruit = ~s\n" favouritefruit)
(printf "needspeeling = ~s\n" needspeeling)
(printf "seedsremoved = ~s\n" ... |
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... | #Phixmonti | Phixmonti | 0 tolist var r
def append
r swap 0 put var r
enddef
"-6,-3--1,3-5,7-11,14,15,17-20" "," " " subst split
len for
get dup tonum dup
nan == if
drop
dup len 1 - 2 swap slice
"-" find dup 2 + rot drop
rot rot 1 swap slice tonum
rot rot len rot swap over - 1 + slice t... |
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... | #PHP | PHP | function rangex($str) {
$lst = array();
foreach (explode(',', $str) as $e) {
if (strpos($e, '-', 1) !== FALSE) {
list($a, $b) = explode('-', substr($e, 1), 2);
$lst = array_merge($lst, range($e[0] . $a, $b));
} else {
$lst[] = (int) $e;
}
}
ret... |
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.
| #Picat | Picat | go =>
FD = open("unixdict.txt"),
while (not at_end_of_stream(FD))
Line = read_line(FD),
println(Line)
end,
close(FD),
nl. |
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.
| #PicoLisp | PicoLisp | (in "foobar.txt"
(while (line)
(process @) ) ) |
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
... | #Ring | Ring |
cStr = "asdf" cStr2 = ""
for x = len(cStr) to 1 step -1 cStr2 += cStr[x] next
See cStr2 # 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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' queue_rosetta.bi
' simple generic Queue type
#Define Queue(T) Queue_##T
#Macro Declare_Queue(T)
Type Queue(T)
Public:
Declare Constructor()
Declare Destructor()
Declare Property capacity As Integer
Declare Property count As Integer
Declare Property empty As Boolean
De... |
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... | #JavaScript | JavaScript | var Quaternion = (function() {
// The Q() function takes an array argument and changes it
// prototype so that it becomes a Quaternion instance. This is
// scoped only for prototype member access.
function Q(a) {
a.__proto__ = proto;
return a;
}
// Actual constructor. This constructor conv... |
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 ... | #D | D | const auto s=`const auto q="const auto s=\x60"~s~"\x60;
mixin(s);";import std.stdio;void main(){writefln(q);pragma(msg,q);}`;
mixin(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... | #Sidef | Sidef | var f = FIFO();
say f.empty; # true
f.push('foo');
f.push('bar', 'baz');
say f.pop; # foo
say f.empty; # false
var g = FIFO('xxx', 'yyy');
say g.pop; # xxx
say f.pop; # bar |
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... | #Standard_ML | Standard ML | - open Fifo;
opening Fifo
datatype 'a fifo = ...
exception Dequeue
val empty : 'a fifo
val isEmpty : 'a fifo -> bool
val enqueue : 'a fifo * 'a -> 'a fifo
val dequeue : 'a fifo -> 'a fifo * 'a
val next : 'a fifo -> ('a * 'a fifo) option
val delete : 'a fifo * ('a -> bool) -> 'a fifo
val head : 'a fifo... |
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... | #Stata | Stata | set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
empty Q ;# ==> 0 (false)
push Q bar
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar |
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
... | #Ring | Ring |
aList = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
see partition(aList, 9, 4, 2) + nl
func partition list, left, right, pivotIndex
pivotValue = list[pivotIndex]
temp = list[pivotIndex]
list[pivotIndex] = list[right]
list[right] = temp
storeIndex = left
for i = left to right-1
... |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Lua | Lua | function extractRange (rList)
local rExpr, startVal = ""
for k, v in pairs(rList) do
if rList[k + 1] == v + 1 then
if not startVal then startVal = v end
else
if startVal then
if v == startVal + 1 then
rExpr = rExpr .. startVal .. "," ..... |
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
| #Pop11 | Pop11 | ;;; Choose radians as arguments to trigonometic functions
true -> popradians;
;;; procedure generating standard normal distribution
define random_normal() -> result;
lvars r1 = random0(1.0), r2 = random0(1.0);
cos(2*pi*r1)*sqrt(-2*log(r2)) -> result
enddefine;
lvars array, i;
;;; Put numbers on the stack
for... |
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
| #PowerShell | PowerShell | function Get-RandomNormal
{
[CmdletBinding()]
Param ( [double]$Mean, [double]$StandardDeviation )
$RandomNormal = $Mean + $StandardDeviation * [math]::Sqrt( -2 * [math]::Log( ( Get-Random -Minimum 0.0 -Maximum 1.0 ) ) ) * [math]::Cos( 2 * [math]::PI * ( Get-Random -Minimum 0.0 -Maximum 1.0 ) )
r... |
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... | #Raku | Raku | my $fullname;
my $favouritefruit;
my $needspeeling = False;
my $seedsremoved = False;
my @otherfamily;
grammar ConfFile {
token TOP {
:my $*linenum = 0;
^ <fullline>* [$ || (\N*) { die "Parse failed at $0" } ]
}
token fullline {
<?before .>
{ ++$*linenum }
<line>
[ \n || { die "Parse failed at lin... |
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... | #PicoLisp | PicoLisp | (de rangeexpand (Str)
(make
(for S (split (chop Str) ",")
(if (index "-" (cdr S))
(chain
(range
(format (head @ S))
(format (tail (- -1 @) S)) ) )
(link (format S)) ) ) ) ) |
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.
| #PL.2FI | PL/I |
read: procedure options (main);
declare line character (500) varying;
on endfile (sysin) stop;
do forever;
get edit (line)(L);
end;
end read;
|
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.
| #PowerShell | PowerShell | $reader = [System.IO.File]::OpenText($mancorfile)
try {
do {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
DoSomethingWithLine($line)
} while ($TRUE)
} finally {
$reader.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
... | #RLaB | RLaB | >> x = "rosettacode"
rosettacode
// script
rx = "";
for (i in strlen(x):1:-1)
{
rx = rx + substr(x, i);
}
>> rx
edocattesor |
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... | #GAP | GAP | Enqueue := function(v, x)
Add(v[1], x);
end;
Dequeue := function(v)
if IsEmpty(v[2]) then
if IsEmpty(v[1]) then
return fail;
else
v[2] := Reversed(v[1]);
v[1] := [];
fi;
fi;
return Remove(v[2]);
end;
# a new queue
v := [[], []];
Enqueue... |
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... | #jq | jq | def Quaternion(q0;q1;q2;q3): { "q0": q0, "q1": q1, "q2": q2, "q3": q3, "type": "Quaternion" };
# promotion of a real number to a quaternion
def Quaternion(r): if (r|type) == "number" then Quaternion(r;0;0;0) else r end;
# thoroughly recursive pretty-print
def pp:
def signage: if . >= 0 then "+ \(.)" else "- \... |
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 ... | #Dao | Dao | syntax{Q $EXP}as{io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\')}Q io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\') |
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... | #Tcl | Tcl | set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
empty Q ;# ==> 0 (false)
push Q bar
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar |
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... | #UNIX_Shell | UNIX Shell | # any valid variable name can be used as a queue without initialization
queue_empty foo && echo foo is empty || echo foo is not empty
queue_push foo bar
queue_push foo baz
queue_push foo "element with spaces"
queue_empty foo && echo foo is empty || echo foo is not empty
print "peek: $(queue_peek foo)"; queue_po... |
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
... | #Ruby | Ruby | def quickselect(a, k)
arr = a.dup # we will be modifying it
loop do
pivot = arr.delete_at(rand(arr.length))
left, right = arr.partition { |x| x < pivot }
if k == left.length
return pivot
elsif k < left.length
arr = left
else
k = k - left.length - 1
arr = right
end
e... |
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... | #Maple | Maple | lst := [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]:
r1,r2:= lst[1],lst[1]:
for i from 2 to numelems(lst) do
if lst[i] - lst[i-1] = 1 then #consecutive
r2 := lst[i]:
else #break
printf(piecewise(r2-r1=1, "%d,%d,", r2-r1>1,"%d-%d,",... |
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
| #PureBasic | PureBasic | Procedure.f RandomNormal()
; This procedure can return any real number.
Protected.f x1, x2
; random numbers from the open interval ]0, 1[
x1 = (Random(999998)+1) / 1000000 ; must be > 0 because of Log(x1)
x2 = (Random(999998)+1) / 1000000
ProcedureReturn Sqr(-2*Log(x1)) * Cos(2*#PI*x2)
EndPr... |
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
| #Python | Python | >>> import random
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>> |
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... | #RapidQ | RapidQ |
type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
... |
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... | #PL.2FI | PL/I | range_expansion:
procedure options (main);
get_number:
procedure (Number, c, eof);
declare number fixed binary (31), c character (1), eof bit (1) aligned;
declare neg fixed binary (1);
number = 0; eof = false;
do until (c ^= ' ');
get edit (c) (a(1));
end;
if c = '-' then do; get edit ... |
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... | #PowerShell | PowerShell |
function range-expansion($array) {
function expansion($arr) {
if($arr) {
$arr = $arr.Split(',')
$arr | foreach{
$a = $_
$b, $c, $d, $e = $a.Split('-')
switch($a) {
$b {return $a}
"-$c" {return... |
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.
| #PureBasic | PureBasic | FileName$ = OpenFileRequester("","foo.txt","*.txt",0)
If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files
BOMformat = ReadStringFormat(0) ; reads the BOMformat (Unicode, UTF-8, ASCII, ...)
While Not Eof(0)
line$ = ReadString(0, BOMformat)
DoSomethingWithTheLin... |
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.
| #Python | Python | with open("foobar.txt") as f:
for line in f:
process(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
... | #Robotic | Robotic |
. "local1 = Main string"
. "local2 = Temporary string storage"
. "local3 = String length"
set "$local1" to ""
set "$local2 " to ""
set "local3" to 0
input string "String to reverse:"
set "$local1" to "&INPUT&"
set "$local2" to "$local1"
set "local3" to "$local2.length"
loop start
set "$local1.(('local3' - 1) - 'loo... |
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... | #Go | Go |
package queue
// int queue
// the zero object is a valid queue ready to be used.
// items are pushed at tail, popped at head.
// tail = -1 means queue is full
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
// buffer full. reallocate.
case q.tail < 0:
... |
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... | #Julia | Julia | import Base: convert, promote_rule, show, conj, abs, +, -, *
immutable Quaternion{T<:Real} <: Number
q0::T
q1::T
q2::T
q3::T
end
Quaternion(q0::Real,q1::Real,q2::Real,q3::Real) = Quaternion(promote(q0,q1,q2,q3)...)
convert{T}(::Type{Quaternion{T}}, x::Real) =
Quaternion(convert(T,x), zero(T), ... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Dart | Dart | main()=>(s){print('$s(r\x22$s\x22);');}(r"main()=>(s){print('$s(r\x22$s\x22);');}"); |
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 ... | #dc | dc | [91PP93P[dx]P]dx |
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... | #VBA | VBA | Public Sub fifo()
push "One"
push "Two"
push "Three"
Debug.Print pop, pop, pop, empty_
End Sub |
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... | #Wart | Wart | q <- (queue)
empty? q
=> 1
enq 1 q
empty? q
=> nil
enq 2 q
len q
=> 2
deq q
len q
=> 1 |
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
... | #Rust | Rust | // See https://en.wikipedia.org/wiki/Quickselect
fn partition<T: PartialOrd>(a: &mut [T], left: usize, right: usize, pivot: usize) -> usize {
a.swap(pivot, right);
let mut store_index = left;
for i in left..right {
if a[i] < a[right] {
a.swap(store_index, i);
store_index +=... |
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
... | #Scala | Scala | import scala.util.Random
object QuickSelect {
def quickSelect[A <% Ordered[A]](seq: Seq[A], n: Int, rand: Random = new Random): A = {
val pivot = rand.nextInt(seq.length);
val (left, right) = seq.partition(_ < seq(pivot))
if (left.length == n) {
seq(pivot)
} else if (left.length < n) {
q... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | rangeExtract[data_List] := ToString[Row[Riffle[
Flatten[Split[Sort[data], #2 - #1 == 1 &] /. {a_Integer, __, b_} :> Row[{a, "-", b}]],
","]]];
rangeExtract[{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}... |
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
| #R | R | # For reproducibility, set the seed:
set.seed(12345L)
result <- rnorm(1000, mean = 1, sd = 0.5) |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Racket | Racket |
#lang racket
(for/list ([i 1000])
(add1 (* (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... | #Red | Red | Red ["Read a config file"]
remove-each l lines: read/lines %file.conf [any [empty? l #"#" = l/1]]
foreach line lines [
foo: parse line [collect [keep to [" " | end] skip keep to end]]
either foo/1 = #";" [set to-word foo/2 false][
set to-word foo/1 any [
all [find foo/2 #"," split foo/2 ", "]
foo/2
true
... |
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... | #Prolog | Prolog | range_expand :-
L = '-6,-3--1,3-5,7-11,14,15,17-20',
writeln(L),
atom_chars(L, LA),
extract_Range(LA, R),
maplist(study_Range, R, LR),
pack_Range(LX, LR),
writeln(LX).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% extract_Range(?In, ?Out)
% In : '-6,-3--1,3-5,7-11,14,15,17-20'
% Out : [-6], [-3... |
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.
| #R | R | conn <- file("notes.txt", "r")
while(length(line <- readLines(conn, 1)) > 0) {
cat(line, "\n")
} |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Racket | Racket | (define (read-next-line-iter file)
(let ((line (read-line file 'any)))
(unless (eof-object? line)
(display line)
(newline)
(read-next-line-iter file))))
(call-with-input-file "foobar.txt" read-next-line-iter) |
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
... | #Ruby | Ruby | str = "asdf"
reversed = str.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... | #Groovy | Groovy | class Queue {
private List buffer
public Queue(List buffer = new LinkedList()) {
assert buffer != null
assert buffer.empty
this.buffer = buffer
}
def push (def item) { buffer << item }
final enqueue = this.&push
def pop() {
if (this.empty) throw new NoSuchE... |
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... | #Kotlin | Kotlin | // version 1.1.2
data class Quaternion(val a: Double, val b: Double, val c: Double, val d: Double) {
operator fun plus(other: Quaternion): Quaternion {
return Quaternion (this.a + other.a, this.b + other.b,
this.c + other.c, this.d + other.d)
}
operator fun plus(r: Dou... |
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 ... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | "!print !. dup"
!print !. dup |
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... | #Wren | Wren | import "/queue" for Queue
var q = Queue.new()
q.push(1)
q.push(2)
System.print("Queue contains %(q)")
System.print("Number of elements in queue = %(q.count)")
var item = q.pop()
System.print("'%(item)' popped from the queue")
System.print("First element is now %(q.peek())")
q.clear()
System.print("Queue cleared")
Sys... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
int In, Out; \fill and empty indexes into Fifo
proc Push(A); \Add integer A to queue
int A; \(overflow not detected)
[Fifo(In):= A;
In:= In+1;
if In >= Size then In:= 0;
];
func Pop; \Return first integer in queue... |
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
... | #Scheme | Scheme | ;;
;; Quickselect with random pivot.
;;
;; Such a pivot provides O(n) worst-case *expected* time.
;;
;; One can get true O(n) time by using "median of medians" to choose
;; the pivot, but quickselect with a median of medians pivot is a
;; complicated algorithm. See
;; https://en.wikipedia.org/w/index.php?title=Median_o... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function S=range_extraction(L)
% Range extraction
L(end+1) = NaN;
S = int2str(L(1));
k = 1;
while (k < length(L)-1)
if (L(k)+1==L(k+1) && L(k)+2==L(k+2) )
m = 2;
while (L(k)+m==L(k+m))
m = m+1;
end
k = k+m-1;
S = [... |
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
| #Raku | Raku | sub randnorm ($mean, $stddev) {
$mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand)
}
my @nums = randnorm(1, 0.5) xx 1000;
# Checking
say my $mean = @nums R/ [+] @nums;
say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2;
|
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... | #REXX | REXX | /*REXX program reads a config (configuration) file and assigns VARs as found within. */
signal on syntax; signal on novalue /*handle REXX source program errors. */
parse arg cFID _ . /*cFID: is the CONFIG file to be read.*/
if cFID=='' then cFID='CONFIG.DAT' ... |
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... | #PureBasic | PureBasic | Procedure rangeexpand(txt.s, List outputList())
Protected rangesCount = CountString(txt, ",") + 1
Protected subTxt.s, r, rangeMarker, rangeStart, rangeFinish, rangeIncrement, i
LastElement(outputList())
For r = 1 To rangesCount
subTxt = StringField(txt, r, ",")
rangeMarker = FindString(subTxt, "-", 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.
| #Raku | Raku | for open('test.txt').lines
{
.say
} |
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.
| #RapidQ | RapidQ |
$Include "Rapidq.inc"
dim file as qfilestream
if file.open("c:\A Test.txt", fmOpenRead) then
while not File.eof
print File.readline
wend
else
print "Cannot read file"
end if
input "Press enter to exit: ";a$
|
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
... | #Run_BASIC | Run BASIC | string$ = "123456789abcdefghijk"
for i = len(string$) to 1 step -1
print mid$(string$,i,1);
next i |
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... | #Haskell | Haskell | data Fifo a = F [a] [a]
emptyFifo :: Fifo a
emptyFifo = F [] []
push :: Fifo a -> a -> Fifo a
push (F input output) item = F (item:input) output
pop :: Fifo a -> (Maybe a, Fifo a)
pop (F input (item:output)) = (Just item, F input output)
pop (F [] [] ) = (Nothing, F [] [])
pop (F input [] )... |
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... | #Liberty_BASIC | Liberty BASIC |
q$ = q$( 1 , 2 , 3 , 4 )
q1$ = q$( 2 , 3 , 4 , 5 )
q2$ = q$( 3 , 4 , 5 , 6 )
real = 7
print "q = " ; q$
print "q1 = " ; q1$
print "q2 = " ; q2$
print "real = " ; real
print "length /norm q = " ; length( q$ ) ' =norm norm of q
print "negative (-q1) = " ; negative$... |
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 ... | #Draco | Draco | *char q=
"proc main() void:\r\n"
" [128]char l;\r\n"
" char ch;\r\n"
" channel input text qc, lc;\r\n"
" open(qc, q);\r\n"
" writeln(\"*char q=\");\r\n"
" while readln(qc; &l[0]) do\r\n"
" write('\"');\r\n"
" open(lc, &l[0]);\r\n"
" while read(lc; ch) do\r\n"
" if ch='\... |
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... | #Yabasic | Yabasic | sub push(x$)
queue$ = queue$ + x$ + "#"
end sub
sub pop$()
local i, r$
if queue$ <> "" then
i = instr(queue$, "#")
if i then
r$ = left$(queue$, i-1)
stack$ = right$(queue$, len(queue$) - i)
else
r$ = queue$
queue$ = ""
end i... |
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... | #zkl | zkl | q:=Queue();
q.empty(); //-->True
q.push(1,2,3);
q.pop(); //-->1
q.empty(); //-->False
q.pop();q.pop();q.pop(); //-->IndexError thrown
|
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
... | #Sidef | Sidef | func quickselect(a, k) {
var pivot = a.pick;
var left = a.grep{|i| i < pivot};
var right = a.grep{|i| i > pivot};
given(var l = left.len) {
when (k) { pivot }
case (k < l) { __FUNC__(left, k) }
default { __FUNC__(right, k - l - 1) }
}
}
var v = [9, 8, 7, 6, 5, 0... |
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... | #Mercury | Mercury | :- module range_extraction.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, ranges, string.
main(!IO) :-
print_ranges(numbers, !IO).
:- pred print_ranges(list(int)::in, io::di, io::uo) is det.
print_ranges(Nums, !IO) :-
Ranges ... |
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
| #Raven | Raven | define PI
-1 acos
define rand1
9999999 choose 1 + 10000000.0 /
define randNormal
rand1 PI * 2 * cos
rand1 log -2 * sqrt
*
2 / 1 +
1000 each drop randNormal "%f\n" print |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.