task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Vedit_macro_language | Vedit macro language | File_Open("example.txt", BROWSE)
Goto_Line(7)
if (Cur_Line < 7) {
Statline_Message("File contains too few lines")
} else {
if (At_EOL) {
Statline_Message("Empty line")
}
Reg_Copy(10, 1)
}
Buf_Close(NOMSG) |
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
... | #Factor | Factor | USING: combinators kernel make math locals prettyprint sequences ;
IN: rosetta-code.quickselect
:: quickselect ( k seq -- n )
seq unclip :> ( xs x )
xs [ x < ] partition :> ( ys zs )
ys length :> l
{
{ [ k l < ] [ k ys quickselect ] }
{ [ k l > ] [ k l - 1 - zs quickselect ] }
... |
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
... | #Fortran | Fortran | INTEGER FUNCTION FINDELEMENT(K,A,N) !I know I can.
Chase an order statistic: FindElement(N/2,A,N) leads to the median, with some odd/even caution.
Careful! The array is shuffled: for i < K, A(i) <= A(K); for i > K, A(i) >= A(K).
Charles Anthony Richard Hoare devised this method, as related to his famous QuickSort... |
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... | #Erlang | Erlang |
-module( range ).
-export( [extraction/1, task/0] ).
extraction( [H | T] ) when is_integer(H) ->
Reversed_extracts = extraction_acc( lists:foldl(fun extraction/2, {H, []}, T) ),
string:join( lists:reverse(Reversed_extracts), "," ).
task() ->
io:fwrite( "~p~n", [extraction([0, 1, 2, 4, 6, 7, ... |
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
| #Java | Java | double[] list = new double[1000];
double mean = 1.0, std = 0.5;
Random rng = new Random();
for(int i = 0;i<list.length;i++) {
list[i] = mean + std * rng.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
| #JavaScript | JavaScript | function randomNormal() {
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
var a = []
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
} |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Tcl | Tcl | rand |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #TI-83_BASIC | TI-83 BASIC | rand |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #TXR | TXR | echo $RANDOM |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #UNIX_Shell | UNIX Shell | echo $RANDOM |
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... | #Ksh | Ksh |
#!/bin/ksh
# Read a configuration file
# # Variables:
#
# # The configuration file (below) could be read in from a file
# But this method keeps everything together.
# e.g. config=$(< /path/to/config_file)
integer config_num=0
config='# This is a configuration file in standard configuration file format
#
# L... |
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... | #Haskell | Haskell | > expandRange "-6,-3--1,3-5,7-11,14,15,17-20"
[-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.
| #Groovy | Groovy | new File("Test.txt").eachLine { line, lineNumber ->
println "processing line $lineNumber: $line"
} |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Haskell | Haskell | main = do
file <- readFile "linebyline.hs"
mapM_ putStrLn (lines file)
|
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Wren | Wren | import "/math" for Nums
import "/fmt" for Fmt
/* all ranking functions assume the array of Pairs is non-empty and already sorted
by decreasing order of scores and then, if the scores are equal, by reverse
alphabetic order of names
*/
var standardRanking = Fn.new { |scores|
var rankings = List.filled(scor... |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Plain_TeX | Plain TeX | \def\gobtoA#1\revA{}\def\gobtoB#1\revB{}
\def\reverse#1{\reversei{}#1\revA\revB\revB\revB\revB\revB\revB\revB\revB\revA}
\def\reversei#1#2#3#4#5#6#7#8#9{\gobtoB#9\revend\revB\reversei{#9#8#7#6#5#4#3#2#1}}
\def\revend\revB\reversei#1#2\revA{\gobtoA#1}
\reverse{Rosetta}
\bye |
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... | #Bracmat | Bracmat | ( queue
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
( dequeue
= x
. !(its.list):?(its.list) (.?x)
& !x
)
(empty=.!(its.list):)
) |
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... | #Common_Lisp | Common Lisp |
(defclass quaternion () ((a :accessor q-a :initarg :a :type real)
(b :accessor q-b :initarg :b :type real)
(c :accessor q-c :initarg :c :type real)
(d :accessor q-d :initarg :d :type real))
(:default-initargs :a 0 :b 0 :c 0 :d 0))
(defun ... |
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 ... | #beeswax | beeswax | _4~++~+.@1~0@D@1J |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
Declare_Queue(String) '' expand Queue type for Strings
Dim stringQueue As Queue(String)
With stringQueue '' push some strings into the Queue
.push("first")
.push("second")
.push("third")
.push("f... |
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... | #Go | Go | package main
import (
"fmt"
"queue"
)
func main() {
q := new(queue.Queue)
fmt.Println("empty?", q.Empty())
x := "black"
fmt.Println("push", x)
q.Push(x)
fmt.Println("empty?", q.Empty())
r, ok := q.Pop()
if ok {
fmt.Println(r, "popped")
} else {
fmt.Pri... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Wren | Wren | import "io" for File
var lines = File.read("input.txt").replace("\r", "").split("\n")
if (lines.count < 7) {
System.print("There are only %(lines.count) lines in the file")
} else {
var line7 = lines[6].trim()
if (line7 == "") {
System.print("The seventh line is empty")
} else {
System... |
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
... | #FreeBASIC | FreeBASIC |
Dim Shared As Long array(9), pivote
Function QuickPartition (array() As Long, izda As Long, dcha As Long, pivote As Long) As Long
Dim As Long pivotValue = array(pivote)
Swap array(pivote), array(dcha)
Dim As Long indice = izda
For i As Long = izda To dcha-1
If array(i) < pivotValue Then
... |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Euphoria | Euphoria | function extract_ranges(sequence s)
integer first
sequence out
out = ""
if length(s) = 0 then
return out
end if
first = 1
for i = 2 to length(s) do
if s[i] != s[i-1]+1 then
if first = i-1 then
out &= sprintf("%d,", s[first])
elsif first... |
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
| #jq | jq | # 15-bit integers generated using the same formula as rand() from the Microsoft C Runtime.
# The random numbers are in [0 -- 32767] inclusive.
# Input: an array of length at least 2 interpreted as [count, state, ...]
# Output: [count+1, newstate, r] where r is the next pseudo-random number.
def next_rand_Microsoft:
.... |
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
| #Julia | Julia | randn(1000) * 0.5 + 1 |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Ursa | Ursa | include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
] |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Ursala | Ursala | include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
] |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Wee_Basic | Wee Basic | include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
] |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Wren | Wren | include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
] |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Lasso | Lasso | local(config = '# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FA... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
s := "-6,-3--1,3-5,7-11,14,15,17-20"
write("Input string := ",s)
write("Expanded list := ", list2string(range_expand(s)) | "FAILED")
end
procedure range_expand(s) #: return list of integers extracted from an ordered string representation
local R,low,high
R := []
s ? until pos(0) do ... |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
f := open("input.txt","r") | stop("cannot open file ",fn)
while line := read(f)
close(f)
end |
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.
| #J | J | cocurrent 'linereader'
NB. configuration parameter
blocksize=: 400000
NB. implementation
offset=: 0
position=: 0
buffer=: ''
lines=: ''
create=: monad define
name=: boxxopen y
size=: 1!:4 name
blocks=: 2 <@(-~/\)\ ~. size <. blocksize * i. 1 + >. size % blocksize
)
readblocks=: m... |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Yabasic | Yabasic |
n = 7
dim puntos(7), ptosnom(7), nombre$(7)
sub MostarTabla()
for i = 1 to n
print str$(ptosnom(i)), " ", puntos(i), " ", nombre$(i)
next i
print
end sub
print "Puntuaciones a clasificar (mejores primero):"
for i = 1 to n
read puntos(i), nombre$(i)
print " ", puntos(i), " ", n... |
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
... | #Pop11 | Pop11 | define reverse_string(s);
lvars i, l = length(s);
for i from l by -1 to 1 do
s(i);
endfor;
consstring(l);
enddefine; |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA; /* type of data to store in queue */
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = ... |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #Crystal | Crystal | class Quaternion
property a, b, c, d
def initialize(@a : Int64, @b : Int64, @c : Int64, @d : Int64) end
def norm; Math.sqrt(a**2 + b**2 + c**2 + d**2) end
def conj; Quaternion.new(a, -b, -c, -d) end
def +(n) Quaternion.new(a + n, b, c, d) end
def -(n) Quaternion.new(a - n, 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 ... | #Befunge | Befunge | :0g,:66+`#@_1+ |
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... | #Groovy | Groovy | def q = new LinkedList() |
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... | #Haskell | Haskell |
Prelude> :l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Ok, modules loaded: Main.
*Main> let q = emptyFifo
*Main> isEmpty q
True
*Main> let q' = push q 1
*Main> isEmpty q'
False
*Main> let q'' = foldl push q' [2..4]
*Main> let (v,q''') = pop q''
*Main> v
Just 1
*Main> let (v',q'''') = pop q''... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)
func ReadLine(N, L); \Read line N from input file and return it in string L
int N; char L;
int I, C;
[for I:= 1 to N-1 do \skip to start of specified line
repeat C:=... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #zkl | zkl | reg line; do(7){line=File.stdin.readln()} println(">>>",line); |
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
... | #Go | Go | package main
import "fmt"
func quickselect(list []int, k int) int {
for {
// partition
px := len(list) / 2
pv := list[px]
last := len(list) - 1
list[px], list[last] = list[last], list[px]
i := 0
for j := 0; j < last; j++ {
if list[j] < pv {
... |
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... | #F.23 | F# | let extractRanges = function
| [] -> Seq.empty
| x::xr ->
let rec loop ys first last = seq {
match ys with
| y::yr when y = last + 1 -> yield! loop yr first y // add to current range
| y::yr -> yield (first, last) // finish current range
... |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val da = DoubleArray(1000)
for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian()
// now check actual mean and SD
val mean = da.average()
val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.a... |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
] |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #zkl | zkl | ld a,r |
http://rosettacode.org/wiki/Random_number_generator_(included) | Random number generator (included) | The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not t... | #Z80_Assembly | Z80 Assembly | ld a,r |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Liberty_BASIC | Liberty BASIC |
dim confKeys$(100)
dim confValues$(100)
optionCount = ParseConfiguration("a.txt")
fullName$ = GetOption$( "FULLNAME", optionCount)
favouriteFruit$ = GetOption$( "FAVOURITEFRUIT", optionCount)
needsPeeling = HasOption("NEEDSPEELING", optionCount)
seedsRemoved = HasOption("SEEDSREMOVED", optionCount)
otherFamily$ =... |
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... | #J | J | require'strings'
thru=: <. + i.@(+*)@-~
num=: _&".
normaliz=: rplc&(',-';',_';'--';'-_')@,~&','
subranges=:<@(thru/)@(num;._2)@,&'-';._1
rngexp=: ;@subranges@normaliz |
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.
| #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
/**
* Reads a file line by line, processing each line.
*
* @author $Author$
* @version $Revision$
*/
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
// ...
}
public static void main(String[]... |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #zkl | zkl | fcn group(scores){ // group like scores into one list --> list of lists
sink:=List();
scores.reduce('wrap(ps,sn,buf){
if(sn[0]!=ps){ sink.append(buf.copy()); buf.clear(); }
buf+sn;
sn[0];
},scores[0][0],buf:=List());
sink.append(buf);
}
fcn print(list,rank){
list.apply2('wrap(sn){ "%2s:... |
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
... | #PostScript | PostScript | /reverse{
/str exch def
/temp str 0 get def
/i 0 def
str length 2 idiv{
/temp str i get def
str i str str length i sub 1 sub get put
str str length i sub 1 sub temp put
/i i 1 add def
}repeat
str pstack
}def |
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... | #C.23 | C# | public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
//Uses object initializers to set fields of new node
first = new Node() { Item = item, Next = null };
... |
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... | #D | D | import std.math, std.numeric, std.traits, std.conv, std.complex;
struct Quat(T) if (isFloatingPoint!T) {
alias CT = Complex!T;
union {
struct { T re, i, j, k; } // Default init to NaN.
struct { CT x, y; }
struct { T[4] vector; }
}
string toString() const pure /*nothrow*/ ... |
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 ... | #Binary_Lambda_Calculus | Binary Lambda Calculus | 000101100100011010000000000001011011110010111100111111011111011010000101100100011010000000000001011011110010111100111111011111011010 |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
queue := []
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
write("Queue is:")
every x := !arglist do {
case x of {
"-" : pop(queue) | write("pop(empty) failed.") # pop if the next arglist[i] is a -
default : put(queue,x) ... |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #J | J | queue=: conew 'fifo'
isEmpty__queue ''
1
push__queue 9
9
push__queue 8
8
push__queue 7
7
isEmpty__queue ''
0
pop__queue ''
9
pop__queue ''
8
pop__queue ''
7
isEmpty__queue ''
1 |
http://rosettacode.org/wiki/Quickselect_algorithm | Quickselect algorithm |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Haskell | Haskell | import Data.List (partition)
quickselect
:: Ord a
=> [a] -> Int -> a
quickselect (x:xs) k
| k < l = quickselect ys k
| k > l = quickselect zs (k - l - 1)
| otherwise = x
where
(ys, zs) = partition (< x) xs
l = length ys
main :: IO ()
main =
print
((fmap . quickselect) <*> zipWith const [0 ... |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Factor | Factor | USING: formatting io kernel math math.parser sequences
splitting.monotonic ;
IN: rosetta-code.range-extraction
: make-range ( seq -- str )
[ first ] [ last ] bi "%d-%d" sprintf ;
: make-atomic ( seq -- str ) [ number>string ] map "," join ;
: extract-range ( seq -- str )
[ - -1 = ] monotonic-split
[ d... |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #LabVIEW | LabVIEW | dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000 ' throw 1000 normal variates
a( i) =mean +sd *( 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
| #Liberty_BASIC | Liberty BASIC | dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000 ' throw 1000 normal variates
a( i) =mean +sd *( sqr( -2 * log( rnd( 0))) * cos( 2 * pi * rnd( 0)))
next i |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Lua | Lua | conf = {}
fp = io.open( "conf.txt", "r" )
for line in fp:lines() do
line = line:match( "%s*(.+)" )
if line and line:sub( 1, 1 ) ~= "#" and line:sub( 1, 1 ) ~= ";" then
option = line:match( "%S+" ):lower()
value = line:match( "%S*%s*(.*)" )
if not value then
conf[option] = true
else
if not... |
http://rosettacode.org/wiki/Range_expansion | Range expansion | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Java | Java | import java.util.*;
class RangeExpander implements Iterator<Integer>, Iterable<Integer> {
private static final Pattern TOKEN_PATTERN = Pattern.compile("([+-]?\\d+)-([+-]?\\d+)");
private final Iterator<String> tokensIterator;
private boolean inRange;
private int upperRangeEndpoint;
private i... |
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.
| #JavaScript | JavaScript | var fs = require("fs");
var readFile = function(path) {
return fs.readFileSync(path).toString();
};
console.log(readFile('file.txt')); |
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.
| #jq | jq | $ seq 0 5 | jq -R 'tonumber|sin'
0
0.8414709848078965
0.9092974268256817
0.1411200080598672
-0.7568024953079282
-0.9589242746631385 |
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
... | #PowerBASIC | PowerBASIC | #DIM ALL
#COMPILER PBCC 6
FUNCTION PBMAIN () AS LONG
CON.PRINT STRREVERSE$("PowerBASIC")
END FUNCTION |
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... | #C.2B.2B | C++ | namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
... |
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... | #Delphi | Delphi | unit Quaternions;
interface
type
TQuaternion = record
A, B, C, D: double;
function Init (aA, aB, aC, aD : double): TQuaternion;
function Norm : double;
function Conjugate : TQuaternion;
function ToString : string;
class operator Negative (Left : TQuater... |
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 ... | #Bob | Bob | c=","; n="\n"; q="\""; s="\\";
v=\[
"c=\",\"; n=\"\\n\"; q=\"\\\"\"; s=\"\\\\\";",
"v=\\[",
"define prtQuote(str) {",
" local j,t,v;",
" stdout.Display(q);",
" for (j=0; j<str.size; j++) {",
" t = str.Substring(j,1);",
" if (t==q) { stdout.Display(s); }",
" if (t==s) { stdout.Display(s); }",
" stdout.Display(t);",
... |
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... | #Java | Java | import java.util.LinkedList;
import java.util.Queue;
...
Queue<Integer> queue = new LinkedList<Integer>();
System.out.println(queue.isEmpty()); // empty test - true
// queue.remove(); // would throw NoSuchElementException
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue); // ... |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #JavaScript | JavaScript | var f = new Array();
print(f.length);
f.push(1,2); // can take multiple arguments
f.push(3);
f.shift();
f.shift();
print(f.length);
print(f.shift())
print(f.length == 0);
print(f.shift()); |
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
... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every writes(" ",select(1 to *A, A, 1, *A)|"\n")
end
procedure select(k,A,min,max)
repeat {
pNI := partition(?(max-min)+min, A, min, max)
pD := pNI - min + 1
if pD = k then return A[pNI]
if k < pD then max := pNI-1
else (k -:= pD, min := pNI+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... | #Forth | Forth | create values
here
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 ,
here swap - 1 cells / constant /values
: clip 1- swap cell+ swap ; \ reduce array
: .range2 0 .r ." -" 0 .r ; ... |
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
| #Lingo | Lingo | -- Returns a random float value in range 0..1
on randf ()
n = random(the maxinteger)-1
return n / float(the maxinteger-1)
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
| #Lobster | Lobster |
let mean = 1.0
let stdv = 0.5
let count = 1000
// stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
def stats(xs: [float]) -> float, float: // variance, mean
var M = xs[0]
var S = 0.0
var n = 1.0
for(xs.length - 1) i:
let x = xs[i + 1]
n = ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CreateVar, ImportConfig];
CreateVar[x_, y_String: "True"] := Module[{},
If[StringFreeQ[y, ","]
,
ToExpression[x <> "=" <> y]
,
ToExpression[x <> "={" <> StringJoin@Riffle[StringSplit[y, ","], ","] <> "}"]
]
]
ImportConfig[configfile_String] := Module[{data},
(*data = ImportString[configfil... |
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... | #JavaScript | JavaScript | #!/usr/bin/env js
function main() {
print(rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20'));
}
function rangeExpand(rangeExpr) {
function getFactors(term) {
var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);
if (!matches) return {first:Number(term)};
return {first:Number(matches[1]), l... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Jsish | Jsish | /* Read by line, in Jsish */
var f = new Channel('read-by-line.jsi');
var line;
while (line = f.gets()) puts(line);
f.close(); |
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.
| #Julia | Julia | open("input_file","r") do f
for line in eachline(f)
println("read line: ", line)
end
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
... | #PowerShell | PowerShell | $s = "asdf" |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operation... | #Clojure | Clojure |
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY)
#'user/empty-queue
user=> (def aqueue (atom empty-queue))
#'user/aqueue
; Check if queue is empty
user=> (empty? @aqueue)
true
; As with other Clojure data structures, you can add items using conj and into
user=> (swap! aqueue conj 1)
user=> (swap! aqueue ... |
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... | #E | E | interface Quaternion guards QS {}
def makeQuaternion(a, b, c, d) {
return def quaternion implements QS {
to __printOn(out) {
out.print("(", a, " + ", b, "i + ")
out.print(c, "j + ", d, "k)")
}
# Task requirement 1
to norm() {
return (a**2 + b**... |
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 ... | #bootBASIC | bootBASIC | 10 list |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Julia | Julia | using DataStructures
queue = Queue(String)
@show enqueue!(queue, "foo")
@show enqueue!(queue, "bar")
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> bar |
http://rosettacode.org/wiki/Queue/Usage | Queue/Usage |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Ope... | #Kotlin | Kotlin | // version 1.1.2
import java.util.*
fun main(args: Array<String>) {
val q: Queue<Int> = ArrayDeque<Int>()
(1..5).forEach { q.add(it) }
println(q)
println("Size of queue = ${q.size}")
print("Removing: ")
(1..3).forEach { print("${q.remove()} ") }
println("\nRemaining in queue: $q")
pr... |
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
... | #J | J | quickselect=:4 :0
if. 0=#y do. _ return. end.
n=.?#y
m=.n{y
if. x < m do.
x quickselect (m>y)#y
else.
if. x > m do.
x quickselect (m<y)#y
else.
m
end.
end.
) |
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
... | #Java | Java | import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) ... |
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Fortran | Fortran | SUBROUTINE IRANGE(TEXT) !Identifies integer ranges in a list of integers.
Could make this a function, but then a maximum text length returned would have to be specified.
CHARACTER*(*) TEXT !The list on input, the list with ranges on output.
INTEGER LOTS !Once again, how long is a piece of string?
... |
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
| #Logo | Logo | to random.float ; 0..1
localmake "max.int lshift -1 -1
output quotient random :max.int :max.int
end
to random.gaussian
output product cos random 360 sqrt -2 / ln random.float
end
make "randoms cascade 1000 [fput random.gaussian / 2 + 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
| #Lua | Lua | local list = {}
for i = 1, 1000 do
list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function R = readconf(configfile)
% READCONF reads configuration file.
%
% The value of boolean parameters can be tested with
% exist(parameter,'var')
if nargin<1,
configfile = 'q.conf';
end;
fid = fopen(configfile);
if fid<0, error('cannot open file %s\n',a); end;
while ~feof(fid)
line = strtrim(f... |
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... | #jq | jq | def expand_range:
def number: "-?[0-9]+";
def expand: [range(.[0]; .[1] + 1)];
split(",")
| reduce .[] as $r
( []; . +
($r | if test("^\(number)$") then [tonumber]
else sub( "(?<x>\(number))-(?<y>\(number))"; "\(.x):\(.y)")
| split(":") | map(tonumber) | e... |
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... | #Jsish | Jsish | #!/usr/bin/env jsish
"use strict";
/* Range expansion, in Jsish */
function rangeExpand(rangeExpr) {
function getFactors(term) {
var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);
if (!matches) return {first:Number(term)};
return {first:Number(matches[1]), last:Number(matches[2])};
... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun main(args: Array<String>) {
File("input.txt").forEachLine { println(it) }
} |
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.
| #Lasso | Lasso | local(f) = file('foo.txt')
handle => {#f->close}
#f->forEachLine => {^
#1
'<br>' // note this simply inserts an HTML line break between each 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
... | #Prolog | Prolog | reverse("abcd", L), string_to_list(S,L). |
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... | #CoffeeScript | CoffeeScript |
# Implement a fifo as an array of arrays, to
# greatly amortize dequeue costs, at some expense of
# memory overhead and insertion time. The speedup
# depends on the underlying JS implementation, but
# it's significant on node.js.
Fifo = ->
max_chunk = 512
arr = [] # array of arrays
count = 0
self =
enq... |
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... | #Eero | Eero | #import <Foundation/Foundation.h>
interface Quaternion : Number
// Properties -- note that this is an immutable class.
double real, i, j, k {readonly}
end
implementation Quaternion
initWithReal: double, i: double, j: double, k: double, return instancetype
self = super.init
if self
_real = real... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.