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/OLE_automation | OLE automation | OLE Automation is an inter-process communication mechanism based on Component Object Model (COM) on Microsoft Windows.
Task
Provide an automation server implementing objects that can be accessed by a client running in a separate process.
The client gets a proxy-object that can call methods on the object.
Th... | #Wren | Wren | /* OLE_automation.wren */
class Ole {
foreign static coInitialize(p)
foreign static coUninitialize()
}
class OleUtil {
static createObject(programID) {
return IUnknown.new(programID)
}
foreign static putProperty(disp, name, param)
foreign static mustGetProperty(disp, name)
fore... |
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... | #Nim | Nim | import algorithm, math, sequtils, strformat, strutils, sugar
type
CorrectionType {.pure.} = enum
BenjaminiHochberg = "Benjamini-Hochberg"
BenjaminiYekutieli = "Benjamini-Yekutieli"
Bonferroni = "Bonferroni"
Hochberg = "Hochberg"
Holm = "Holm"
Hommel = "Hommel"
Šidák = "Šidák"
Direc... |
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
... | #Go | Go | package main
import (
"fmt"
"sort"
"strings"
)
type indexSort struct {
val sort.Interface
ind []int
}
func (s indexSort) Len() int { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
s.val.Swap(s.ind[i], s.ind[j])
s.ind[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
... | #Common_Lisp | Common Lisp | (defun sort-table (table &key (ordering #'string<)
(column 0)
reverse)
(sort table (if reverse
(complement ordering)
ordering)
:key (lambda (row) (elt row column)))) |
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
... | #D | D | import std.stdio, std.algorithm, std.functional;
string[][] sortTable(string[][] table,
in bool function(string[],string[]) ordering=null,
in int column = 0,
in bool reverse = false) {
if (ordering is null)
table.schwartzSort!(row => row[colum... |
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... | #Bracmat | Bracmat | ( 1 2 3 4 5:?List1
& 1 2 1 5 2 2:?List2
& 1 2 1 5 2:?List3
& 1 2 1 5 2:?List4
& Cat Elephant Rat Cat:?List5
& Cat Elephant Rat:?List6
& Cat Cat Elephant:?List7
& ( gt
= first second
. !arg:(?first,?second)
& out
$ ( (.!first)+(.!second)
: ((.!first)+(.!second)|2*(.!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... | #TI-83_BASIC | TI-83 BASIC | PROGRAM:PASCALTR
:Lbl IN
:ClrHome
:Disp "NUMBER OF ROWS"
:Input N
:If N < 1:Goto IN
:{N,N}→dim([A])
:"CHEATING TO MAKE IT FASTER"
:For(I,1,N)
:1→[A](1,1)
:End
:For(I,2,N)
:For(J,2,I)
:[A](I-1,J-1)+[A](I-1,J)→[A](I,J)
:End
:End
:[A] |
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... | #FreeBASIC | FreeBASIC | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #Furor | Furor | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #FutureBasic | FutureBasic | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #Delphi | Delphi |
program POrderedWords;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes, IdHTTP;
function IsOrdered(const s:string): Boolean;
var
I: Integer;
begin
Result := Length(s)<2; // empty or 1 char strings are ordered
for I := 2 to Length(s) do
if s[I]<s[I-1] then // can improve using case/localization to order...... |
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 ... | #NetRexx | NetRexx |
y='In girum imus nocte et consumimur igni'
-- translation: We walk around in the night and
-- we are burnt by the fire (of love)
say
say 'string = 'y
say
pal=isPal(y)
if pal==0 then say "The string isn't palindromic."
else say 'The string is palindromic.'
method isPal(x) static
x=x.upper().space(0... |
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... | #Java | Java |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OneTimePad {
public static void main(String[] args) {
St... |
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... | #Nim | Nim | import bitops, strutils
func ownCalcPass(password, nonce: string): uint32 =
var start = true
for c in nonce:
if c != '0' and start:
result = parseInt(password).uint32
start = false
case c
of '0':
discard
of '1':
result = result.rotateRightBits(7)
of '2':
resul... |
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use integer; # required solely for 2's complement operation: $n1 = ~$n2
sub own_password {
my($password, $nonce) = @_;
my $n1 = 0;
my $n2 = $password;
for my $d (split //, $nonce) {
if ($d == 1) {
$n1 = ($n2 & 0xFFFFFF80) >> 7;
... |
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.
| #C | C | #include <stdlib.h>
#include <GL/gl.h>
#include <GL/glut.h>
void paint(void)
{
glClearColor(0.3,0.3,0.3,0.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glLoadIdentity();
glTranslatef(-15.0, -15.0, 0.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(... |
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... | #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Float_Random;
procedure One_Of_N is
Num_Of_Lines: constant Positive := 10;
package Rnd renames Ada.Numerics.Float_Random;
Gen: Rnd.Generator; -- used globally
function Choose_One_Of_N(Last_Line_Number: Positive) return Natural is
Current_Choice: Natural := 0;
... |
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... | #Perl | Perl | #!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use autodie ':all';
use List::Util 'min';
use feature 'say';
sub pmin {
my $array = shift;
my $x = 1;
my @pmin_array;
my $n = scalar @$array;
for (my $index = 0; $index < $n; $index++) {
$pmin_array[$index] = min(@$array[$index], $x);
}
@pmin_arr... |
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
... | #Haskell | Haskell | import Data.List (mapAccumL, sort)
order
:: Ord a
=> [[a]] -> [a]
order [ms, ns] = snd . mapAccumL yu ls $ ks
where
ks = zip ms [(0 :: Int) ..]
ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks
yu ((u, v):us) (_, y)
| v == y = (us, u)
yu ys (x, _) = (ys, x)
go (u:us, ys) (x... |
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
... | #Delphi | Delphi | program Optional_parameters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TRow = TArray<string>;
TOrderingFun = TFunc<TRow, TRow, Boolean>;
TTable = array of TRow;
TRowHelper = record helper for TRow
public
procedure Swap(var other: TRow);
function ToString: string;
function Length:... |
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... | #C | C | int list_cmp(int *a, int la, int *b, int lb)
{
int i, l = la;
if (l > lb) l = lb;
for (i = 0; i < l; i++) {
if (a[i] == b[i]) continue;
return (a[i] > b[i]) ? 1 : -1;
}
if (la == lb) return 0;
return la > lb ? 1 : -1;
} |
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... | #Turing | Turing | proc pascal (n : int)
for i : 0 .. n
var c := 1
for k : 0 .. i
put c : 4 ..
c := c * (i - k) div (k + 1)
end for
put ""
end for
end pascal
pascal(5) |
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... | #Go | Go | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #Haskell | Haskell | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #Icon_and_Unicon | Icon and Unicon | (expr) # grouping
{expr1;expr2;...} # compound
x(expr1,expr2,...) # process argument list
x{expr1,expr2,...} # process co-expression list
[expr1,expr2,...] # list
expr.F ... |
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... | #E | E | pragma.enable("accumulator")
def words := <http://www.puzzlers.org/pub/wordlists/unixdict.txt>.getText().split("\n")
def ordered := accum [] for word ? (word.sort() <=> word) in words { _.with(word) }
def maxLen := accum 0 for word in ordered { _.max(word.size()) }
def maxOrderedWords := accum [] for word ? (word.siz... |
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 ... | #NewLISP | NewLISP |
(define (palindrome? s)
(setq r s)
(reverse r) ; Reverse is destructive.
(= s r))
;; Make ‘reverse’ non-destructive and avoid a global variable
(define (palindrome? s)
(= s (reverse (copy s))))
|
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... | #Julia | Julia | // version 1.2.31
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true // would normally be set to false
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.fil... |
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... | #Phix | Phix | with javascript_semantics
function ownCalcPass(atom pwd, string nonce)
bool start = true
atom num1 = 0,
num2 = 0
for i=1 to length(nonce) do
integer c = nonce[i]
if c!='0' and start then
num2 = pwd
start = false
end if
switch c do
... |
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.
| #C.23 | C# | using OpenTK;
using OpenTK.Graphics;
namespace OpenGLTest
{
class Program
{
static void Main(string[] args)
{
//Create the OpenGL window
GameWindow window = new GameWindow(640, 480, GraphicsMode.Default, "OpenGL Example");
GL.MatrixMode(MatrixMode.Projection... |
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... | #Aime | Aime | one_of_n(integer n)
{
integer i, r;
i = r = 0;
while ((r += 1) < n) {
i = drand(r) ? i : r;
}
i;
}
main(void)
{
integer i;
index x;
i = 1000000;
do {
x[one_of_n(10)] += 1;
} while (i -= 1);
x.ucall(o_winteger, 1, 7);
o_newline();
0;
} |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
INT max lines = 10; CO Should be read from a file. CO
[max lines]INT stats;
FOR i TO max lines DO stats[i] := 0 OD;
first random (42); CO Should have rather more entropy! CO
PROC one of n = (INT n) INT :
BEGIN
INT result := 1;
FOR i TO n DO (random < 1/i | result := i) OD;
re... |
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... | #Phix | Phix | with javascript_semantics
enum UP, DOWN
function ratchet(sequence p, integer direction)
atom m = p[1]
for i=1 to length(p) do
if iff(direction=UP?p[i]>m:p[i]<m) then p[i] = m end if
m = p[i]
end for
return sq_min(p,1)
end function
function schwartzian(sequence p, mult, integer direct... |
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
... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every write(" -> ",odli("the cat sat on the mat","mat cat"))
every write(" -> ",odli("the cat sat on the mat","cat mat"))
every write(" -> ",odli("A B C A B C A B C","C A C A"))
every write(" -> ",odli("A B C A B D A B E","E A D A"))
every write(" -> ",odli("A B","B"))
every wr... |
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
... | #E | E | def defaultOrdering(a, b) { return a.op__cmp(b) }
def sort {
to run(table) {
return sort(table, 0, false, defaultOrdering)
}
to run(table, column) {
return sort(table, column, false, defaultOrdering)
}
to run(table, column, reverse) {
return sort(table, column, reverse,... |
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... | #C.23 | C# | namespace RosettaCode.OrderTwoNumericalLists
{
using System;
using System.Collections.Generic;
internal static class Program
{
private static bool IsLessThan(this IEnumerable<int> enumerable,
IEnumerable<int> otherEnumerable)
{
using (
IEnumerato... |
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... | #TypeScript | TypeScript | // Pascal's triangle
function pascal(n: number): void {
// Display the first n rows of Pascal's triangle
// if n<=0 then nothing is displayed
var ld: number[] = new Array(40); // Old
var nw: number[] = new Array(40); // New
for (var row = 0; row < n; row++) {
nw[0] = 1;
for (var i = 1; i <= row; 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... | #J | J | Julia Operators in Order of Preference
--------------------------------------------
Syntax . followed by ::
Exponentiation ^
Fractions //
Multiplication * / % & \
Bitshifts << >> >>>
Addition + - | ⊻
Syntax : .. followed by |>
Comparisons > < >= <= == === != !== <:
Control flow && followed by || fo... |
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... | #Java | Java | Julia Operators in Order of Preference
--------------------------------------------
Syntax . followed by ::
Exponentiation ^
Fractions //
Multiplication * / % & \
Bitshifts << >> >>>
Addition + - | ⊻
Syntax : .. followed by |>
Comparisons > < >= <= == === != !== <:
Control flow && followed by || fo... |
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... | #JavaScript | JavaScript | Julia Operators in Order of Preference
--------------------------------------------
Syntax . followed by ::
Exponentiation ^
Fractions //
Multiplication * / % & \
Bitshifts << >> >>>
Addition + - | ⊻
Syntax : .. followed by |>
Comparisons > < >= <= == === != !== <:
Control flow && followed by || fo... |
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... | #EchoLisp | EchoLisp |
(define (ordered? str)
(for/and ([i (in-range 1 (string-length str))])
(string-ci<=? (string-ref str (1- i)) (string-ref str i))))
(define (ordre words)
(define wl 0)
(define s 's)
(for/fold (len 0) ((w words))
(set! wl (string-length w))
#:continue (< wl len)
#:when (ordered? w)
#:continue (and (= l... |
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 ... | #Nim | Nim | import unicode
func isPalindrome(rseq: seq[Rune]): bool =
## Return true if a sequence of runes is a palindrome.
for i in 1..(rseq.len shr 1):
if rseq[i - 1] != rseq[^i]:
return false
result = true
func isPalindrome(str: string; exact = true): bool {.inline.} =
## Return true if a UTF-8 string... |
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... | #Kotlin | Kotlin | // version 1.2.31
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true // would normally be set to false
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.fil... |
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... | #PHP | PHP | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$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:
... | #11l | 11l | V unit2mult = [‘arshin’ = 0.7112, ‘centimeter’ = 0.01, ‘diuym’ = 0.0254,
‘fut’ = 0.3048, ‘kilometer’ = 1000.0, ‘liniya’ = 0.00254,
‘meter’ = 1.0, ‘milia’ = 7467.6, ‘piad’ = 0.1778,
‘sazhen’ = 2.1336, ‘tochka’ = 0.000254, ‘vershok’ = 0.04445,
... |
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.
| #Clojure | Clojure | (use 'penumbra.opengl)
(require '[penumbra.app :as app])
(defn init [state]
(app/title! "Triangle")
(clear-color 0.3 0.3 0.3 0)
(shade-model :smooth)
state)
(defn reshape [[x y w h] state]
(ortho-view -30 30 -30 30 -30 30)
(load-identity)
(translate -15 -15)
state)
(defn display [[dt time] state]
... |
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... | #Applesoft_BASIC | Applesoft BASIC | 10 I = RND(0) : REMRANDOM SEED
20 FOR J = 1 TO 1000000 : REMMAYBE TRY 100 ON A 1MHZ APPLE II
30 N = 10 : GOSUB 100"ONE_OF_N
40 C(C) = C(C) + 1
50 NEXT
60 FOR J = 1 TO 10
70 PRINT J, C(J)
80 NEXT
90 END
100 REMONE_OF_N
110 FOR I = 1 TO N
120 IF INT(RND(1) * I) = 0 THEN C = I
130 NEXT I
140 RETURN |
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... | #Arturo | Arturo | oneOfN: function [n][
result: 0
loop 0..dec n 'x [
if zero? random 0 x ->
result: x
]
return result
]
oneOfNTest: function [n,trials][
ret: array.of:n 0
if n > 0 [
loop 1..trials 'i [
oon: oneOfN n
ret\[oon]: ret\[oon] + 1
]
]
... |
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... | #Python | Python | from __future__ import division
import sys
def pminf(array):
x = 1
pmin_list = []
N = len(array)
for index in range(N):
if array[index] < x:
pmin_list.insert(index, array[index])
else:
pmin_list.insert(index, x)
return pmin_list
#end function
def cumminf(a... |
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
... | #J | J | disjorder=:3 :0&.;:
:
clusters=. (</. i.@#) x
order=. x i.&~. y
need=. #/.~ y
from=. ;need (#{.)each (/:~order){clusters
to=. ;need {.!._ each order{clusters
(from{x) to} x
) |
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
... | #Java | Java | import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;
public class OrderDisjointItems {
public static void main(String[] args) {
final String[][] MNs = {{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B... |
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
... | #Elixir | Elixir | defmodule Optional_parameters do
def sort( table, options\\[] ) do
options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ]
ordering = options[ :ordering ]
column = options[ :column ]
reverse = options[ :reverse ]
sorted = sort( table, ordering, column )
if reverse, do: ... |
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
... | #Erlang | Erlang |
-module( optional_parameters ).
-export( [sort/2, task/0] ).
sort( Table, Options ) ->
Ordering = proplists:get_value( ordering, Options, lexicographic ),
Column = proplists:get_value( column, Options, 1 ),
Is_reverse = proplists:get_value( reverse, Options, false ),
Sorted = sort( Table, Ordering, 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... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(1);
a.push_back(3);
a.push_back(2);
std::vector<int> b;
b.push_back(1);
b.push_back(2);
b.push_back(0);
b.push_back(4);
b.push_back(4);
b.push_back(0);
b.push_back(0);
b.pus... |
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... | #uBasic.2F4tH | uBasic/4tH | Input "Number Of Rows: "; N
@(1) = 1
Print Tab((N+1)*3);"1"
For R = 2 To N
Print Tab((N-R)*3+1);
For I = R To 1 Step -1
@(I) = @(I) + @(I-1)
Print Using "______";@(i);
Next
Next
Print
End |
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... | #jq | jq | Julia Operators in Order of Preference
--------------------------------------------
Syntax . followed by ::
Exponentiation ^
Fractions //
Multiplication * / % & \
Bitshifts << >> >>>
Addition + - | ⊻
Syntax : .. followed by |>
Comparisons > < >= <= == === != !== <:
Control flow && followed by || fo... |
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... | #Julia | Julia | Julia Operators in Order of Preference
--------------------------------------------
Syntax . followed by ::
Exponentiation ^
Fractions //
Multiplication * / % & \
Bitshifts << >> >>>
Addition + - | ⊻
Syntax : .. followed by |>
Comparisons > < >= <= == === != !== <:
Control flow && followed by || fo... |
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... | #Kotlin | Kotlin |
As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence.
Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}
|
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... | #Elixir | Elixir | File.read!("unixdict.txt")
|> String.split
|> Enum.filter(fn word -> String.codepoints(word) |> Enum.sort |> Enum.join == word end)
|> Enum.group_by(fn word -> String.length(word) end)
|> Enum.max_by(fn {length,_words} -> length end)
|> elem(1)
|> Enum.sort
|> Enum.each(fn word -> IO.puts word end) |
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... | #Erlang | Erlang |
-module( ordered_words ).
-export( [is_ordered/1, task/0] ).
is_ordered( Word ) -> lists:sort( Word ) =:= Word.
task() ->
ok = find_unimplemented_tasks:init_http(),
Ordered_words = [X || X <- words(), is_ordered(X)],
Sorted_longest_length_first = lists:reverse( sort_with_length( Ordered_words ) ),
... |
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 ... | #Objeck | Objeck |
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
IsPalindrome("aasa")->PrintLine();
IsPalindrome("acbca")->PrintLine();
IsPalindrome("xx")->PrintLine();
}
function : native : IsPalindrome(s : String) ~ Bool {
l := s->Size();
for(i := 0; i < l / 2; i ... |
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... | #Nim | Nim | import os, re, sequtils, strformat, strutils
import nimcrypto
# One-time pad file signature.
const Magic = "#one-time pad"
# Suffix for pad files.
const Suffix = ".1tp"
proc log(msg: string) =
## Log a message.
stderr.write msg
stderr.write '\n'
proc makeKeys(n, size: Positive): seq[string] =
## Generat... |
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... | #Perl | Perl | # 20200814 added Perl programming solution
use strict;
use warnings;
use Crypt::OTP;
use Bytes::Random::Secure qw( random_bytes );
print "Message : ", my $message = "show me the monKey", "\n";
my $otp = random_bytes(length $message);
print "Ord(OTP) : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n";... |
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... | #Python | Python |
def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if tes... |
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:
... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
DEFINE UNIT_COUNT="10"
PTR ARRAY
names(UNIT_COUNT),
values(UNIT_COUNT)
BYTE count=[0]
PROC Append(CHAR ARRAY name REAL POINTER value)
names(count)=name
values(count)=value
count==+1
RETURN
PROC Init()
REAL
arshin,centimeter,kilom... |
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:
... | #AppleScript | AppleScript | -- General purpose linear measurement converter.
on convertLinear(inputNumber, inputUnitRecord, outputUnitRecord)
set {inputType, outputType} to {inputUnitRecord's type, outputUnitRecord's type}
if (inputType is not outputType) then error "Unit type mismatch: " & inputType & ", " & outputType
-- The |offset... |
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.
| #Common_Lisp | Common Lisp | (defun draw-triangle (x y &key (z 0) (type 'right))
(case type
(right
(gl:with-primitive :triangles
(gl:color 0 0 1)
(gl:vertex x y z)
(gl:color 0 1 0)
(gl:vertex x (- y 1) z)
(gl:color 1 0 0)
(gl:vertex (+ x 1) (1- y) z)))
(equilateral
(gl:with-primitive :t... |
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... | #AutoHotkey | AutoHotkey | one_of_n(n){
; One based line numbers
choice = 1
Loop % n-1
{
Random, rnd, 1, % A_Index+1
If rnd = 1
choice := A_Index+1
}
return choice
}
one_of_n_test(n=10, trials=100000){
bins := [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Loop % trials
bins[one_of_n(n)] += 1
... |
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... | #R | R | p <- c(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.194... |
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
... | #JavaScript | JavaScript | (() => {
"use strict";
// ------------ ORDER DISJOINT LIST ITEMS ------------
// disjointOrder :: [String] -> [String] -> [String]
const disjointOrder = ms =>
ns => zipWith(
a => b => [...a, b]
)(
segments(ms)(ns)
)(
ns.concat("")
)... |
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
... | #F.23 | F# | type Table(rows:string[][]) =
// in-place sorting of rows
member x.Sort(?ordering, ?column, ?reverse) =
let ordering = defaultArg ordering compare
let column = defaultArg column 0
let reverse = defaultArg reverse false
let factor = if reverse then -1 else 1
let comparer (row1... |
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... | #clojure | clojure |
(defn lex? [a b]
(compare a b))
|
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... | #UNIX_Shell | UNIX Shell | #! /bin/bash
pascal() {
local -i n=${1:-1}
if (( n <= 1 )); then
echo 1
else
local output=$( $FUNCNAME $((n - 1)) )
set -- $( tail -n 1 <<<"$output" ) # previous row
echo "$output"
printf "1 "
while [[ -n $1 ]]; do
printf "%d " $(( $1 + ${2:-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... | #Lambdatalk | Lambdatalk |
As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence.
Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}
|
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... | #LIL | LIL | expr [...]
combines all arguments into a single string and evaluates the
mathematical expression in that string. The expression can use the
following operators (in the order presented):
(a) - parentheses
-a - negative sign
+a ... |
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... | #Lua | Lua | 42 :my-var
42 "my-var" define |
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... | #Euphoria | Euphoria | include misc.e
type ordered(sequence s)
for i = 1 to length(s)-1 do
-- assume all items in the sequence are atoms
if s[i]>s[i+1] then
return 0
end if
end for
return 1
end type
integer maxlen
sequence words
object word
constant fn = open("unixdict.txt","r")
maxlen = -1... |
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 ... | #OCaml | OCaml | let is_palindrome s =
let l = String.length s in
let rec comp n =
n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in
comp (l / 2) |
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... | #Phix | Phix |
"""One-time pad using an XOR cipher. Requires Python >=3.6."""
import argparse
import itertools
import pathlib
import re
import secrets
import sys
# One-time pad file signature.
MAGIC = "#one-time pad"
def make_keys(n, size):
"""Generate ``n`` secure, random keys of ``size`` bytes."""
# We're genera... |
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... | #Racket | Racket | #lang racket/base
(define (32-bit-truncate n)
(bitwise-and n #xFFFFFFFF))
(define (own-calc-pass password-string nonce)
(define-values (num-1 flag)
(for/fold ((num-1 0) (flag #t))
((c (in-string nonce)))
(let* ((num-1 (32-bit-truncate num-1))
(num-2 (if flag (string->number pa... |
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... | #Raku | Raku | sub own-password (Int $password, Int $nonce) {
my int $n1 = 0;
my int $n2 = $password;
for $nonce.comb {
given $_ {
when 1 {
$n1 = $n2 +& 0xFFFFFF80 +> 7;
$n2 +<= 25;
}
when 2 {
$n1 = $n2 +& 0xFFFFFFF0 +> 4;
... |
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:
... | #AWK | AWK |
# syntax: GAWK -f OLD_RUSSIAN_MEASURE_OF_LENGTH.AWK
BEGIN {
units = "kilometer meter centimeter tochka liniya diuym vershok piad fut arshin sazhen versta milia"
values = "1000.0 1.0 0.01 0.000254 0.00254 0.0254 0.04445 0.1778 0.3048 0.7112 2.1336 1066.8 7467.6"
u_leng = split(units,u_arr," ")
v_leng =... |
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.
| #D | D | module opengl_sample; // file name + directory
import dglut.core, dglut.window, dglut.opengl;
void main() {
with (new Canvas) {
setName("Triangle");
map;
onResize = (Canvas self) { // A delegate literal that takes a parameter.
with (self) glViewport(0, 0, width, height);
MatrixMode.Project... |
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... | #AWK | AWK | #!/usr/bin/gawk -f
#
# Usage:
# gawk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk
#
BEGIN {
srand(Seed ? Seed : 1);
}
{
if (NR*rand() < 1 ) {
line = $0
}
}
END {
print line;
} |
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... | #BASIC | BASIC | DECLARE FUNCTION oneofN& (n AS LONG)
DIM L0 AS LONG, c AS LONG
DIM chosen(1 TO 10) AS LONG
RANDOMIZE TIMER
FOR L0 = 1 TO 1000000
c = oneofN&(10)
chosen(c) = chosen(c) + 1
NEXT
FOR L0 = 1 TO 10
PRINT L0, chosen(L0)
NEXT
FUNCTION oneofN& (n AS LONG)
'assumes first line is 1
DIM L1 AS LONG, c... |
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... | #Raku | Raku | ########################### Helper subs ###########################
sub adjusted (@p, $type) { "\n$type\n" ~ format adjust( check(@p), $type ) }
sub format ( @p, $cols = 5 ) {
my $i = -$cols;
my $fmt = "%1.10f";
join "\n", @p.rotor($cols, :partial).map:
{ sprintf "[%2d] { join ' ', $fmt xx $_ }",... |
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
... | #jq | jq | def disjoint_order(N):
# The helper function, indices, ensures that successive occurrences
# of a particular value in N are matched by successive occurrences
# in the input on the assumption that null is not initially in the input.
def indices:
. as $in
| reduce range(0; N|length) as $i
# state: ... |
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
... | #Julia | Julia |
function order_disjoint{T<:AbstractArray}(m::T, n::T)
rlen = length(n)
rdis = zeros(Int, rlen)
for (i, e) in enumerate(n)
j = findfirst(m, e)
while j in rdis && j != 0
j = findnext(m, e, j+1)
end
rdis[i] = j
end
if 0 in rdis
throw(DomainError())
... |
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
... | #Kotlin | Kotlin | // version 1.0.6
const val NULL = "\u0000"
fun orderDisjointList(m: String, n: String): String {
val nList = n.split(' ')
// first replace the first occurrence of items of 'n' in 'm' with the NULL character
// which we can safely assume won't occur in 'm' naturally
var p = m
for (item in nList)... |
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
... | #Factor | Factor | USING: accessors combinators io kernel math.order prettyprint
sequences sorting ;
TUPLE: table-sorter
data
{ column initial: 0 }
reversed?
{ ordering initial: [ ] } ;
: <table-sorter> ( -- obj ) table-sorter new ;
: sort-table ( table-sorter -- matrix )
{
[ data>> ]
[ column>> ... |
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
... | #Fortran | Fortran | module ExampleOptionalParameter
! use any module needed for the sort function(s)
! and all the interfaces needed to make the code work
implicit none
contains
subroutine sort_table(table, ordering, column, reverse)
type(table_type), intent(inout) :: table
integer, optional :: column
logical, option... |
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... | #Common_Lisp | Common Lisp | (defun list< (a b)
(cond ((not b) nil)
((not a) t)
((= (first a) (first b))
(list< (rest a) (rest b)))
(t (< (first a) (first b))))) |
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... | #Ursala | Ursala | #import std
#import nat
pascal = choose**ziDS+ iota*t+ iota+ successor |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 42 :my-var
42 "my-var" define |
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... | #MATLAB | MATLAB | 42 :my-var
42 "my-var" define |
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... | #min | min | 42 :my-var
42 "my-var" define |
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... | #F.23 | F# | open System
open System.IO
let longestOrderedWords() =
let isOrdered = Seq.pairwise >> Seq.forall (fun (a,b) -> a <= b)
File.ReadLines("unixdict.txt")
|> Seq.filter isOrdered
|> Seq.groupBy (fun s -> s.Length)
|> Seq.sortBy (fst >> (~-))
|> Seq.head |> snd
longestOrderedWords() |> Seq.iter... |
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 ... | #Octave | Octave | function v = palindro_r(s)
if ( length(s) == 1 )
v = true;
return;
elseif ( length(s) == 2 )
v = s(1) == s(2);
return;
endif
if ( s(1) == s(length(s)) )
v = palindro_r(s(2:length(s)-1));
else
v = false;
endif
endfunction |
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... | #Python | Python |
"""One-time pad using an XOR cipher. Requires Python >=3.6."""
import argparse
import itertools
import pathlib
import re
import secrets
import sys
# One-time pad file signature.
MAGIC = "#one-time pad"
def make_keys(n, size):
"""Generate ``n`` secure, random keys of ``size`` bytes."""
# We're genera... |
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... | #Swift | Swift |
func openAuthenticationResponse(_password: String, operations: String) -> String? {
var num1 = UInt32(0)
var num2 = UInt32(0)
var start = true
let password = UInt32(_password)!
for c in operations {
if (c != "0") {
if start {
num2 = password
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.