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/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
| #REXX | REXX | /*REXX pgm generates 1,000 normally distributed numbers: mean=1, standard deviation=½.*/
numeric digits 20 /*the default decimal digit precision=9*/
parse arg n seed . /*allow specification of N and the seed*/
if n=='' | n=="," then n=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... | #Ruby | Ruby | fullname = favouritefruit = ""
needspeeling = seedsremoved = false
otherfamily = []
IO.foreach("config.file") do |line|
line.chomp!
key, value = line.split(nil, 2)
case key
when /^([#;]|$)/; # ignore line
when "FULLNAME"; fullname = value
when "FAVOURITEFRUIT"; favouritefruit = value
when "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... | #Python | Python | def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1) + 1)
else:
lst.append(int(r))
return lst
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20')) |
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.
| #REXX | REXX | /*REXX program reads and displays (with a count) a file, one line at a time. */
parse arg fID . /*obtain optional argument from the CL.*/
if fID=='' then exit 8 /*Was no fileID specified? Then quit. */
say center(' displaying file: ' fID" ", 79, '═'... |
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
... | #Rust | Rust | let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba"); |
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... | #Icon_and_Unicon | Icon and Unicon |
# Use a record to hold a Queue, using a list as the concrete implementation
record Queue(items)
procedure make_queue ()
return Queue ([])
end
procedure queue_push (queue, item)
put (queue.items, item)
end
# if the queue is empty, this will 'fail' and return nothing
procedure queue_pop (queue)
return pop (... |
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... | #Lua | Lua | Quaternion = {}
function Quaternion.new( a, b, c, d )
local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }
local metatab = {}
setmetatable( q, metatab )
metatab.__add = Quaternion.add
metatab.__sub = Quaternion.sub
metatab.__unm = Quaternion.unm
metatab.__mul = Quaternion.mul
... |
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 ... | #E | E | " =~ x; println(E.toQuote(x),x)" =~ x; println(E.toQuote(x),x) |
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
... | #Standard_ML | Standard ML | fun quickselect (_, _, []) = raise Fail "empty"
| quickselect (k, cmp, x :: xs) = let
val (ys, zs) = List.partition (fn y => cmp (y, x) = LESS) xs
val l = length ys
in
if k < l then
quickselect (k, cmp, ys)
else if k > l then
quickselect (k-l-1, cmp, zs)
... |
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
... | #Swift | Swift | func select<T where T : Comparable>(var elements: [T], n: Int) -> T {
var r = indices(elements)
while true {
let pivotIndex = partition(&elements, r)
if n == pivotIndex {
return elements[pivotIndex]
} else if n < pivotIndex {
r.endIndex = pivotIndex
} else {
r.startIndex = pivotInd... |
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... | #MiniScript | MiniScript | extractRange = function(ints)
result = []
idx = 0
while idx < ints.len
runLen = 1
while idx+runLen < ints.len and ints[idx+runLen] == ints[idx] + runLen
runLen = runLen + 1
end while
if runLen > 2 then
result.push ints[idx] + "-" + ints[idx+runLen-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
| #Ring | Ring |
for i = 1 to 10
see random(i) + nl
next i
|
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Ruby | Ruby | Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) } |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Run_BASIC | Run BASIC | dim param$(6)
dim paramVal$(6)
param$(1) = "fullname"
param$(2) = "favouritefruit"
param$(3) = "needspeeling"
param$(4) = "seedsremoved"
param$(5) = "otherfamily"
for i = 1 to 6
paramVal$(i) = "false"
next i
open DefaultDir$ + "\public\a.txt" for binary as #f
while not(eof(#f))
line input #f, a$
a$ = trim$(a$)
if... |
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... | #R | R |
rangeExpand <- function(text) {
lst <- gsub("(\\d)-", "\\1:", unlist(strsplit(text, ",")))
unlist(sapply(lst, function (x) eval(parse(text=x))), use.names=FALSE)
}
rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20")
[1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
|
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.
| #Ring | Ring |
fp = fopen("C:\Ring\ReadMe.txt","r")
r = ""
while isstring(r)
r = fgetc(fp)
if r = char(10) see nl
else see r ok
end
fclose(fp)
|
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.
| #Ruby | Ruby | IO.foreach "foobar.txt" do |line|
# Do something with line.
puts line
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
... | #S-lang | S-lang | variable sa = "Hello, World", aa = Char_Type[strlen(sa)+1];
init_char_array(aa, sa);
array_reverse(aa);
% print(aa);
% Unfortunately, strjoin() only joins strings, so we map char()
% [sadly named: actually converts char into single-length string]
% onto the array:
print( strjoin(array_map(String_Type, &char, aa), "... |
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... | #J | J | queue_fifo_=: ''
pop_fifo_=: verb define
r=. {. ::] queue
queue=: }.queue
r
)
push_fifo_=: verb define
queue=: queue,y
y
)
isEmpty_fifo_=: verb define
0=#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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
class Quaternion {
\\ by default are double
a,b,c,d
Property ToString$ {
Value {
link parent a,b,c, d to a,b,c,d
value$=format$("{0} + {1}i + {2}j + {3}k",a,b,c,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 ... | #Elixir | Elixir | a = <<"a = ~p~n:io.fwrite(a,[a])~n">>
:io.fwrite(a,[a]) |
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
... | #Tcl | Tcl | # Swap the values at two indices of a list
proc swap {list i j} {
upvar 1 $list l
set tmp [lindex $l $i]
lset l $i [lindex $l $j]
lset l $j $tmp
}
proc quickselect {vector k {left 0} {right ""}} {
set last [expr {[llength $vector] - 1}]
if {$right eq ""} {
set right $last
}
# Sanity a... |
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... | #MUMPS | MUMPS | RANGCONT(X) ;Integer range contraction
NEW Y,I,CONT,NOTFIRST,CURR,PREV,NEXT,SEQ SET Y="",SEQ=0,PREV="",CONT=0
FOR I=1:1:$LENGTH(X,",") DO
.SET NOTFIRST=$LENGTH(Y),CURR=$PIECE(X,",",I),NEXT=$PIECE(X,",",I+1)
.FOR Q:$EXTRACT(CURR)'=" " S CURR=$EXTRACT(CURR,2,$LENGTH(CURR)) ;clean up leading spaces
.S SEQ=((CURR-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
| #Run_BASIC | Run BASIC | dim a(1000)
pi = 22/7
for i = 1 to 1000
a( i) = 1 + .5 * (sqr(-2 * log(rnd(0))) * cos(2 * pi * rnd(0)))
next i |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Rust | Rust | extern crate rand;
use rand::distributions::{Normal, IndependentSample};
fn main() {
let mut rands = [0.0; 1000];
let normal = Normal::new(1.0, 0.5);
let mut rng = rand::thread_rng();
for num in rands.iter_mut() {
*num = normal.ind_sample(&mut rng);
}
} |
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... | #Rust | Rust | use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
let path = String::from("file.conf");
let cfg = config_from_file(path);
println!("{:?}", cfg);
}
fn config_from_file(path: String) -> Config {
let path = Path::new(&path);
... |
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... | #Racket | Racket |
#lang racket
(define (range-expand s)
(append*
(for/list ([r (regexp-split "," s)])
(match (regexp-match* "(-?[0-9]+)-(-?[0-9]+)" r
#:match-select cdr)
[(list (list f t))
(range (string->number f) (+ (string->number t) 1))]
[(list)
(list (str... |
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... | #Raku | Raku | sub range-expand (Str $range-description) {
my token number { '-'? \d+ }
my token range { (<&number>) '-' (<&number>) }
$range-description
.split(',')
.map({ .match(&range) ?? $0..$1 !! +$_ })
.flat
}
say range-expand('-6,-3--1,3-5,7-11,14,15,17-20').join(', '); |
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.
| #Run_BASIC | Run BASIC | open DefaultDir$ + "\public\filetest.txt" for input as #f
while not(eof(#f))
line input #f, a$
print a$
wend
close #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.
| #Rust | Rust | use std::io::{BufReader,BufRead};
use std::fs::File;
fn main() {
let file = File::open("file.txt").unwrap();
for line in BufReader::new(file).lines() {
println!("{}", line.unwrap());
}
} |
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
... | #SAS | SAS | data _null_;
length a b $11;
a="I am Legend";
b=reverse(a);
put a;
put b;
run; |
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... | #Java | Java | public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){ //standard ... |
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... | #Maple | Maple |
with(ArrayTools);
module Quaternion()
option object;
local real := 0;
local i := 0;
local j := 0;
local k := 0;
export getReal::static := proc(self::Quaternion, $)
return self:-real;
end proc;
export getI::static := proc(self::Quaternion, $)
return self:-i;
end proc;
export getJ::static := proc(... |
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 ... | #Erlang | Erlang | PROGRAM QUINE
BEGIN
READ(D$,Y$)
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(X$)
END LOOP
RESTORE
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))
END LOOP
PRINT(D$;CHR$(34);CHR$(34);CHR$(41))
PRINT(Y$)
DATA("DATA(")
DATA("END PROGRAM")
DATA("PROGRAM QUINE")
DATA("BEGIN")
DATA("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
... | #VBA | VBA | Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
Dim left As Integer, right As Integer, pos As Integer
Dim pivotValue As Integer, tmp As Integer
left = 1: right = UBound(s)
Do While left < right
pivotValue = s(k)
tmp = s(k)
s(k) = s(righ... |
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... | #NetRexx | NetRexx | /*NetRexx program to test range extraction. ***************************
* 07.08.2012 Walter Pachl derived from my Rexx Version
* Changes: line continuation in aaa assignment changed
* 1e99 -> 999999999
* Do -> Loop
* words(aaa) -> aaa.words()
* word(aaa,i) -> aaa.word(i)
************... |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #SAS | SAS |
/* Generate 1000 random numbers with mean 1 and standard deviation 0.5.
SAS version 9.2 was used to create this code.*/
data norm1000;
call streaminit(123456);
/* Set the starting point, so we can replicate results.
If you want different results each time, comment the above line. */
do i=1 to 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
| #Sather | Sather | class MAIN is
main is
a:ARRAY{FLTD} := #(1000);
i:INT;
RND::seed(2010);
loop i := 1.upto!(1000) - 1;
a[i] := 1.0d + 0.5d * RND::standard_normal;
end;
-- testing the distribution
mean ::= a.reduce(bind(_.plus(_))) / a.size.fltd;
#OUT + "mean " + mean + "\n";
a.map(bind(_.m... |
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... | #Scala | Scala | val conf = scala.io.Source.fromFile("config.file").
getLines.
toList.
filter(_.trim.size > 0).
filterNot("#;" contains _(0)).
map(_ split(" ", 2) toList).
map(_ :+ "true" take 2).
map {
s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList)
}.toMap |
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... | #Raven | Raven | define get_num use $lst
# "-22" split by "-" is [ "", "22" ] so check if
# first list item is "" -> a negative number
$lst 0 get "" = if
# negative number
#
# convert str to integer and multiply by -1
-1 $lst 1 get 0 prefer *
$lst shift $lst shift drop drop
else
... |
http://rosettacode.org/wiki/Range_expansion | Range expansion | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #REXX | REXX | /*REXX program expands an ordered list of integers into an expanded list. */
old= '-6,-3--1, 3-5, 7-11, 14,15,17-20'; a=translate(old,,',')
new= /*translate [↑] commas (,) ───► blanks*/
do until a==''; parse var a X a /*obtain th... |
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.
| #Scala | Scala | import scala.io._
Source.fromFile("foobar.txt").getLines.foreach(println) |
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.
| #Scheme | Scheme | ; Commented line below should be uncommented to use read-line with Guile
;(use-modules (ice-9 rdelim))
(define file (open-input-file "input.txt"))
(do ((line (read-line file) (read-line file))) ((eof-object? line))
(display line)
(newline)) |
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
... | #Sather | Sather | class MAIN is
main is
s ::= "asdf";
reversed ::= s.reverse;
-- current implementation does not handle multibyte encodings correctly
end;
end; |
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... | #JavaScript | JavaScript | var fifo = [];
fifo.push(42); // Enqueue.
fifo.push(43);
var x = fifo.shift(); // Dequeue.
alert(x); // 42 |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | <<Quaternions`
q=Quaternion[1,2,3,4]
q1=Quaternion[2,3,4,5]
q2=Quaternion[3,4,5,6]
r=7
->Quaternion[1,2,3,4]
->Quaternion[2,3,4,5]
->Quaternion[3,4,5,6]
->7
Abs[q]
->√30
-q
->Quaternion[-1,-2,-3,-4]
Conjugate[q]
->Quaternion[1,-2,-3,-4]
r+q
->Quaternion[8,2,3,4]
q+r
->Quaternion[8,2,3,4]
q1+q2
->Quaternion[5,7,9,11]
... |
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 ... | #ERRE | ERRE | PROGRAM QUINE
BEGIN
READ(D$,Y$)
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(X$)
END LOOP
RESTORE
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))
END LOOP
PRINT(D$;CHR$(34);CHR$(34);CHR$(41))
PRINT(Y$)
DATA("DATA(")
DATA("END PROGRAM")
DATA("PROGRAM QUINE")
DATA("BEGIN")
DATA("R... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Euphoria | Euphoria | constant p="constant p=%s%s%s printf(1,p,{34,p,34})" printf(1,p,{34,p,34}) |
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
... | #Wren | Wren | import "/sort" for Find
var a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
for (k in 0..9) {
System.write(Find.quick(a, k))
if (k < 9) System.write(", ")
}
System.print() |
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... | #Nim | Nim | import parseutils, re, strutils, sequtils
proc extractRange(input: string): string =
var list = input.replace(re"\s+").split(',').map(parseInt)
var ranges: seq[string]
var i = 0
while i < list.len:
var first = list[i] # first element in the current range
var offset = i
while True: # skip ahead to ... |
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
| #Scala | Scala | List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian) |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Scheme | Scheme | ; linear congruential generator given in C99 section 7.20.2.1
(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))
; uniform real numbers in open interval (0, 1)
(define (unif-rand seed) (let ((r (c-rand seed))) (lambda () (/ (+ (r) 1) 32769.0))))
; Box-Mul... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "scanfile.s7i";
var string: fullname is "";
var string: favouritefruit is "";
var boolean: needspeeling is FALSE;
var boolean: seedsremoved is FALSE;
var array string: otherfamily is 0 times "";
const proc: main is func
local
var file: configFile is STD_NULL;
var stri... |
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... | #Ring | Ring |
# Project : Range expansion
int = "-6,-3--1,3-5,7-11,14,15,17-20"
int = str2list(substr(int, ",", nl))
newint = []
for n=1 to len(int)
nrint = substr(int[n], "-")
nrint2 = substr(int[n], "--")
if nrint2 > 0
temp1 = left(int[n], nrint2 -1)
temp2 = right(int[n], len(int[n]) - nrint2)
... |
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... | #Ruby | Ruby | def range_expand(rng)
rng.split(',').flat_map do |part|
if part =~ /^(-?\d+)-(-?\d+)$/
($1.to_i .. $2.to_i).to_a
else
Integer(part)
end
end
end
p range_expand('-6,-3--1,3-5,7-11,14,15,17-20') |
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.
| #Sed | Sed | #!/bin/sed -f
p
|
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: aFile is STD_NULL;
var string: line is "";
begin
aFile := open("input.txt", "r");
while hasNext(aFile) do
readln(aFile, line);
writeln("LINE: " <& line);
end while;
end func; |
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
... | #Scala | Scala | "asdf".reverse |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operation... | #jq | jq | # An empty queue:
def fifo: [];
def push(e): [e] + .;
def pop: [.[0], .[1:]];
def pop_or_error: if length == 0 then error("pop_or_error") else pop end;
def empty: length == 0; |
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... | #Julia | Julia |
struct Queue{T}
a::Array{T,1}
end
Queue() = Queue(Any[])
Queue(a::DataType) = Queue(a[])
Queue(a) = Queue(typeof(a)[])
Base.isempty(q::Queue) = isempty(q.a)
function Base.pop!(q::Queue{T}) where {T}
!isempty(q) || error("queue must be non-empty")
pop!(q.a)
end
function Base.push!(q::Queue{T}, x::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... | #Mercury | Mercury | :- module quaternion.
:- interface.
:- import_module float.
:- type quaternion
---> q( w :: float,
i :: float,
j :: float,
k :: float ).
% conversion
:- func r(float) = quaternion is det.
% operations
:- func norm(quaternion) = float is det.
:... |
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 ... | #F.23 | F# | let s = "let s = {0}{1}{0} in System.Console.WriteLine(s, char 34, s);;" in System.Console.WriteLine(s, char 34, s);; |
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
... | #zkl | zkl | fcn qselect(list,nth){ // in place quick select
fcn(list,left,right,nth){
if (left==right) return(list[left]);
pivotIndex:=(left+right)/2; // or median of first,middle,last
// partition
pivot:=list[pivotIndex];
list.swap(pivotIndex,right); // move pivot to end
pivotIndex := lef... |
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... | #Oberon-2 | Oberon-2 |
MODULE RangeExtraction;
IMPORT Out;
PROCEDURE Range(s: ARRAY OF INTEGER);
VAR
i,j: INTEGER;
PROCEDURE Emit(sep: CHAR);
BEGIN
IF i > 2 THEN
Out.Int(s[j],3);Out.Char('-');Out.Int(s[j + i - 1],3);Out.Char(sep);
INC(j,i)
ELSE
Out.Int(s[j],3);Out.Char(sep);
INC(j)
END;
END Emit;
BEGIN
j := 0;i... |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const func float: frand is func # Uniform distribution, (0..1]
result
var float: frand is 0.0;
begin
repeat
frand := rand(0.0, 1.0);
until frand <> 0.0;
end func;
const func float: randomNormal is # Normal distribution,... |
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
| #Sidef | Sidef | var arr = 1000.of { 1 + (0.5 * sqrt(-2 * 1.rand.log) * cos(Num.tau * 1.rand)) }
arr.each { .say } |
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... | #SenseTalk | SenseTalk |
// read the configuration file and get a list of just the interesting lines
set lines to each line of file "config.txt" where char 1 of each isn't in ("#", ";", "")
set the listFormat's quotes to quote -- be sure to quote values for evaluating
repeat with each configLine in lines
put word 1 of configLine into va... |
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... | #Run_BASIC | Run BASIC | PRINT rangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
end
function rangeExpand$(range$)
[loop]
i = INSTR(range$, "-", i+1)
IF i THEN
j = i
WHILE MID$(range$,j-1,1) <> "," AND j <> 1
j = j - 1
wend
IF i > j then
IF MID$(range$,j,i-j) <> str$(i-j)+" " THEN
t$ = ""
FOR k = VAL(MID$(range$,j)) 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... | #Rust | Rust | use std::str::FromStr;
// Precondition: range doesn't contain multibyte UTF-8 characters
fn range_expand(range : &str) -> Vec<i32> {
range.split(',').flat_map(|item| {
match i32::from_str(item) {
Ok(n) => n..n+1,
_ => {
let dashpos=
match item.rfi... |
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.
| #SenseTalk | SenseTalk | repeat with each line of file "input.txt"
put it
end repeat
|
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.
| #Sidef | Sidef | File(__FILE__).open_r.each { |line|
print 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
... | #Scheme | Scheme | (define (string-reverse s)
(list->string (reverse (string->list s)))) |
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... | #Klingphix | Klingphix | { include ..\Utilitys.tlhy }
"..\Utilitys.tlhy" load
:push! { l i -- l&i }
0 put
;
:empty? { l -- flag }
len not { len 0 equal }
;
:pop! { l -- l-1 }
empty? (
["Empty"]
[pop swap]
) if
;
( ) { empty queue }
1 push! 2 push! 3 push!
pop! ? pop! ? pop! ? pop! ?
"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... | #Nim | Nim | import math, tables
type Quaternion* = object
a, b, c, d: float
func initQuaternion*(a, b, c, d = 0.0): Quaternion =
Quaternion(a: a, b: b, c: c, d: d)
func `-`*(q: Quaternion): Quaternion =
initQuaternion(-q.a, -q.b, -q.c, -q.d)
func `+`*(q: Quaternion; r: float): Quaternion =
initQuaternion(q.a + r, q... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Factor | Factor | "%s [ 34 1string dup surround ] keep printf" [ 34 1string dup surround ] keep printf |
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... | #Objeck | Objeck | class IdentityMatrix {
function : Main(args : String[]) ~ Nil {
Compress2Range("-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20")->PrintLine();
Compress2Range("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... |
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
| #Standard_ML | Standard ML | val seed = 0w42;
val gen = Rand.mkRandom seed;
fun random_gaussian () =
1.0 + Math.sqrt (~2.0 * Math.ln (Rand.norm (gen ()))) * Math.cos (2.0 * Math.pi * Rand.norm (gen ()));
val a = List.tabulate (1000, fn _ => random_gaussian ()); |
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
| #Stata | Stata | clear all
set obs 1000
gen x=rnormal(1,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... | #Sidef | Sidef | var fullname = (var favouritefruit = "");
var needspeeling = (var seedsremoved = false);
var otherfamily = [];
ARGF.each { |line|
var(key, value) = line.strip.split(/\h+/, 2)...;
given(key) {
when (nil) { }
when (/^([#;]|\h*$)/) { }
when ("FULLNAME") { fullname =... |
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... | #S-lang | S-lang | variable r_expres = "-6,-3--1,3-5,7-11,14,15,17-20", s, r_expan = {}, dpos, i;
foreach s (strchop(r_expres, ',', 0))
{
% S-Lang built-in RE's are fairly limited, and have a quirk:
% grouping is done with \\( and \\), not ( and )
% [PCRE and Oniguruma RE's are available via standard libraries]
if (string_mat... |
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... | #Scala | Scala | def rangex(str: String): Seq[Int] =
str split "," flatMap { (s) =>
val r = """(-?\d+)(?:-(-?\d+))?""".r
val r(a,b) = s
if (b == null) Seq(a.toInt) else a.toInt to b.toInt
} |
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.
| #Smalltalk | Smalltalk |
(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ]
|
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.
| #SNOBOL4 | SNOBOL4 | input(.infile,20,"readfrom.txt") :f(end)
rdloop output = infile :s(rdloop)
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
... | #Scratch | Scratch | #!/bin/sed -f
/../! b
# Reverse a line. Begin embedding the line between two newlines
s/^.*$/\
&\
/
# Move first character at the end. The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
# Remove the newline markers
s/\n//g |
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... | #Kotlin | Kotlin | // version 1.1.2
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queu... |
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... | #OCaml | OCaml |
type quaternion = {a: float; b: float; c: float; d: float}
let norm q = sqrt (q.a**2.0 +.
q.b**2.0 +.
q.c**2.0 +.
q.d**2.0 )
let floatneg r = ~-. r (* readability *)
let negative q =
{a = floatneg q.a;
b = floatneg q.b;
c = floatneg q.c;
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 ... | #FALSE | FALSE | ["'[,34,$!34,'],!"]'[,34,$!34,'],! |
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... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
NSString *extractRanges(NSArray *nums) {
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
for (NSNumber *n in nums) {
if ([n integerValue] < 0)
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"negative number not supported" userIn... |
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
| #Tcl | Tcl | package require Tcl 8.5
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
expr {sqrt(-2*log(rand())) * cos(2*$::pi*rand())}
}
set mean 1.0
set stddev 0.5
for {set i 0} {$i < 1000} {incr i} {
lappend result [expr {$mean + $stddev*nrand()}]
} |
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... | #Smalltalk | Smalltalk | dict := Dictionary new.
configFile asFilename readingLinesDo:[:line |
(line isEmpty or:[ line startsWithAnyOf:#('#' ';') ]) ifFalse:[
s := line readStream.
(s skipSeparators; atEnd) ifFalse:[
|optionName values|
optionName := s upToSeparator.
values := (s upToEnd ... |
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... | #Scheme | Scheme | (define split
(lambda (str char skip count)
(let ((len (string-length str)))
(let loop ((index skip)
(last-index 0)
(result '()))
(if (= index len)
(reverse (cons (substring str last-index) result))
(if (eq? char (string-ref str index))
... |
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.
| #Sparkling | Sparkling | let f = fopen("foo.txt", "r");
if f != nil {
var line;
while (line = fgetline(f)) != nil {
print(line);
}
fclose(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
... | #Sed | Sed | #!/bin/sed -f
/../! b
# Reverse a line. Begin embedding the line between two newlines
s/^.*$/\
&\
/
# Move first character at the end. The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
# Remove the newline markers
s/\n//g |
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... | #LabVIEW | LabVIEW | define myqueue => type {
data store = list
public onCreate(...) => {
if(void != #rest) => {
with item in #rest do .`store`->insert(#item)
}
}
public push(value) => .`store`->insertLast(#value)
public pop => {
handle => {
.`store`->removefirst
... |
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... | #Octave | Octave | pkg install -forge quaternion |
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 ... | #Fish | Fish | 00000000000000000000++++++++++++++++++ v
2[$:{:@]$g:0=?v >o:4a*=?!v~1+:3=?;0ao>
>~" "^ >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... | #OCaml | OCaml | let range_extract = function
| [] -> []
| x::xs ->
let f (i,j,ret) k =
if k = succ j then (i,k,ret) else (k,k,(i,j)::ret) in
let (m,n,ret) = List.fold_left f (x,x,[]) xs in
List.rev ((m,n)::ret)
let string_of_range rng =
let str (a,b) =
if a = b then string_of_int a
else Printf.sprintf... |
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
| #TI-83_BASIC | TI-83 BASIC | randNorm(1,.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
| #TorqueScript | TorqueScript | for (%i = 0; %i < 1000; %i++)
%list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom()); |
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... | #Tcl | Tcl | proc readConfig {filename {defaults {}}} {
global cfg
# Read the file in
set f [open $filename]
set contents [read $f]
close $f
# Set up the defaults, if supplied
foreach {var defaultValue} $defaults {
set cfg($var) $defaultValue
}
# Parse the file's contents
foreach line [split... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.