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/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 ... | #BQN | BQN | •Out 1⌽∾˜18⥊•Repr"•Out 1⌽∾˜18⥊•Repr" |
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... | #Lasso | Lasso | push: queue->insert
pop: queue->get
empty: queue->size == 0
|
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Logo | Logo | make "fifo []
print empty? :fifo ; true
queue "fifo 1
queue "fifo 2
queue "fifo 3
show :fifo ; [1 2 3]
print dequeue "fifo ; 1
show :fifo ; [2 3]
print empty? :fifo ; false |
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
... | #JavaScript | JavaScript | // this just helps make partition read better
function swap(items, firstIndex, secondIndex) {
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
};
// many algorithms on this page violate
// the constraint that partition operates in place
function partition(array, f... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function formatRange (a() As Integer) As String
Dim lb As Integer = LBound(a)
Dim ub As Integer = UBound(a)
If ub = - 1 Then Return ""
If lb = ub Then Return Str(a(lb))
Dim rangeCount As Integer = 1
Dim range As String = Str(a(lb))
For i As Integer = lb + 1 To ub
If a(i) = a(i - 1)... |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Function StdDev (A()) {
\\ A() has a copy of values
N=Len(A())
if N<1 then Error "Empty Array"
M=Each(A())
k=0
\\ make sum, dev same type as A(k)
sum=A(k)-A(k)
dev=sum
\\ find mean
... |
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
| #Maple | Maple | with(Statistics):
Sample(Normal(1, 0.5), 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... | #Nanoquery | Nanoquery | import Nanoquery.IO
import dict
def get_config(fname)
f = new(File).open(fname)
lines = split(f.readAll(), "\n")
values = new(Dict)
for line in lines
line = trim(line)
if len(line) > 0
if not (line .startswith. "#") or (line .st... |
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... | #Julia | Julia | slurp(s) = readcsv(IOBuffer(s))
conv(s)= colon(map(x->parse(Int,x),match(r"^(-?\d+)-(-?\d+)$", s).captures)...)
expand(s) = mapreduce(x -> isa(x,Number)? Int(x) : conv(x), vcat, slurp(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.
| #Liberty_BASIC | Liberty BASIC | filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
while not(eof(#f))
line input #f, t$
print t$
wend
close #f |
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
... | #PureBasic | PureBasic | Debug ReverseString("!dekrow tI") |
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... | #Common_Lisp | Common Lisp | (defstruct (queue (:constructor %make-queue))
(items '() :type list)
(tail '() :type list))
(defun make-queue ()
"Returns an empty queue."
(%make-queue))
(defun queue-empty-p (queue)
"Returns true if the queue is empty."
(endp (queue-items queue)))
(defun enqueue (item queue)
"Enqueue item in queue.... |
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... | #Elena | Elena | import system'math;
import extensions;
import extensions'text;
struct Quaternion
{
rprop real A;
rprop real B;
rprop real C;
rprop real D;
constructor new(a, b, c, d)
<= new(cast real(a), cast real(b), cast real(c), cast real(d));
constructor new(real a, real b, real c, real d)
... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Bracmat | Bracmat | 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... | #Lua | Lua | q = Queue.new()
Queue.push( q, 5 )
Queue.push( q, "abc" )
while not Queue.empty( q ) do
print( Queue.pop( q ) )
end |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #M2000_Interpreter | M2000 Interpreter |
Module CheckStackAsQueue {
a=stack
Stack a {
Push 1, 2, 3
Print number=3
Print number=2
Print number=1
Print Empty=True
Push "A", "B", "C"
Print letter$="C"
Print letter$="B"
Print letter$="A"
Print Empty=True
Push 1,"OK"
}
Print Len(a)=2, StackItem(a, 2)=1, StackItem$(a, 1)="OK"
Print Stac... |
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
... | #jq | jq | # Emit the k-th smallest item in the input array,
# or nothing if k is too small or too large.
# The smallest corresponds to k==1.
# The input array may hold arbitrary JSON entities, including null.
def quickselect(k):
def partition(pivot):
reduce .[] as $x
# state: [less, other]
( [ [], [] ]; ... |
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
... | #Julia | Julia | v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
@show v partialsort(v, 1:10)
|
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... | #Gambas | Gambas | siInput As New Short[]
siInput1 As Short[] = [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]
siInput2 As Short[] = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
sOutput As New String[]
siCount As Short
siNum As Sho... |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RandomReal[NormalDistribution[1, 1/2], 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
| #MATLAB | MATLAB | mu = 1; sd = 0.5;
x = randn(1000,1) * sd + mu;
|
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... | #Nim | Nim | import re, strformat, strutils, tables
var configs: OrderedTable[string, seq[string]]
var parsed: seq[string]
for line in "demo.config".lines():
let line = line.strip()
if line != "" and not line.startswith(re"#|;"):
parsed = line.split(re"\s*=\s*|\s+", 1)
configs[parsed[0].toLower()] = if len(parsed) >... |
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... | #K | K | grp : {1_'(&x=*x)_ x:",",x}
pos : {:[3=l:#p:&"-"=x;0,p@1;2=l;p;0=*p;,0;0,p]}
conv: 0${(x;1_ y)}/'{(pos x)_ x}'
expd: {,/@[x;&2=#:'x;{(*x)+!1+,/-':x}]}
rnge: {expd@conv grp x} |
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... | #Kotlin | Kotlin | // version 1.0.6
fun expandRange(s: String): MutableList<Int> {
val list = mutableListOf<Int>()
val items = s.split(',')
var first: Int
var last: Int
for (item in items) {
val count = item.count { it == '-' }
if (count == 0 || (count == 1 && item[0] == '-'))
list.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.
| #Lingo | Lingo | fp = xtra("fileIO").new()
fp.openFile(_movie.path & "input.txt", 1)
fileSize = fp.getLength()
repeat while TRUE
str = fp.readLine()
if str.char[1] = numtochar(10) then delete char 1 of str
if the last char of str = numtochar(13) then delete the last char of str
put str
if fp.getPosition()>=fileSize then exit ... |
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.
| #LiveCode | LiveCode | command readFileLineByLine
local tFile, tLines, startRead
put "/usr/share/dict/words" into tFile
open file tFile for text read
put true into startRead
repeat until it is empty and startRead is false
put false into startRead
read from file tFile for 1 line
add 1 to tLines
... |
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
... | #Python | Python | input()[::-1] |
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... | #Component_Pascal | Component Pascal |
MODULE Queue;
IMPORT
Boxes;
TYPE
Instance* = POINTER TO LIMITED RECORD
size: LONGINT;
first,last: LONGINT;
_queue: POINTER TO ARRAY OF Boxes.Box;
END;
PROCEDURE (self: Instance) Initialize(capacity: LONGINT),NEW;
BEGIN
self.size := 0;
self.first := 0;
self.last := 0;
NEW(self._queue,capacity)
E... |
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... | #ERRE | ERRE |
PROGRAM QUATERNION
!$DOUBLE
TYPE QUATERNION=(A,B,C,D)
DIM Q:QUATERNION,Q1:QUATERNION,Q2:QUATERNION
DIM R:QUATERNION,S:QUATERNION,T:QUATERNION
PROCEDURE NORM(T.->NORM)
NORM=SQR(T.A*T.A+T.B*T.B+T.C*T.C+T.D*T.D)
END PROCEDURE
PROCEDURE NEGATIVE(T.->T.)
T.A=-T.A
T.B=-T.B
T.C=-T.C
T.D=-T.D... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Brainf.2A.2A.2A | Brainf*** | ->+>+++>>+>++>+>+++>>+>++>>>+>+>+>++>+>>>>+++>+>>++>+>+++>>++>++>>+>>+>++>++>+>>>>+++>+>>>>++>++>>>>+>>++>+>+++>>>++>>++++++>>+>>++>
+>>>>+++>>+++++>>+>+++>>>++>>++>>+>>++>+>+++>>>++>>+++++++++++++>>+>>++>+>+++>+>+++>>>++>>++++>>+>>++>+>>>>+++>>+++++>>>>++>>>>+>+>+
+>>+++>+>>>>+++>+>>>>+++>+>>>>+++>>++>++>+>+++>+>++>++... |
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... | #Maple | Maple | q := queue[new]();
queue[enqueue](q,1);
queue[enqueue](q,2);
queue[enqueue](q,3);
queue[empty](q);
>>>false
queue[dequeue](q);
>>>1
queue[dequeue](q);
>>>2
queue[dequeue](q);
>>>3
queue[empty](q);
>>>true |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Empty[a_] := If[Length[a] == 0, True, False]
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
Queue = {}
-> {}
Empty[Queue]
-> True
Push[Queue, "1"]
-> {"1"}
EmptyQ[Queue]
->False
Pop[Queue]
->1
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
... | #Kotlin | Kotlin | // version 1.1.2
const val MAX = Int.MAX_VALUE
val rand = java.util.Random()
fun partition(list:IntArray, left: Int, right:Int, pivotIndex: Int): Int {
val pivotValue = list[pivotIndex]
list[pivotIndex] = list[right]
list[right] = pivotValue
var storeIndex = left
for (i in left until right) {
... |
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... | #Go | Go | package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
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,
})
if err != nil {
f... |
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
| #Maxima | Maxima | load(distrib)$
random_normal(1.0, 0.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
| #MAXScript | MAXScript | arr = #()
for i in 1 to 1000 do
(
a = random 0.0 1.0
b = random 0.0 1.0
c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees
append arr c
) |
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... | #OCaml | OCaml | #use "topfind"
#require "inifiles"
open Inifiles
let print_field ini (label, field) =
try
let v = ini#getval "params" field in
Printf.printf "%s: %s\n" label v
with Invalid_element _ ->
Printf.printf "%s: not defined\n" label
let () =
let ini = new inifile "./conf.ini" in
let lst = [
"Full 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... | #Lasso | Lasso | define range_expand(expression::string) => {
local(parts) = regexp(`^(-?\d+)-(-?\d+)$`)
return (
with elm in #expression->split(`,`)
let isRange = #parts->setInput(#elm)&matches
select #isRange
? (integer(#parts->matchString(1)) to integer(#parts->matchString(2)))->asString... |
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... | #Liberty_BASIC | Liberty BASIC | print ExpandRange$( "-6,-3--1,3-5,7-11,14,15,17-20")
end
function ExpandRange$( compressed$)
for i = 1 to ItemCount( compressed$, ",")
item$ = word$( compressed$, i, ",")
dash = instr( item$, "-", 2) 'dash that is not the first character, is a separator
if dash then
for k = va... |
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.
| #Logo | Logo | while [not eof?] [print readline] |
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.
| #Lua | Lua | filename = "input.txt"
fp = io.open( filename, "r" )
for line in fp:lines() do
print( line )
end
fp: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
... | #Quackery | Quackery | [ dup nest? if
[ [] swap witheach
[ nested
swap join ] ] ] is reverse ( x --> x ) |
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... | #Cowgol | Cowgol | include "strings.coh";
include "malloc.coh";
# Define types. The calling code is expected to provide a QueueData type.
record QueueItem is
data: QueueData;
next: [QueueItem];
end record;
record QueueMeta is
head: [QueueItem];
tail: [QueueItem];
end record;
typedef Queue is [QueueMeta];
const Q_N... |
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... | #Euphoria | Euphoria | function norm(sequence q)
return sqrt(power(q[1],2)+power(q[2],2)+power(q[3],2)+power(q[4],2))
end function
function conj(sequence q)
q[2..4] = -q[2..4]
return q
end function
function add(object q1, object q2)
if atom(q1) != atom(q2) then
if atom(q1) then
q1 = {q1,0,0,0}
... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Burlesque | Burlesque | blsq ) "I'm a quine."
"I'm a 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... | #Nemerle | Nemerle | mutable q = Queue(); // or use immutable version as per Haskell example
def empty = q.IsEmpty(); // true at this point
q.Push(empty); // or Enqueue(), or Add()
def a = q.Pop(); // or Dequeue() or Take() |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
-- Queue Usage Demonstration Program -------------------------------------------
method main(args = String[]) public constant
kew = RCQueueImpl()
do
say kew.pop()
catch ex = IndexOutOfBoundsException
say ex.getMessage
... |
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
... | #Lua | Lua | function partition (list, left, right, pivotIndex)
local pivotValue = list[pivotIndex]
list[pivotIndex], list[right] = list[right], list[pivotIndex]
local storeIndex = left
for i = left, right do
if list[i] < pivotValue then
list[storeIndex], list[i] = list[i], list[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... | #Groovy | Groovy | def range = { s, e -> s == e ? "${s}," : s == e - 1 ? "${s},${e}," : "${s}-${e}," }
def compressList = { list ->
def sb, start, end
(sb, start, end) = [''<<'', list[0], list[0]]
for (i in list[1..-1]) {
(sb, start, end) = i == end + 1 ? [sb, start, i] : [sb << range(start, end), i, i]
}
(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
| #Metafont | Metafont | numeric col[];
m := 0; % m holds the mean, for testing purposes
for i = 1 upto 1000:
col[i] := 1 + .5normaldeviate;
m := m + col[i];
endfor
% testing
m := m / 1000; % finalize the computation of the mean
s := 0; % in s we compute the standard deviation
for i = 1 upto 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
| #MiniScript | MiniScript | randNormal = function(mean=0, stddev=1)
return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function
x = []
for i in range(1,1000)
x.push randNormal(1, 0.5)
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... | #ooRexx | ooRexx |
#!/usr/bin/rexx
/*.----------------------------------------------------------------------.*/
/*|readconfig: Read keyword value pairs from a configuration file into |*/
/*| Rexx variables. |*/
/*| ... |
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... | #Lingo | Lingo | -- Note: currently does not support extra white space in input string
on expandRange (str)
res = ""
_player.itemDelimiter = ","
cnt = str.item.count
repeat with i = 1 to cnt
part = str.item[i]
pos = offset("-", part.char[2..part.length])
if pos>0 then
a = integer(part.char[1..pos])
b = i... |
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... | #LiveCode | LiveCode | function range beginning ending stepping
local tRange, tBegin, tEnd, tstep
if stepping is empty or stepping is 0 then
put 1 into tstep
else
put abs(stepping) into tstep
end if
if ending is empty or isNumber(ending) is not true then
put 0 into tEnd
else
put endin... |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module checkit {
\\ prepare a file
document a$
a$={First Line
Second line
Third Line
}
Save.Doc a$, "checkthis.txt", 0 ' 0 for UTF-16LE
Flush
Open "checkthis.txt" For Wide Input as #F
While not Eof(#f) {
Data Seek(#f)
... |
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.
| #Maple | Maple | path := "file.txt":
while (true) do
input := readline(path):
if input = 0 then break; end if:
#The line is stored in input
end do: |
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
... | #Qi | Qi | (REVERSE "ABCD") |
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... | #D | D | queue:
{ :start 0 :end 0 }
enqueue q item:
set-to q q!end item
set-to q :end ++ q!end
dequeue q:
if empty q:
Raise :value-error "popping from empty queue"
q! q!start
delete-from q q!start
set-to q :start ++ q!start
empty q:
= q!start q!end |
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... | #F.23 | F# | open System
[<Struct; StructuralEquality; NoComparison>]
type Quaternion(r : float, i : float, j : float, k : float) =
member this.A = r
member this.B = i
member this.C = j
member this.D = k
new (f : float) = Quaternion(f, 0., 0., 0.)
static member (~-) (q : Quaternion) = Quaternion(-q.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 ... | #C | C | #include <stdio.h>
static char sym[] = "\n\t\\\"";
int main(void) {
const char *code = "#include <stdio.h>%c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym... |
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... | #Nim | Nim | import deques
var queue = initDeque[int]()
queue.addLast(26)
queue.addLast(99)
queue.addLast(2)
echo "Queue size: ", queue.len()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst() |
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... | #Objeck | Objeck |
class Test {
function : Main(args : String[]) ~ Nil {
q := Struct.IntQueue->New();
q->Add(1);
q->Add(2);
q->Add(3);
q->Remove()->PrintLine();
q->Remove()->PrintLine();
q->Remove()->PrintLine();
q->IsEmpty()->PrintLine();
}
}
|
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
... | #Maple | Maple | part := proc(arr, left, right, pivot)
local val,safe,i:
val := arr[pivot]:
arr[pivot], arr[right] := arr[right], arr[pivot]:
safe := left:
for i from left to right do
if arr[i] < val then
arr[safe], arr[i] := arr[i], arr[safe]:
safe := safe + 1:
end if:
end do:
arr[right], arr[safe] := arr[safe], arr[r... |
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
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Quickselect[ds : DataStructure["DynamicArray", _], k_] := QuickselectWorker[ds, 1, ds["Length"], k];
QuickselectWorker[ds_, low0_, high0_, k_] := Module[{pivotIdx, low = low0, high = high0},
While[True,
If[low === high,
Return[ds["Part", low]]
];
pivotIdx = SelectPartition[ds, low, high];
Which... |
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... | #Haskell | Haskell | import Data.List (intercalate)
extractRange :: [Int] -> String
extractRange = intercalate "," . f
where f :: [Int] -> [String]
f (x1 : x2 : x3 : xs) | x1 + 1 == x2 && x2 + 1 == x3
= (show x1 ++ '-' : show xn) : f xs'
where (xn, xs') = g (x3 + 1) xs
g a (n : ns) | a == ... |
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
| #Mirah | Mirah | import java.util.Random
list = double[999]
mean = 1.0
std = 0.5
rng = Random.new
0.upto(998) do | i |
list[i] = mean + std * rng.nextGaussian
end
|
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П7 <-> П8 1/x П6 ИП6 П9 СЧ П6 1/x
ln ИП8 * 2 * КвКор ИП9 2 * пи
* sin * ИП7 + С/П БП 05 |
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... | #Pascal | Pascal | #!/usr/bin/instantfpc
{$if not defined(fpc) or (fpc_fullversion < 20600)}
{$error FPC 2.6.0 or greater required}
{$endif}
{$mode objfpc}{$H+}
uses
Classes,SysUtils,gvector,ghashmap;
type
TStrHashCaseInsensitive = class
class function hash(s: String; n: Integer): Integer;
end;
class function TStrHa... |
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... | #Lua | Lua | function range(i, j)
local t = {}
for n = i, j, i<j and 1 or -1 do
t[#t+1] = n
end
return t
end
function expand_ranges(rspec)
local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)"
local t = {}
for v in string.gmatch(rspec, '[^,]+') do
local s, e = v:match(ptn)
if s == nil t... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | strm=OpenRead["input.txt"];
If[strm=!=$Failed,
While[line=!=EndOfFile,
line=Read[strm];
(*Do something*)
]];
Close[strm]; |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave |
fid = fopen('foobar.txt','r');
if (fid < 0)
printf('Error:could not open file\n')
else
while ~feof(fid),
line = fgetl(fid);
%% process line %%
end;
fclose(fid)
end; |
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
... | #R | R | revstring <- function(stringtorev) {
return(
paste(
strsplit(stringtorev,"")[[1]][nchar(stringtorev):1]
,collapse="")
)
} |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | queue:
{ :start 0 :end 0 }
enqueue q item:
set-to q q!end item
set-to q :end ++ q!end
dequeue q:
if empty q:
Raise :value-error "popping from empty queue"
q! q!start
delete-from q q!start
set-to q :start ++ q!start
empty q:
= q!start q!end |
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... | #Factor | Factor | USING: generalizations io kernel locals math.quaternions
math.vectors prettyprint sequences ;
IN: rosetta-code.quaternion-type
: show ( quot -- )
[ unparse 2 tail but-last "= " append write ] [ call . ] bi
; inline
: 2show ( quots -- )
[ 2curry show ] map-compose [ call ] each ; inline
: q+n ( q n -- ... |
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 ... | #C.23 | C# | class Program { static void Main() { var s = "class Program {{ static void Main() {{ var s = {0}{1}{0}; System.Console.WriteLine(s, (char)34, s); }} }}"; System.Console.WriteLine(s, (char)34, 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... | #OCaml | OCaml | # let q = Queue.create ();;
val q : '_a Queue.t = <abstr>
# Queue.is_empty q;;
- : bool = true
# Queue.add 1 q;;
- : unit = ()
# Queue.is_empty q;;
- : bool = false
# Queue.add 2 q;;
- : unit = ()
# Queue.add 3 q;;
- : unit = ()
# Queue.peek q;;
- : int = 1
# Queue.length q;;
- : int = 3
# Queue.iter (Printf.printf "%d... |
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
... | #Mercury | Mercury | %%%-------------------------------------------------------------------
:- module quickselect_task.
:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
:- implementation.
:- import_module array.
:- import_module exception.
:- import_module int.
:- import_module list.
:- import_mod... |
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
... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
/** @see <a href="http://en.wikipedia.org/wiki/Quickselect">http://en.wikipedia.org/wiki/Quickselect</a> */
runSample(arg)
return
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
method qpartition(list, ilef... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
R := [ 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 ]
write("Input list := ",list2string(R))
write("Extracted sting := ",s := range_extract(R) | "FAILED")
end
proc... |
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
| #Modula-3 | Modula-3 | MODULE Rand EXPORTS Main;
IMPORT Random;
FROM Math IMPORT log, cos, sqrt, Pi;
VAR rands: ARRAY [1..1000] OF LONGREAL;
(* Normal distribution. *)
PROCEDURE RandNorm(): LONGREAL =
BEGIN
WITH rand = NEW(Random.Default).init() DO
RETURN
sqrt(-2.0D0 * log(rand.longreal())) * cos(2.0D0 * Pi * rand.... |
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
| #Nanoquery | Nanoquery | list = {0} * 1000
mean = 1.0; std = 0.5
rng = new(Nanoquery.Util.Random)
for i in range(0, len(list) - 1)
list[i] = mean + std * rng.getGaussian()
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... | #Peloton | Peloton | * blank lines and lines beginning with # and ; should be ignored.
* an all uppercase word defines a configuration symbol
* no tail means a boolean true
* a tail including a comma means a list
* any other kind of tail is a 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... | #Maple | Maple |
ExpandRanges := proc( s :: string )
uses StringTools;
local DoOne := proc( input )
uses StringTools;
local lo, hi, pos;
if IsDigit( input ) or input[ 1 ] = "-"
and IsDigit( input[ 2 .. -1 ] ) then
parse( input )
else
pos := Search( "--", input );
if pos > 0 then
lo ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | rangeexpand[ rng_ ] := Module[ { step1 },
step1 = StringSplit[StringReplacePart[rng,"S",StringPosition[ rng,DigitCharacter~~"-"] /. {x_,y_} -> {y,y}],","];
Flatten@ToExpression/@Quiet@StringReplace[step1,x__~~"S"~~y__->"Range["<>x<>","<>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.
| #Maxima | Maxima | /* Read a file and return a list of all lines */
readfile(name) := block(
[v: [ ], f: openr(name), line],
while stringp(line: readline(f)) do v: endcons(line, v),
close(f),
v
)$ |
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
... | #Racket | Racket | #lang racket
(define (string-reverse s)
(list->string (reverse (string->list s))))
(string-reverse "aoeu") |
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... | #Delphi | Delphi | program QueueDefinition;
{$APPTYPE CONSOLE}
uses
System.Generics.Collections;
type
TQueue = System.Generics.Collections.TQueue<Integer>;
TQueueHelper = class helper for TQueue
function Empty: Boolean;
function Pop: Integer;
procedure Push(const NewItem: Integer);
end;
{ TQueueHelper }
fu... |
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... | #Forth | Forth | : quaternions 4 * floats ;
: qvariable create 1 quaternions allot ;
: q! ( a b c d q -- )
dup 3 floats + f! dup 2 floats + f! dup float+ f! f! ;
: qcopy ( src dest -- ) 1 quaternions move ;
: qnorm ( q -- f )
0e 4 0 do dup f@ fdup f* f+ float+ loop drop fsqrt ;
: qf* ( q f -- )
4 0 do dup f@ fove... |
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 ... | #C.2B.2B | C++ | #include<cstdio>
int main(){char n[]=R"(#include<cstdio>
int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);} |
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... | #Oforth | Oforth | : testQueue
| q i |
Queue new ->q
20 loop: i [ i q push ]
while ( q empty not ) [ q pop . ] ; |
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... | #ooRexx | ooRexx |
q = .queue~new -- create an instance
q~queue(3) -- adds to the end, but this is at the front
q~push(1) -- push on the front
q~queue(2) -- add to the end
say q~pull q~pull q~pull q~isempty -- should display all and be 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
... | #Nim | Nim | proc qselect[T](a: var openarray[T]; k: int, inl = 0, inr = -1): T =
var r = if inr >= 0: inr else: a.high
var st = 0
for i in 0 ..< r:
if a[i] > a[r]: continue
swap a[i], a[st]
inc st
swap a[r], a[st]
if k == st: a[st]
elif st > k: qselect(a, k, 0, st - 1)
else: qselect(a, k, st, ... |
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... | #J | J | fmt=: [: ;@(8!:0) [`]`({. ; (',-' {~ 2 < #) ; {:)@.(2 <. #)
group=: <@fmt;.1~ 1 ~: 0 , 2 -~/\ ]
extractRange=: ',' joinstring group |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.math.BigDecimal
import java.math.MathContext
-- prologue
numeric digits 20
-- get input, set defaults
parse arg dp mu sigma ec .
if mu = '' | mu = '.' then mean = 1.0; else mean = mu
if sigma = ... |
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... | #Perl | Perl | my $fullname;
my $favouritefruit;
my $needspeeling;
my $seedsremoved;
my @otherfamily;
# configuration file definition. See read_conf_file below for explanation.
my $conf_definition = {
'fullname' => [ 'string', \$fullname ],
'favouritefruit' => [ 'string', \$favouritefruit ],
'needspeeling' ... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function L=range_expansion(S)
% Range expansion
if nargin < 1;
S='[]';
end
if ~all(isdigit(S) | (S=='-') | (S==',') | isspace(S))
error 'invalid input';
end
ixr = find(isdigit(S(1:end-1)) & S(2:end) == '-')+1;
S(ixr)=':';
S=['[',S,']'];
L=eval(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.
| #Mercury | Mercury | :- module read_a_file_line_by_line.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, require, string.
main(!IO) :-
io.open_input("test.txt", OpenResult, !IO),
(
OpenResult = ok(File),
read_file_line_by_line(File, 0, ... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Neko | Neko | /**
Read a file line by line, in Neko
<doc><pre>Tectonics:
nekoc readfile.neko
neko readfile [filename]</pre></doc>
*/
var stdin = $loader.loadprim("std@file_stdin", 0)()
var file_open = $loader.loadprim("std@file_open", 2)
var file_read_char = $loader.loadprim("std@file_read_char", 1)
/* Read a line from... |
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
... | #Raku | Raku | say "hello world".flip;
say "as⃝df̅".flip;
say 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧 👨👩👧👦🆗🗺'.flip; |
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... | #E | E | def makeQueue() {
def [var head, var tail] := Ref.promise()
def writer {
to enqueue(value) {
def [nh, nt] := Ref.promise()
tail.resolve([value, nh])
tail := nt
}
}
def reader {
to empty() { return !Ref.isResolved(head) }
to dequeue(whenEmpty) {
if (Ref.isResolved(he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.