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/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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "scanstri.s7i";
const func array integer: rangeExpansion (in var string: rangeStri) is func
result
var array integer: numbers is 0 times 0;
local
var integer: number is 0;
begin
while rangeStri <> "" do
number := integer parse getInteger(rangeStri);
nu... |
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... | #Sidef | Sidef | func rangex(str) {
str.split(',').map { |r|
var m = r.match(/^
(?(DEFINE) (?<int>[+-]?[0-9]+) )
(?<from>(?&int))-(?<to>(?&int))
$/x)
m ? do {var c = m.ncap; (Num(c{:from}) .. Num(c{:to}))...}
: Num(r)
}
}
say rangex('-6,-3--1,3-5,7-11,14,15,17-20').joi... |
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.
| #SPL | SPL | f = "file.txt"
> !#.eof(f)
#.output(#.readline(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
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: reverse (in string: stri) is func
result
var string: result is "";
local
var integer: index is 0;
begin
for index range length(stri) downto 1 do
result &:= stri[index];
end for;
end func;
const proc: main is func
begin
writeln(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... | #Lasso | Lasso | 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... | #Oforth | Oforth | 160 Number Class newPriority: Quaternion(a, b, c, d)
Quaternion method: _a @a ;
Quaternion method: _b @b ;
Quaternion method: _c @c ;
Quaternion method: _d @d ;
Quaternion method: initialize := d := c := b := a ;
Quaternion method: << '(' <<c @a << ',' <<c @b << ',' <<c @c << ',' <<c @d << ')' <<c ;
Integer... |
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 ... | #Forth | Forth | SOURCE TYPE |
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... | #Ol | Ol |
(define (extract ll)
(let loop ((head (car ll)) (tail (cdr ll)) (out #null))
(if (null? tail)
(reverse (cons head out))
else
(cond
((eq? head (- (car tail) 1))
(loop (list (car tail) head) (cdr tail) out))
((and (pair? head) (eq? (car head) (- (c... |
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
| #Ursala | Ursala | #import nat
#import flo
pop_stats("mu","sigma") = plus/*"mu"+ times/*"sigma"+ Z*+ iota
sample_stats("mu","sigma") = plus^*D(minus/"mu"+ mean,~&)+ vid^*D(div\"sigma"+ stdev,~&)+ Z*+ iota
#cast %eWL
test =
^(mean,stdev)* <
pop_stats(1.,0.5) 1000,
sample_stats(1.,0.5) 1000> |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #TXR | TXR | @(collect)
@ (cases)
#@/.*/
@ (or)
;@/.*/
@ (or)
@{IDENT /[A-Z_][A-Z_0-9]+/}@/ */
@(bind VAL ("true"))
@ (or)
@{IDENT /[A-Z_][A-Z_0-9]+/}@(coll)@/ */@{VAL /[^,]+/}@/ */@(end)
@ (or)
@{IDENT /[A-Z_][A-Z_0-9]+/}@(coll)@/ */@{VAL /[^, ]+/}@/,? */@(end)
@(flatten VAL)
@ (or)
@/ */
@ (or)
@ (throw error "bad configu... |
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... | #SNOBOL4 | SNOBOL4 | * # Return range n1 .. n2
define('range(n1,n2)') :(range_end)
range range = range n1 ','; n1 = lt(n1,n2) n1 + 1 :s(range)
range rtab(1) . range :(return)
range_end
define('rangex(range)d1,d2')
num = ('-' | '') span('0123456789') :(rangex_end)
rangex range num ... |
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.
| #Tcl | Tcl | set f [open "foobar.txt"]
while {[gets $f line] >= 0} {
# This loops over every line
puts ">>$line<<"
}
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.
| #TorqueScript | TorqueScript |
//Create a file object
%f = new fileObject();
//Open and read a file
%f.openForRead("PATH/PATH.txt");
while(!%f.isEOF())
{
//Read each line from our file
%line = %f.readLine();
}
//Close the file object
%f.close();
//Delete the file object
%f.delete();
|
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
... | #Self | Self | 'asdf' copyMutable 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... | #Lua | Lua | Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[q... |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #ooRexx | ooRexx |
q = .quaternion~new(1, 2, 3, 4)
q1 = .quaternion~new(2, 3, 4, 5)
q2 = .quaternion~new(3, 4, 5, 6)
r = 7
say "q =" q
say "q1 =" q1
say "q2 =" q2
say "r =" r
say "norm(q) =" q~norm
say "-q =" (-q)
say "q* =" q~conjugate
say "q + r =" q + r
say ... |
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 ... | #Fortran | Fortran | character*46::s='("character*46::s=",3a,";print s,39,s,39;end")';print s,39,s,39;end |
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... | #ooRexx | ooRexx | /* Rexx */
parse arg userInput
call runSample userInput
return
exit
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- Compact a list of numbers by reducing ranges
compact:
procedure
--trace ?r;nop
parse arg expanded
nums = expanded~changestr(',', ' ')~space -- remove possible c... |
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
| #Visual_FoxPro | Visual FoxPro |
LOCAL i As Integer, m As Double, n As Integer, sd As Double
py = PI()
SET TALK OFF
SET DECIMALS TO 6
CREATE CURSOR gdev (deviate B(6))
RAND(-1)
n = 1000
m = 1
sd = 0.5
CLEAR
FOR i = 1 TO n
INSERT INTO gdev VALUES (GaussDev(m, 1/sd))
ENDFOR
CALCULATE AVG(deviate), STD(deviate) TO m, sd
? "Mean", m, "Std Dev", sd
SET... |
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
| #Wren | Wren | import "random" for Random
var rand = Random.new()
var randNormal = Fn.new { (-2 * rand.float().log).sqrt * (2 * Num.pi * rand.float()).cos }
var stdDev = Fn.new { |a, m|
var c = a.count
return ((a.reduce(0) { |acc, x| acc + x*x } - m*m*c) / c).sqrt
}
var n = 1000
var numbers = List.filled(n, 0)
var mu ... |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #UNIX_Shell | UNIX Shell | readconfig() (
# redirect stdin to read from the given filename
exec 0<"$1"
declare -l varname
while IFS=$' =\t' read -ra words; do
# is it a comment or blank line?
if [[ ${#words[@]} -eq 0 || ${words[0]} == ["#;"]* ]]; then
continue
fi
# get the variable ... |
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... | #Tailspin | Tailspin |
composer expand
[<element>*]
rule element: <range|INT> (<','>?)
rule range: (def start: <INT>; <'-'>) <INT> -> $start..$
end expand
'-6,-3--1,3-5,7-11,14,15,17-20' -> expand -> !OUT::write
|
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.
| #Turing | Turing | var f : int
open : f, "rosetta.txt", get
loop
exit when eof (f)
var line: string
get : f, line:*
put line
end loop
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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
datei="rosetta.txt"
ERROR/STOP OPEN (datei,READ,-std-)
ACCESS q: READ/RECORDS/UTF8 $datei s,line
LOOP
READ/NEXT/EXIT q
PRINT line
ENDLOOP
ENDACCESS q
|
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
... | #SenseTalk | SenseTalk | put "asdf" reversed -- reverse on the fly
set imp to "rumpelstiltskin"
reverse imp -- reverse in place
put imp
|
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... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
a=Stack
Stack a {
Data 100,200, 300
}
Stack a {
While not empty {
Read N
Print N
}
}
}
Checkit
|
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... | #PARI.2FGP | PARI/GP | q.norm={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
sqrt(q[1]^2+q[2]^2+q[3]^2+q[4]^2)
};
q.conj={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
-[-q[1],q[2],q[3],q[4]]
};
q.add={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
x->if(type(x) == "t_INT" || type(x) == t_REA... |
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 ... | #Free_Pascal | Free Pascal | const s=';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s);readln;end.';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s);readln;end. |
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... | #OxygenBasic | OxygenBasic |
int ints(100)
ints={
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
}
' RESULT:
' 0-2, 4, 6-8, 11, 12, 14-25, 27-33, 35-39
function Ranges(int*i) as string
'===============================
string pr=""
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
| #Yorick | Yorick | func random_normal(count) {
return sqrt(-2*log(random(count))) * cos(2*pi*random(count));
} |
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
| #zkl | zkl | fcn mkRand(mean,sd){ //normally distributed random w/mean & standard deviation
pi:=(0.0).pi; // using the Box–Muller transform
rz1:=fcn{1.0-(0.0).random(1)} // from [0,1) to (0,1]
return('wrap(){((-2.0*rz1().log()).sqrt() * (2.0*pi*rz1()).cos())*sd + mean })
} |
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... | #VBScript | VBScript |
Set ofso = CreateObject("Scripting.FileSystemObject")
Set config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&"\config.txt",1)
config_out = ""
Do Until config.AtEndOfStream
line = config.ReadLine
If Left(line,1) <> "#" And Len(line) <> 0 Then
config_out = config_out & parse_var(line) &... |
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... | #Tcl | Tcl | proc rangeExpand desc {
set result {}
foreach term [split $desc ","] {
set count [scan $term %d-%d from to]
if {$count == 1} {
lappend result $from
} elseif {$count == 2} {
for {set i $from} {$i <= $to} {incr i} {lappend result $i}
}
}
return $result
}
puts [rangeExpand "-6,-3--1,3-5,7-1... |
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.
| #Ultimate.2B.2B | Ultimate++ | #include <Core/Core.h>
using namespace Upp;
CONSOLE_APP_MAIN
{
FileIn in(CommandLine()[0]);
while(in && !in.IsEof())
Cout().PutLine(in.GetLine());
} |
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
... | #SequenceL | SequenceL | import <Utilities/Sequence.sl>;
main(args(2)) := Sequence::reverse(args[1]); |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operation... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b] |
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... | #Pascal | Pascal | package Quaternion;
use List::Util 'reduce';
use List::MoreUtils 'pairwise';
sub make {
my $cls = shift;
if (@_ == 1) { return bless [ @_, 0, 0, 0 ] }
elsif (@_ == 4) { return bless [ @_ ] }
else { die "Bad number of components: @_" }
}
sub _abs { sqrt reduce { $a + $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 ... | #FreeBASIC | FreeBASIC | #Define P(X) Print X: Print "P(" & #X & ")"
P("#Define P(X) Print X: Print ""P("" & #X & "")""") |
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... | #Oz | Oz | declare
fun {Extract Xs}
{CommaSeparated
{Map {ExtractRanges Xs} RangeToString}}
end
fun {ExtractRanges Xs}
fun {Loop Ys Start End}
case Ys
of Y|Yr andthen Y == End+1 then {Loop Yr Start Y}
[] Y|Yr then Start#End|{Loop Yr Y Y}
[] nil ... |
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 RANDOMIZE 0 : REM seeds random number generator based on uptime
20 DIM a(1000)
30 CLS
40 FOR i = 1 TO 1000
50 LET a(i) = 1 + SQR(-2 * LN(RND)) * COS(2 * PI * RND)
60 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... | #Vedit_macro_language | Vedit macro language | #11 = 0 // needspeeling = FALSE
#12 = 0 // seedsremoved = FALSE
Reg_Empty(21) // fullname
Reg_Empty(22) // favouritefruit
Reg_Empty(23) // otherfamily
File_Open("|(PATH_ONLY)\example.cfg")
if (Search("|<FULLNAME|s", BEGIN+ADVANCE+NOERR)) {
Match("=",... |
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... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
rangednrs="-6,-3--1,3-5,7-11,14,15,17-20"
expandnrs=SPLIT (rangednrs,":,:")
LOOP/CLEAR r=expandnrs
test=STRINGS (r,":><-><<>>/:")
sz_test=SIZE (test)
IF (sz_test==1) THEN
expandnrs=APPEND (expandnrs,r)
ELSE
r=SPLIT (r,"::<|->/::-:",beg,end)
expandnrs=APPEND (expandnrs,beg)
LOOP/CLEAR next... |
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.
| #UNIX_Shell | UNIX Shell | # This while loop repeats for each line of the file.
# This loop is inside a pipeline; many shells will
# run this loop inside a subshell.
cat input.txt |
while IFS= read -r line ; do
printf '%s\n' "$line"
done |
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
... | #Sidef | Sidef | "asdf".reverse; # fdsa
"résumé niño".reverse; # oñin émusér |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | myfifo = {};
% push
myfifo{end+1} = x;
% pop
x = myfifo{1}; myfifo{1} = [];
% empty
isempty(myfifo) |
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... | #Perl | Perl | package Quaternion;
use List::Util 'reduce';
use List::MoreUtils 'pairwise';
sub make {
my $cls = shift;
if (@_ == 1) { return bless [ @_, 0, 0, 0 ] }
elsif (@_ == 4) { return bless [ @_ ] }
else { die "Bad number of components: @_" }
}
sub _abs { sqrt reduce { $a + $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 ... | #Frink | Frink | d="633d636861725b33345d3b653d643b7072696e745b22643d2463246424635c6e222b28653d7e25732f285b612d7a302d395d7b327d292f636861725b7061727365496e745b24312c31365d5d2f6567295d"
c=char[34];e=d;print["d=$c$d$c\n"+(e=~%s/([a-z0-9]{2})/char[parseInt[$1,16]]/eg)] |
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... | #Pascal | Pascal | program RangeExtractionApp;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
SysUtils;
function RangeExtraction(const Seq: array of integer): String;
const
SubSeqLen = 3; // minimal length of the range, can be changed.
var
i, j: Integer;... |
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... | #Visual_Basic | Visual Basic | ' Configuration file parser routines.
'
' (c) Copyright 1993 - 2011 Mark Hobley
'
' This configuration parser contains code ported from an application program
' written in Microsoft Quickbasic
'
' This code can be redistributed or modified under the terms of version 1.2 of
' the GNU Free Documentation Licence as publis... |
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... | #TXR | TXR | num := [ + | - ] { digit } +
entry := num [ ws ] - [ ws ] num
| num
rangelist := entry [ ws ] , [ ws ] rangelist
| entry
| /* empty */ |
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... | #UNIX_Shell | UNIX Shell | #!/usr/bin/bash
range_expand () (
IFS=,
set -- $1
n=$#
for element; do
if [[ $element =~ ^(-?[0-9]+)-(-?[0-9]+)$ ]]; then
set -- "$@" $(eval echo "{${BASH_REMATCH[1]}..${BASH_REMATCH[2]}}")
else
set -- "$@" $element
fi
done
shift $n
echo "$@"... |
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.
| #Ursa | Ursa | decl file f
f.open "filename.txt"
while (f.hasline)
out (in string f) endl console
end while |
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.
| #Vala | Vala |
public static void main(){
var file = FileStream.open("foo.txt", "r");
string line = file.read_line();
while (line != null){
stdout.printf("%s\n", line);
line = file.read_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
... | #Simula | Simula |
BEGIN
TEXT PROCEDURE REV(S); TEXT S;
BEGIN
TEXT T;
INTEGER L,R;
T :- COPY(S);
L := 1; R := T.LENGTH;
WHILE L < R DO
BEGIN
CHARACTER CL,CR;
T.SETPOS(L); CL := T.GETCHAR;
T.SETPOS(R); CR := T.GETCHAR;
T.SETPOS(L); T.PUTCHAR(CR);... |
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... | #Maxima | Maxima | defstruct(queue(in=[], out=[]))$
enqueue(x, q) := (q@in: cons(x, q@in), done)$
dequeue(q) := (if not emptyp(q@out) then first([first(q@out), q@out: rest(q@out)])
elseif emptyp(q@in) then 'fail
else (q@out: reverse(q@in), q@in: [], first([first(q@out), q@out: rest(q@out)])))$
q:new(queue); /* queue([], []) */
e... |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #Phix | Phix | with javascript_semantics
function norm(sequence q)
return sqrt(sum(sq_power(q,2)))
end function
function conjugate(sequence q)
q = deep_copy(q)
q[2..4] = sq_uminus(q[2..4])
return q
end function
function negative(sequence q)
return sq_uminus(q)
end function
function add(object q1, object q2)
... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | "#s sto selfstring QUOTE @selfstring dup print QUOTE NL printnl end { „selfstring” }"
#s sto selfstring QUOTE @selfstring dup print QUOTE NL printnl end { „selfstring” } |
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... | #Perl | Perl | sub rangext {
my $str = join ' ', @_;
1 while $str =~ s{([+-]?\d+) ([+-]?\d+)}
{$1.(abs($2 - $1) == 1 ? '~' : ',').$2}eg; # abs for neg ranges
$str =~ s/(\d+)~(?:[+-]?\d+~)+([+-]?\d+)/$1-$2/g;
$str =~ tr/~/,/;
return $str;
}
# Test and display
my @test = qw(0 1 2 4 6 7 8 11 12 14
... |
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... | #Wren | Wren | import "io" for File
import "/ioutil" for FileUtil
class Configuration {
construct new(map) {
_fullName = map["fullName"]
_favouriteFruit = map["favouriteFruit"]
_needsPeeling = map["needsPeeling"]
_seedsRemoved = map["seedsRemoved"]
_otherFamily = map["otherFa... |
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... | #Ursala | Ursala | #import std
#import int
rex = sep`,; zrange+*= %zp~~htttPzztPQhQXbiNC+ rlc ~&r~=`-
#cast %zL
t = rex '-6,-3--1,3-5,7-11,14,15,17-20' |
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... | #VBA | VBA | Public Function RangeExpand(AString as string)
' return a list with the numbers expressed in AString
Dim Splits() As String
Dim List() As Integer
Dim count As Integer
count = -1 'to start a zero-based List() array
' first split it using comma as delimiter
Splits = Split(AString, ",")
' process all fragments
For 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.
| #VBA | VBA | ' Read a file line by line
Sub Main()
Dim fInput As String, fOutput As String 'File names
Dim sInput As String, sOutput As String 'Lines
fInput = "input.txt"
fOutput = "output.txt"
Open fInput For Input As #1
Open fOutput For Output As #2
While Not EOF(1)
Line Input #1, sInput
... |
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
... | #Slate | Slate | '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... | #Nanoquery | Nanoquery | class FIFO
declare contents
// define constructors for FIFO objects
def FIFO()
this.contents = {}
end
def FIFO(contents)
this.contents = contents
end
// define methods for this class
def push(value)
contents.append(value)
end
def pop()
if !this.empty()
value = contents[len(contents) - 1]
con... |
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... | #Picat | Picat | go =>
test,
nl.
add(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :-
!, R is R0+R1, I is I0+I1, J is J0+J1, K is K0+K1.
add(qx(R0,I,J,K), F, qx(R,I,J,K)) :-
number(F), !, R is R0 + F.
add(F, qx(R0,I,J,K), Qx) :-
add($qx(R0,I,J,K), F, Qx).
mul(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :- !,
R is R0*R1 - ... |
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 ... | #Furor | Furor | "#s sto selfstring QUOTE @selfstring dup print QUOTE NL printnl end { „selfstring” }"
#s sto selfstring QUOTE @selfstring dup print QUOTE NL printnl end { „selfstring” } |
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... | #Phix | Phix | with javascript_semantics
function spout(integer first, curr, sequence s)
string res
if first=curr-1 then
res = sprintf("%d",s[first])
else
integer sep = iff(first=curr-2?',':'-')
res = sprintf("%d%s%d",{s[first],sep,s[curr-1]})
end if
return res
end function
function extra... |
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... | #Yabasic | Yabasic | a = open("rosetta_read.cfg")
while(not eof(#a))
FLAG = true : REMARK = false
line input #a line$
line$ = trim$(line$)
ll = len(line$)
c$ = left$(line$, 1)
switch(c$)
case "": case "#": REMARK = true : break
case ";": FLAG = false : line$ = trim$(right$(line$, ll - 1)) : break
... |
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... | #Wren | Wren | var expandRange = Fn.new { |s|
var list = []
var items = s.split(",")
for (item in items) {
var count = item.count { |c| c == "-" }
if (count == 0 || (count == 1 && item[0] == "-")) {
list.add(Num.fromString(item))
} else {
var items2 = item.split("-")
... |
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.
| #VBScript | VBScript |
FilePath = "<SPECIFY FILE PATH HERE>"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FilePath,1)
Do Until objFile.AtEndOfStream
WScript.Echo objFile.ReadLine
Loop
objFile.Close
Set objFSO = Nothing
|
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.
| #Vedit_macro_language | Vedit macro language | File_Open("line_by_line.vdm")
#10 = Buf_Num // edit buffer for input file
#11 = Buf_Free // edit buffer for output
#1 = 1 // line number
while (!At_EOF) {
Reg_Copy(20,1) // read one line into text register 20
Buf_Switch(#11) //... |
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
... | #Smalltalk | Smalltalk | '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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('') /* Puts an empty line onto the queue */
mqueue.push(a 2) /* Puts "Fred 2" onto the queue */
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2) /* Enqueu... |
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... | #PicoLisp | PicoLisp | (scl 6)
(def 'quatCopy copy)
(de quatNorm (Q)
(sqrt (sum * Q Q)) )
(de quatNeg (Q)
(mapcar - Q) )
(de quatConj (Q)
(cons (car Q) (mapcar - (cdr Q))) )
(de quatAddR (Q R)
(cons (+ R (car Q)) (cdr Q)) )
(de quatAdd (Q1 Q2)
(mapcar + Q1 Q2) )
(de quatMulR (Q R)
(mapcar */ (mapcar * Q (circ ... |
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 ... | #Gabuzomeu | Gabuzomeu | CALCGA,#ZOGAGABIRDBULIFTBUCALCGA,#MEUZOZOBIRDZOLIFTZOCALCGA,#BUBUMEUMEUBIRDBULIFTBUCALCGA,#ZOGAGABIRDZOLIFTZOCALCGA,#BUGAZOGABIRDBULIFTBUCALCGA,#BUGABUBUBIRDZOLIFTZOCALCGA,#BUGAGABUBIRDBULIFTBUCALCGA,#BUGABUGABIRDZOLIFTZOCALCGA,#BUGAGAZOBIRDBULIFTBUCALCGA,#BUBUBUBUBIRDZOLIFTZOCALCGA,#ZOMEUGABIRDBULIFTBUCALCGA,#BUZOGAB... |
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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
( ) var res
( )
( 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 )
def append
1 get swap -1 get rot swap
2 tolist res swap 0 put var res
enddef
def printRes
res len for
get
1 get swap 2 get nip
ov... |
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... | #zkl | zkl | fcn readConfigFile(config){ //--> read only dictionary
conf:=Dictionary();
foreach line in (config){
line=line.strip();
if (not line or "#"==line[0] or ";"==line[0]) continue;
line=line.replace("\t"," ");
n:=line.find(" ");
if (Void==n) conf[line.toLower()]=True; // eg 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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb
char Str;
int Char, Inx;
proc GetCh; \Get character from Str
[Char:= Str(Inx);
Inx:= Inx+1;
]; \GetCh
func GetNum; \Get number from ... |
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.
| #Visual_Basic | Visual Basic | ' Read a file line by line
Sub Main()
Dim fInput As String, fOutput As String 'File names
Dim sInput As String, sOutput As String 'Lines
Dim nRecord As Long
fInput = "input.txt"
fOutput = "output.txt"
On Error GoTo InputError
Open fInput For Input As #1
On Error GoTo 0 'reset error handl... |
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
... | #SNOBOL4 | SNOBOL4 | output = reverse(reverse("reverse"))
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... | #Nim | Nim | type
Node[T] = ref object
value: T
next: Node[T]
Queue*[T] = object
head, tail: Node[T]
length: Natural
func initQueue*[T](): Queue[T] = Queue[T]()
func len*(queue: Queue): Natural =
queue.length
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
func push*[T](queue: var Q... |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #PL.2FI | PL/I | *process source attributes xref or(!);
qu: Proc Options(main);
/**********************************************************************
* 06.09.2013 Walter Pachl translated from REXX
* added tasks 9 and A
**********************************************************************/
dcl v(4) Char(1) Var Init('... |
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 ... | #Gambas | Gambas | dim s as string="dim s as string=&1&2&3&4print subst(s,chr(34),s,chr(34),chr(10))"
print subst(s,chr(34),s,chr(34),chr(10))
|
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #Picat | Picat | go =>
Lists = [
[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9,
10, 11, 14, 15, 17, 18, 19, 20],
[ 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],
1..20,
... |
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... | #Yabasic | Yabasic | print RangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
sub RangeExpand$(s$)
local w$(1), n, i, r$, p, a, b
n = token(s$, w$(), ",")
for i = 1 to n
p = instr(w$(i), "-", 2)
if p then
a = val(left$(w$(i), p-1))
b = val(right$(w$(i), len(w$(i)) - p))
repea... |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
' Loop through the lines of a file.
' Function assumes that the file exists.
Private Sub ReadLines(ByVal FileName As String)
Dim oReader As New StreamReader(FileName)
Dim sLine As String = Nothing
While Not oReader.EndOfStream
sLine = oReader.ReadLine()
' Do somethi... |
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
... | #Standard_ML | Standard ML | val str_reverse = implode o rev o explode;
val string = "asdf";
val reversed = str_reverse string; |
http://rosettacode.org/wiki/Queue/Definition | Queue/Definition |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operation... | #OCaml | OCaml | module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_emp... |
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... | #PowerShell | PowerShell |
class Quaternion {
[Double]$w
[Double]$x
[Double]$y
[Double]$z
Quaternion() {
$this.w = 0
$this.x = 0
$this.y = 0
$this.z = 0
}
Quaternion([Double]$a, [Double]$b, [Double]$c, [Double]$d) {
$this.w = $a
$this.x = $b
$this.y = $c
$this.z = $d
}
[Double]a... |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #GAP | GAP | f:=function ( )
Print( "f:=", f, ";;\nf();\n" );
return;
end;;
f();
|
http://rosettacode.org/wiki/Range_extraction | Range extraction | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #PicoLisp | PicoLisp | (de rangeextract (Lst)
(glue ","
(make
(while Lst
(let (N (pop 'Lst) M N)
(while (= (inc M) (car Lst))
(setq M (pop 'Lst)) )
(cond
((= N M) (link N))
((= (inc N) M) (link N M))
(T (link (... |
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... | #zkl | zkl | fcn rangex(s){
fcn(s,re){
if (re.search(s)){
a,b:=re.matched[1,*].apply("toInt");
[a..b].walk();
}
else s;
} :
s.split(",").pump(List, _.fp1(RegExp(0'|(.*\d+)-(.*\d+)|)))
.flatten().concat(",");
} |
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.
| #Wart | Wart | with infile "x"
drain (read_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
... | #Stata | Stata | . scalar s="ARS LONGA VITA BREVIS"
. di strreverse(s)
SIVERB ATIV AGNOL SRA
. scalar s="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν"
. di ustrreverse(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... | #Oforth | Oforth | Object Class new: Queue(mutable l)
Queue method: initialize ListBuffer new := l ;
Queue method: empty @l isEmpty ;
Queue method: push @l add ;
Queue method: pop @l 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... | #Prolog | Prolog | % A quaternion is represented as a complex term qx/4
add(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :-
!, R is R0+R1, I is I0+I1, J is J0+J1, K is K0+K1.
add(qx(R0,I,J,K), F, qx(R,I,J,K)) :-
number(F), !, R is R0 + F.
add(F, qx(R0,I,J,K), Qx) :-
add(qx(R0,I,J,K), F, Qx).
mul(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(... |
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 ... | #Gema | Gema | *=$1@quote{$1}\}\n@abort;@{\*\=\$1\@quote\{\$1\}\\\}\\n\@abort\;\@\{} |
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... | #PL.2FI | PL/I | /* Modified 19 November 2011 to meet requirement that there be at */
/* least 3 items in a run. */
range_extraction: /* 17 August 2010 */
procedure options (main);
declare (c, d) character (1);
declare (old, new, initial) fixed binary (31);
de... |
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.
| #Wren | Wren | import "io" for File
var lines = [] // store lines read
File.open("input.txt") { |file|
var offset = 0
var line = ""
while(true) {
var b = file.readBytes(1, offset)
offset = offset + 1
if (b == "\n") {
lines.add(line)
line = "" // reset line variable
... |
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
... | #Swift | Swift | func reverseString(s: String) -> String {
return String(s.characters.reverse())
}
print(reverseString("asdf"))
print(reverseString("as⃝df̅")) |
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.