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/OpenWebNet_password | OpenWebNet password | Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist
Note: Factory default password is '12345'. Changing it is highly recommended !
conversation goes as follows
← *#*1##
→ *99*0##
← *#603... | #Wren | Wren | import "/fmt" for Fmt
var ownCalcPass = Fn.new { |password, nonce|
var start = true
var num1 = 0
var num2 = 0
var pwd = Num.fromString(password)
for (c in nonce) {
if (c != "0") {
if (start) num2 = pwd
start = false
}
if (c == "1") {
num1... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #BBC_BASIC | BBC BASIC | REM >oldrussian
@% = &90E
PROColdrus(1, "meter")
PRINT
PROColdrus(10, "arshin")
END
:
DEF PROColdrus(length, unit$)
LOCAL units$(), values(), unit%, i%
DIM units$(12)
DIM values(12)
units$() = "kilometer", "meter", "centimeter", "milia", "versta", "sazhen", "arshin", "fut", "piad", "vershok", "diuym", "liniya", "tochka... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #C | C |
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double fact... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Delphi | Delphi |
program OpenGLTriangle;
{$APPTYPE CONSOLE}
uses
System.Classes,
Sample.App,
Winapi.OpenGL,
System.UITypes;
type
TTriangleApp = class(TApplication)
public
procedure Initialize; override;
procedure Update(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Batch_File | Batch File |
@echo off
for /l %%i in (1,1,10000) do call one_of_n
:: To show progress add to the FOR loop code block -
:: title %%i
for /l %%i in (1,1,10) do (
for /f "usebackq tokens=1,2 delims=:" %%j in (`find /c "%%i" output.txt`) do echo Line %%i =%%k
)
del output.txt
pause>nul
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #BBC_BASIC | BBC BASIC | @% = 7 : REM Column width
DIM cnt%(10)
FOR test% = 1 TO 1000000
cnt%(FNone_of_n(10)) += 1
NEXT
FOR i% = 1 TO 10
PRINT cnt%(i%);
NEXT
PRINT
END
DEF FNone_of_n(n%)
LOCAL i%, l%
FOR i% = 1 TO n%
IF RND(1) <= 1/i% l% = i%
NEXT... |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #Ruby | Ruby | def pmin(array)
x = 1
pmin_array = []
array.each_index do |i|
pmin_array[i] = [array[i], x].min
abort if pmin_array[i] > 1
end
pmin_array
end
def cummin(array)
cumulative_min = array[0]
arr_cummin = []
array.each do |p|
cumulative_min = [p, cumulative_min].min
arr_cummin.push(cumulativ... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Lua | Lua | -- Split str on any space characters and return as a table
function split (str)
local t = {}
for word in str:gmatch("%S+") do table.insert(t, word) end
return t
end
-- Order disjoint list items
function orderList (dataStr, orderStr)
local data, order = split(dataStr), split(orderStr)
for orderPos,... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #FreeBASIC | FreeBASIC | Function power(n As Integer, p As Integer = 2) As Double
Return n ^ p
End Function
Print power(2) ' muestra 4
Print power(2, 3) ' muestra 8
Sleep |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #D | D | void main() {
assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]);
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #VBA | VBA | Option Base 1
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Dim eve() As String
ReDim odd(1)
ReDim eve(2)
odd(1) = " 1"
For i = 1 To n
If i Mod 2 = 1 Then
Debug.Print String$(2 * n - 2 * i, " ") & Join(odd, " ")
eve(1) = " 1"
ReDim Pr... |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #Nim | Nim | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #OCaml | OCaml | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Factor | Factor |
USING: grouping http.client io io.encodings.utf8 io.files
io.files.temp kernel math memoize sequences sequences.extras
unicode.case urls ;
IN: rosetta-code.ordered-words
MEMO: word-list ( -- seq )
"unixdict.txt" temp-file dup exists? [
URL" http://puzzlers.org/pub/wordlists/unixdict.txt"
over do... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Oforth | Oforth | String method: isPalindrome self reverse self == ; |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #Racket | Racket | sub MAIN {
put "Generate data for one time pad encryption.\n" ~
"File will have .1tp extension.";
my $fn;
loop {
$fn = prompt 'Filename for one time pad data: ';
if $fn !~~ /'.1tp' $/ { $fn ~= '.1tp' }
if $fn.IO.e {
my $ow = prompt "$fn aready exists, over-write? ... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #11l | 11l | V gen = ‘_###_##_#_#_#_#__#__’.map(ch -> Int(ch == ‘#’))
L(n) 10
print(gen.map(cell -> (I cell != 0 {‘#’} E ‘_’)).join(‘’))
gen = [0] [+] gen [+] [0]
gen = (0 .< gen.len - 2).map(m -> Int(sum(:gen[m .+ 3]) == 2)) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #11l | 11l | V animals = [
(‘fly’, ‘I don't know why she swallowed a fly, perhaps she'll die.’),
(‘spider’, ‘It wiggled and jiggled and tickled inside her.’),
(‘bird’, ‘How absurd, to swallow a bird.’),
(‘cat’, ‘Imagine that, she swallowed a cat.’),
(‘dog’, ‘What a hog, to swallow a dog.’),
... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Factor | Factor | USING: combinators combinators.short-circuit formatting fry
grouping grouping.extras kernel literals math math.functions
math.parser math.ranges qw regexp sequences sequences.deep
sequences.extras sets splitting unicode ;
IN: rosetta-code.numerical-suffixes
CONSTANT: test-cases {
qw{ 2greatGRo 24Gros 288Doz 1,728... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #C.2B.2B | C++ |
#include <iostream>
#include <iomanip>
//-------------------------------------------------------------------------------------------
using namespace std;
//-------------------------------------------------------------------------------------------
class ormConverter
{
public:
ormConverter() : AR( 0.7112f ), CE... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #eC | eC | #include <GL/gl.h>
import "ecere"
class GLTriangle : Window
{
text = "Triangle";
displayDriver = "OpenGL";
background = activeBorder;
nativeDecorations = true;
borderStyle = sizable;
hasMaximize = true, hasMinimize = true, hasClose = true;
size = { 640, 480 };
void OnRedraw(Surface surface)
... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #C | C | #include <stdio.h>
#include <stdlib.h>
inline int irand(int n)
{
int r, randmax = RAND_MAX/n * n;
while ((r = rand()) >= randmax);
return r / (randmax / n);
}
inline int one_of_n(int n)
{
int i, r = 0;
for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
return r;
}
int main(void)
{
int i, r[10] = {0};
for... |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #Rust | Rust |
use std::iter;
#[rustfmt::skip]
const PVALUES:[f64;50] = [
4.533_744e-01, 7.296_024e-01, 9.936_026e-02, 9.079_658e-02, 1.801_962e-01,
8.752_257e-01, 2.922_222e-01, 9.115_421e-01, 4.355_806e-01, 5.324_867e-01,
4.926_798e-01, 5.802_978e-01, 3.485_442e-01, 7.883_130e-01, 2.729_308e-01,
8.502_518e-01, 4.268_138e-01, 6.... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #M2000_Interpreter | M2000 Interpreter |
Function Checkit$ {
Document Ret$
Flush
Data "the cat sat on the mat", "mat cat"
Data "the cat sat on the mat","cat mat"'
Data "A B C A B C A B C", "C A C A"
Data "A B C A B D A B E", "E A D A"
Data "A B", "B"
Data "A B", "B A"
Data "A B B A","B A"
Dim A$()
while not empty
read m$, n$
A$()=piece$(m$, "... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | order[m_, n_] :=
ReplacePart[m,
MapThread[
Rule, {Position[m, Alternatives @@ n][[;; Length[n]]], n}]];
Print[StringRiffle[
order[{"the", "cat", "sat", "on", "the", "mat"}, {"mat",
"cat"}]]];
Print[StringRiffle[
order[{"the", "cat", "sat", "on", "the", "mat"}, {"cat",
"mat"}]]];
Print[Strin... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Go | Go | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
// initialize any defaults
return
}
// sort with all defaults
t.sort(newSpec())
// reverse sort
s := newSpec
s.reverse = true
t.sort(s) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Groovy | Groovy | def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) {
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #Delphi | Delphi |
program Order_two_numerical_lists;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Defaults;
type
TArray = record
class function LessOrEqual<T>(first, second: TArray<T>): Boolean; static;
end;
class function TArray.LessOrEqual<T>(first, second: TArray<T>): Boolean;
begin
if Length(first... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #VBScript | VBScript | Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
Dim values(100)
values(1) = 1
WScript.StdOut.Write values(1)
WScript.StdOut.WriteLine
For row = 2 To n
For i = row To 1 Step -1
values(i) = values(i) + values(i-1)
WScript.StdOut.Write values(i) & " "
Next
WScript.StdOut.WriteLine
Next
... |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #Oforth | Oforth | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #PARI.2FGP | PARI/GP | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Fantom | Fantom |
class Main
{
public static Bool ordered (Str word)
{
word.chars.all |Int c, Int i -> Bool|
{
(i == (word.size-1) || c <= word.chars[i+1])
}
}
public static Void main ()
{
Str[] words := [,]
File(`unixdict.txt`).eachLine |Str word|
{
if (ordered(word))
{
if... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION RESTfulGET(url)
DIM %HTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")
CALLMETHOD(HTTP, ".open %s, %s, %d", "GET", url, FALSE)
CALLMETHOD(HTTP, ".send")
RETURN GETVALUE("%s", HTTP, ".ResponseText")
END FUNCTION
DIM $TEXT = RESTfulGET("http://www.puzzlers.org/pub/wordlists/u... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Ol | Ol |
; simple case - only lowercase letters
(define (palindrome? str)
(let ((l (string->runes str)))
(equal? l (reverse l))))
(print (palindrome? "ingirumimusnocteetconsumimurigni"))
; ==> #true
(print (palindrome? "thisisnotapalindrome"))
; ==> #false
; complex case - with ignoring letter case and punctuat... |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #Raku | Raku | sub MAIN {
put "Generate data for one time pad encryption.\n" ~
"File will have .1tp extension.";
my $fn;
loop {
$fn = prompt 'Filename for one time pad data: ';
if $fn !~~ /'.1tp' $/ { $fn ~= '.1tp' }
if $fn.IO.e {
my $ow = prompt "$fn aready exists, over-write? ... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #8th | 8th |
\ one-dimensional automaton
\ direct map of input state to output state:
{
" " : 32,
" #" : 32,
" # " : 32,
" ##" : 35,
"# " : 32,
"# #" : 35,
"## " : 35,
"###" : 32,
} var, lifemap
: transition \ s ix (r:s') -- (r:s')
>r dup r@ n:1- 3 s:slice
lifemap @ swap caseof
r> swap r@ -rot ... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
package Messages is
type Message is tagged record
Timestamp : Time;
end record;
procedure Print(Item : Message);
procedure Display(Item : Message'Class);
type Sensor_Message is new Message with record
Sensor_Id : Integer;
Reading : Float;
en... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #8080_Assembly | 8080 Assembly | org 100h
mvi c,-1 ; C = verse counter
verse: inr c
lxi d,lady ; There was an old lady who swallowed a ...
call prstr
mov e,c ; <animal>
call pbeast
lxi d,comma
call prstr
mov e,c ; verse
call pverse
mov a,c ; is this the first verse?
ana a
jz verse ; then we're not swallowing animals yet
cpi 7 ; otherwis... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
mov bl,-1 ; BL = verse counter
verse: inc bl
mov dx,lady ; There was an old lady who swallowed
call prstr
mov dl,bl ; <animal>
call pbeast
mov dx,comma
call prstr
mov dl,bl ; verse
call pverse
test bl,bl ; is this the first verse?
jz verse ; then we're not swallowing a... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
type minmult struct {
min int
mult float64
}
var abbrevs = map[string]minmult{
"PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12},
"GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100},
}
var ... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #D | D | import std.stdio, std.string, std.algorithm, std.conv;
void main(in string[] args) {
auto factor = ["arshin": 0.7112,
"centimeter": 0.01,
"diuym": 0.0254,
"fut": 0.3048,
"kilometer": 1_000.0,
... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Euphoria | Euphoria |
include get.e
include dll.e
include machine.e
include msgbox.e
include constants.ew
include GLfunc.ew
include GLconst.ew
without warning
atom hRC, hDC, hWnd, hInstance, ClassName
sequence keys keys = repeat(0,256) -- array to hold key presses
integer active, fullscreen, retval
active = TRUE
fullscreen = TRUE
h... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #C.23 | C# |
class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)... |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #SAS | SAS | data pvalues;
input raw_p @@;
cards;
4.533744e-01 7.296024e-01 9.936026e-02 9.079658e-02 1.801962e-01
8.752257e-01 2.922222e-01 9.115421e-01 4.355806e-01 5.324867e-01
4.926798e-01 5.802978e-01 3.485442e-01 7.883130e-01 2.729308e-01
8.502518e-01 4.268138e-01 6.442008e-01 3.030266e-01 5.001555e-02
3.194810e-01 7.892933e-... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Nim | Nim | import algorithm, strutils
proc orderDisjoint(m, n: string): string =
# Build the list of items.
var m = m.splitWhitespace()
let n = n.splitWhitespace()
# Find the indexes of items to replace.
var indexes: seq[int]
for item in n:
let idx = m.find(item)
if idx >= 0:
indexes.add idx
... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Perl | Perl | sub dsort {
my ($m, $n) = @_;
my %h;
$h{$_}++ for @$n;
map $h{$_}-- > 0 ? shift @$n : $_, @$m;
}
for (split "\n", <<"IN")
the cat sat on the mat | mat cat
the cat sat on the mat | cat mat
A B C A B C A B C | C A C A
A B C A B D A B E | E A ... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Haskell | Haskell |
{-# LANGUAGE RecordWildCards #-}
data SorterArgs = SorterArgs { cmp :: String, col :: Int, rev :: Bool } deriving Show
defSortArgs = SorterArgs "lex" 0 False
sorter :: SorterArgs -> [[String]] -> [[String]]
sorter (SorterArgs{..}) = case cmp of
_ -> undefined
main = do
sorter d... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #Ela | Ela | [] <. _ = true
_ <. [] = false
(x::xs) <. (y::ys) | x == y = xs <. ys
| else = x < y
[1,2,1,3,2] <. [1,2,0,4,4,0,0,0] |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #Elixir | Elixir | iex(1)> [1,2,3] < [1,2,3,4]
true
iex(2)> [1,2,3] < [1,2,4]
true |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #Vedit_macro_language | Vedit macro language | #100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
for (#99 = 2; #99 <= #100; #99++) {
Ins_Char(' ', COUNT, (#100-#99)*3)
#@99 = 0
for (#98 = #99; #98 > 0; #98--) {
#97 = #98-1
#@98 += #@97
Num_Ins(#@98, COUNT, 6)
}
Ins_Newline
} |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #Pascal | Pascal | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #Perl | Perl | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #Phix | Phix | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Forth | Forth |
include lib/stmstack.4th \ include string stack library
: check-word ( a n -- a n f)
2dup bl >r \ start off with a space
begin
dup \ when not end of word
while
over c@ r@ >= \ check ch... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Oz | Oz | fun {IsPalindrome S}
{Reverse S} == S
end |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #Tcl | Tcl | puts "# True random chars for one-time pad"
proc randInt { min max } {
set randDev [open /dev/urandom rb]
set random [read $randDev 8]
binary scan $random H16 random
set random [expr {([scan $random %x] % (($max-$min) + 1) + $min)}]
close $randDev
return $random
}
proc randStr { sLen grp al... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Ada | Ada | with Ada.Text_IO;
procedure Odd_Word_Problem is
use Ada.Text_IO; -- Get, Put, and Look_Ahead
function Current return Character is
-- reads the current input character, without consuming it
End_Of_Line: Boolean;
C: Character;
begin
Look_Ahead(C, End_Of_Line);
if End_Of_Line t... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #ACL2 | ACL2 | (defun rc-step-r (cells)
(if (endp (rest cells))
nil
(cons (if (second cells)
(xor (first cells) (third cells))
(and (first cells) (third cells)))
(rc-step-r (rest cells)))))
(defun rc-step (cells)
(cons (and (first cells) (second cells))
(rc... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #ALGOL_68 | ALGOL 68 | MODE ENTITY = STRUCT([6]CHAR name, INT creation);
FORMAT entity repr = $"Name: "g", Created:"g$;
MODE PERSON = STRUCT(ENTITY entity, STRING email);
FORMAT person repr = $f(entity repr)", Email: "g$;
PERSON instance1 := PERSON(ENTITY("Cletus", 20080808), "test+1@localhost.localdomain");
print((name OF entity OF instan... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #Ada | Ada | with Ada.Text_IO, Ada.Containers.Indefinite_Doubly_Linked_Lists; use Ada.Text_IO;
procedure Swallow_Fly is
package Strings is new Ada.Containers.Indefinite_Doubly_Linked_Lists(String);
Lines, Animals: Strings.List;
procedure Swallow(Animal: String;
Second_Line: String;
... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Julia | Julia | using Formatting
partialsuffixes = Dict("PAIR" => "PAIRS", "SCO" => "SCORES", "DOZ" => "DOZENS",
"GR" => "GROSS", "GREATGR" => "GREATGROSS", "GOOGOL" => "GOOGOLS")
partials = sort(collect(keys(partialsuffixes)), lt=(a,b)->length(a)<length(b), rev=true)
multicharsuffixes = Dict("PAIRS" => 2, "SCO... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Nim | Nim | import re, strutils, parseutils, tables, math
const input = """
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! ... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes
use warnings;
my %suffix = qw( k 1e3 m 1e6 g 1e9 t 1e12 p 1e15 e 1e18 z 1e21 y 1e24 x 1e27
w 1e30 v 1e33 u 1e36 ki 2**10 mi 2**20 gi 2**30 ti 2**40 pi 2**50 ei 2**60
zi 2**70 yi 2**80 xi 2**90 wi 2**100 vi 2**110 ui 2... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Delphi | Delphi |
program Old_Russian_measure_of_length;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
units: array[0..12] of string = ('tochka', 'liniya', 'dyuim', 'vershok',
'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter',
'kilometer');
convs: array[0..12] of double = (0.0254, 0.254, ... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Factor | Factor | USING: kernel math math.rectangles opengl.gl sequences ui
ui.gadgets ui.render ;
IN: rosettacode.opengl
TUPLE: triangle-gadget < gadget ;
: reshape ( width height -- )
[ 0 0 ] 2dip glViewport
GL_PROJECTION glMatrixMode
glLoadIdentity
-30.0 30.0 -30.0 30.0 -30.0 30.0 glOrtho
GL_MODELVIEW glMatrix... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Forth | Forth | import glconst import float
glconst also float also opengl also |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #C.2B.2B | C++ | #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
mt19937 engine; //mersenne twister
unsigned int one_of_n(unsigned int n) {
unsigned int choice;
for(unsigned int i = 0; i < n; ++i) {
uniform_int_distribution<unsigned int> distribution(0, i);
if(!distribution(... |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #Stata | Stata | ssc install qqvalue |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #Phix | Phix | with javascript_semantics
function order_disjoint(sequence m, sequence n)
integer rlen = length(n)
sequence rdis = repeat(0,rlen)
for i=1 to rlen do
object e = n[i]
integer j = find(e,m)
while j!=0 and find(j,rdis) do
j = find(e,m,j+1)
end while
rdis[i] = ... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Icon_and_Unicon | Icon and Unicon |
procedure main()
X := [ [1,2,3], [2,3,1], [3,1,2]) # A list of lists
Sort(X) # vanilla sort
Sort(X,"ordering","numeric","column",2,"reverse") # using optional parameters
end
procedure Sort(X,A[]) ... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #Erlang | Erlang |
5> [1,2,3] < [1,2,3,4].
true
6> [1,2,3] < [1,2,4].
true
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #Visual_Basic | Visual Basic | Sub pascaltriangle()
'Pascal's triangle
Const m = 11
Dim t(40) As Integer, u(40) As Integer
Dim i As Integer, n As Integer, s As String, ss As String
ss = ""
For n = 1 To m
u(1) = 1
s = ""
For i = 1 To n
u(i + 1) = t(i) + t(i + 1)
s = s & u(i) & " ... |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #PHP | PHP | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #PicoLisp | PicoLisp | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Fortran | Fortran |
!***************************************************************************************
module ordered_module
!***************************************************************************************
implicit none
!the dictionary file:
integer,parameter :: file_unit = 1000
character(len=*),parameter :: filena... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #PARI.2FGP | PARI/GP | ispal(s)={
s=Vec(s);
for(i=1,#v\2,
if(v[i]!=v[#v-i+1],return(0))
);
1
}; |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #Wren | Wren | import "io" for File, Directory
import "/srandom" for SRandom
import "/ioutil" for FileUtil, Input
import "/dynamic" for Enum
import "/str" for Char, Str
var CHARS_PER_LINE = 48
var CHUNK_SIZE = 6
var COLS = 8
var DEMO = true // would normally be set to false
var FileType = Enum.create("FileType", ["OTP", "ENC", "... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #ALGOL_68 | ALGOL 68 | # recursively reverses the current word in the input and returns the #
# the character that followed it #
# "ch" should contain the first letter of the word on entry and will be #
# updated to the punctuation following the word on exit #
PROC reverse word = ( RE... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Action.21 | Action! | CHAR FUNC CalcCell(CHAR prev,curr,next)
IF prev='. AND curr='# AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='. AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='# AND next='. THEN
RETURN ('#)
FI
RETURN ('.)
PROC NextGeneration(CHAR ARRAY s)
BYTE i
CHAR prev,curr,next
IF s(0)<4 ... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #11l | 11l | F legendreIn(x, n)
F prev1(idx, pn1)
R (2 * idx - 1) * @x * pn1
F prev2(idx, pn2)
R (idx - 1) * pn2
I n == 0
R 1.0
E I n == 1
R x
E
V result = 0.0
V p1 = x
V p2 = 1.0
L(i) 2 .. n
result = (prev1(i, p1) - prev2(i, p2)) / i
p2 = p1
... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #C.23 | C# | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
STRING sw=" swallow ",swd=sw[:UPB sw-1]+"ed ", tsa=". To"+sw+"a";
INT count prev := 0; [9]STRING prev;
PROC vs = (STRING in wot,[]STRING co)VOID: (
STRING wot = " "+in wot;
printf(($g$,"I know an old lady who",swd,"a",wot,".",$l$));
IF UPB co = 1 THEN
printf(($gl$,co))
... |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation... | #Phix | Phix | with javascript_semantics
include builtins/bigatom.e
{} = ba_scale(34) -- (min rqd for accuracy on the "Vikki" test)
-- (the default is 25, not quite enough here)
constant suffixes = {{"GREATGRoss",7,1728},
{"GOOGOLs",6,ba_new("1e100")},
{"SCOres",3,20},... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Elena | Elena | import system'collections;
import system'routines;
import extensions;
unit2mult = new Map<string, real>()
.setAt("arshin", 0.7112r)
.setAt("centimeter", 0.01r)
.setAt("diuym", 0.0254r)
.setAt("fut", 0.3048r)
.setAt("kilometer", 1000.0r)
.setAt("liniya", 0.00254r)
... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Factor | Factor | USING: formatting inverse io kernel math prettyprint quotations
sequences units.imperial units.si vocabs ;
IN: rosetta-code.units.russian
: arshin ( n -- d ) 2+1/3 * feet ;
: tochka ( n -- d ) 1/2800 * arshin ;
: liniya ( n -- d ) 1/280 * arshin ;
: dyuim ( n -- d ) 1/28 * arshin ;
: vershok ( n -- d ) 1/16 * ar... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #FreeBASIC | FreeBASIC | #include "fbgfx.bi"
#include once "GL/gl.bi"
#include once "GL/glu.bi"
screen 18, 16, , 2
glViewport 0, 0, 640, 480 'Set the viewport
glMatrixMode GL_PROJECTION ' Select projection
glLoadIdentity ' Set this to default
gluPerspective 45.0, 640.... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Chapel | Chapel | use Random;
proc one_of_n(n) {
var rand = new RandomStream();
var keep = 1;
for i in 2..n do
if rand.getNext() < 1.0 / i then
keep = i;
delete rand;
return keep;
} |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Clojure | Clojure | (defn rand-seq-elem [sequence]
(let [f (fn [[k old] new]
[(inc k) (if (zero? (rand-int k)) new old)])]
(->> sequence (reduce f [1 nil]) second)))
(defn one-of-n [n]
(rand-seq-elem (range 1 (inc n))))
(let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))]
(doseq [[n cnt] (sort countm... |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q... | #Wren | Wren | import "/dynamic" for Enum
import "/fmt" for Fmt
import "/seq" for Lst
import "/math" for Nums
import "/sort" for Sort
var Direction = Enum.create("Direction", ["UP", "DOWN"])
// test also for 'Unknown' correction type
var types = [
"Benjamini-Hochberg", "Benjamini-Yekutieli", "Bonferroni", "Hochberg",
"Hol... |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #PicoLisp | PicoLisp | (de orderDisjoint (M N)
(for S N
(and (memq S M) (set @ NIL)) )
(mapcar
'((S) (or S (pop 'N)))
M ) ) |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
... | #PowerShell | PowerShell |
function sublistsort($M, $N) {
$arr = $M.Split(' ')
$array = $N.Split(' ') | group
$Count = @($array |foreach {$_.Count})
$ip, $i = @(), 0
$arr | foreach{
$name = "$_"
$j = $array.Name.IndexOf($name)
if($j -gt -1){
$k = $Count[$j] - 1
if($k -ge 0) {... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #J | J | srtbl=: verb define
'' srtbl y
:
'`ordering column reverse'=. x , (#x)}. ]`0:`0:
|.^:reverse y /: ordering (column {"1 ])y
) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Java | Java | import java.util.*;
public class OptionalParams {
// "natural ordering" comparator
static <T extends Comparable<? super T>> Comparator<T> naturalOrdering() {
return Collections.reverseOrder(Collections.<T>reverseOrder());
}
public static <T extends Comparable<? super T>> void
... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
She... | #F.23 | F# | let inline cmp x y = if x < y then -1 else if x = y then 0 else 1
let before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0
[
([0], []);
([], []);
([], [0]);
([-1], [0]);
([0], [0]);
([0], [-1]);
([0], [0; -1]);
([0], [0; 0]);
([0], [0; 1]);
([0; -1], [0]);
... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Iterator Function GetRow(rowNumber As BigInteger) As IEnumerable(Of BigInteger)
Dim denominator As BigInteger = 1
Dim numerator = rowNumber
Dim currentValue As BigInteger = 1
For counter = 0 To rowNumber
Yield currentValue
... |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #PL.2FI | PL/I | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #PureBasic | PureBasic | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isOrdered(s As Const String) As Boolean
If Len(s) <= 1 Then Return True
For i As Integer = 1 To Len(s) - 1
If s[i] < s[i - 1] Then Return False
Next
Return True
End Function
Dim words() As String
Dim word As String
Dim maxLength As Integer = 0
Dim count As Integer = 0
Open "... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Pascal | Pascal | program Palindro;
{ RECURSIVE }
function is_palindro_r(s : String) : Boolean;
begin
if length(s) <= 1 then
is_palindro_r := true
else begin
if s[1] = s[length(s)] then
is_palindro_r := is_palindro_r(copy(s, 2, length(s)-2))
else
is_palindro_r := false
end
end; { is_palindro_r }
{ NON ... |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #TypeScript | TypeScript |
#!/usr/bin/env node
import { writeFileSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
//https://www.elitizon.com/2021/01-09-how-to-create-a-cli-command-with-typescript/#:~:text=%20Boost%20your%20productivity%20by%20creating%20your%20own,information.%20Required%3A%20string.%20%20...%20%20More%20
const a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.