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/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... | #AutoHotkey | AutoHotkey | str := "what,is,the;meaning,of:life."
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
res .= A_LoopField, toggle:=!toggle
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res |
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... | #BaCon | BaCon | OPEN "/dev/stdin" FOR DEVICE AS in
FUNCTION get_odd()
LOCAL ch, letter
ch = MEMORY(1)
GETBYTE ch FROM in
IF NOT(REGEX(CHR$(PEEK(ch)), "[[:punct:]]")) THEN
letter = get_odd()
PRINT CHR$(PEEK(ch));
ELSE
letter = PEEK(ch)
END IF
FREE ch
RETURN letter
END ... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Cellular_Automata is
type Petri_Dish is array (Positive range <>) of Boolean;
procedure Step (Culture : in out Petri_Dish) is
Left : Boolean := False;
This : Boolean;
Right : Boolean;
begin
for Index in Culture'First..Culture'Last - 1 ... |
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 ... | #Axiom | Axiom | NNI ==> NonNegativeInteger
RECORD ==> Record(x : List Fraction Integer, w : List Fraction Integer)
gaussCoefficients(n : NNI, eps : Fraction Integer) : RECORD ==
p := legendreP(n,z)
q := n/2*D(p, z)*legendreP(subtractIfCan(n,1)::NNI, z)
x := map(rhs,solve(p,eps))
w := [subst(1/q, z=xi) for xi in x]
[x,w]
... |
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.2B.2B | C++ | #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>
class Employee {
public :
Employee( ) { }
Employee ( const std::string &dep... |
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... | #APL | APL | oldLady←{
N←⎕TC[3]
a←'fly' 'spider' 'bird' 'cat' 'dog' 'goat' 'cow' 'horse'
v←⊂'I don''t know why she swallowed that fly - Perhaps she''ll die',N
v←v,⊂'That wiggled and jiggled and tickled inside her!'
v←v,⊂'How absurd to swallow a bird'
v←v,⊂'Imagine that! She swallowed a cat!'
v←v,⊂'What a... |
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... | #ARM_Assembly | ARM Assembly | .global _start
_start: eor r8,r8,r8 @ Verse counter
verse: add r8,r8,#1 @ Next verse
ldr r1,=lady @ There was an old lady who swallowed...
bl pstr
mov r2,r8
bl pbeast @ <an animal>
ldr r1,=comma
bl pstr
mov r2,r8
bl pverse @ Print the corresponding verse
cmp r8,#1 @ First verse?
beq verse @ Then we're not... |
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... | #Python | Python |
from functools import reduce
from operator import mul
from decimal import *
getcontext().prec = MAX_PREC
def expand(num):
suffixes = [
# (name, min_abbreviation_length, base, exponent)
('greatgross', 7, 12, 3),
('gross', 2, 12, 2),
('dozens', 3, 12, 1),
('pairs', 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:
... | #Fortran | Fortran | PROGRAM RUS
IMPLICIT NONE
REAL, PARAMETER:: E_m = 1.
REAL, PARAMETER:: E_mm = 1.E-3
REAL, PARAMETER:: E_km = 1.E+3
REAL, PARAMETER:: E_cm = 1.E-2
REAL, PARAMETER:: E_arshin = 71.12 * E_cm
REAL, PARAMETER:: E_fut = 3./7. * E_arshin
REAL, PARAMETER:: E_piad = 1./4. * E_arshin
REAL, PARAMETER:: E_vershok = 1./16.... |
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.
| #Go | Go | package main
import (
gl "github.com/chsc/gogl/gl21"
"github.com/go-gl/glfw/v3.2/glfw"
"log"
"runtime"
)
// Window dimensions.
const (
Width = 640
Height = 480
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// OpenGL requires a dedicated O... |
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... | #Common_Lisp | Common Lisp | (defun one-of-n-fn ()
(let ((cur 0) (sel nil))
#'(lambda (v)
(setq cur (+ cur 1))
(if (eql 0 (random cur)) (setq sel v))
sel)))
(defun test-one-of-n ()
(let ((counts (make-array 10 :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(fnt))
(do ((test 0 (+ 1 test)))
((eql tes... |
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... | #zkl | zkl | fcn bh(pvalues){ // Benjamini-Hochberg
psz,pszf := pvalues.len(), psz.toFloat();
n_i := psz.pump(List,'wrap(n){ pszf/(psz - n) }); # N/(N-0),N/(N-1),..
o,ro := order(pvalues,True),order(o,False); # sort pvalues, sort indices
in := psz.pump(List,'wrap(n){ n_i[n]*pvalues[o[n]] });
pmin := ... |
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
... | #Python | Python | from __future__ import print_function
def order_disjoint_list_items(data, items):
#Modifies data list in-place
itemindices = []
for item in set(items):
itemcount = items.count(item)
#assert data.count(item) >= itemcount, 'More of %r than in data' % item
lastindex = [-1]
for... |
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
... | #JavaScript | JavaScript | function sorter(table, options) {
opts = {}
opts.ordering = options.ordering || 'lexicographic';
opts.column = options.column || 0;
opts.reverse = options.reverse || false;
// ...
}
sorter(the_data, {reverse: true, ordering: 'numeric'}); |
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... | #Factor | Factor | IN: scratchpad { 2 3 } { 2 5 } before? .
t
|
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... | #FreeBASIC | FreeBASIC | Dim Shared list1(4) As Integer = {1, 2, 1, 5, 2}
Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2}
Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5}
Dim Shared list4(4) As Integer = {1, 2, 3, 4, 5}
Function Orden(listA() As Integer, listB() As Integer) As Boolean
Dim As Integer i = 0, l1, l2
l1 = Ubound(list... |
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... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var binomial = Fn.new { |n, k|
if (n == k) return 1
var prod = 1
var i = n - k + 1
while (i <= n) {
prod = prod * i
i = i + 1
}
return prod / Int.factorial(k)
}
var pascalTriangle = Fn.new { |n|
if (n <= 0) return
for (i in... |
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... | #Python | Python | 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... | #Q | Q | 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... | #Gambas | Gambas | Public Sub Main()
Dim sDict As String = File.Load(User.Home &/ "unixdict.txt") 'Store the 'Dictionary'
Dim sOrdered As New String[] 'To store ordered words
Dim sHold As New String[] 'General store
Dim sTemp As String ... |
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 ... | #Perl | Perl | # Palindrome.pm
package Palindrome;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT = qw(palindrome palindrome_c palindrome_r palindrome_e);
sub palindrome
{
my $s = (@_ ? shift : $_);
return $s eq reverse $s;
}
sub palindrome_c
{
my $s = (@_ ? shift : $_);
for my $i (0 .. length($s... |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #Ada | Ada | generic
type Real is digits <>;
with function Sqrt(X: Real) return Real;
with function "**"(X: Real; Y: Real) return Real;
package Approximation is
type Number is private;
-- create an approximation
function Approx(Value: Real; Sigma: Real) return Number;
-- unary operations and conversion Re... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// recursively permutates the list of squares to seek a matching sum
static bool soms(int n, IEnumerable<int> f) {
if (n <= 0) return false;
if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) {
case 1:... |
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... | #Bracmat | Bracmat | ( ( odd-word
= dothis doother forward backward
. ( forward
= ch
. fil$:?ch
& put$!ch
& ( low$!ch:~<a:~>z&forward$
| !ch:~"."
)
)
& ( backward
= ch
. fil$:?ch
& ( low$!ch:~<a:~>z
... |
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... | #C | C | #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
... |
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... | #ALGOL_68 | ALGOL 68 | INT stop generation = 9;
INT universe width = 20;
FORMAT alive or dead = $b("#","_")$;
BITS universe := 2r01110110101010100100;
# universe := BIN ( ENTIER ( random * max int ) ); #
INT upb universe = bits width;
INT lwb universe = bits width - universe width + 1;
PROC couple = (BITS parent, INT lwb, upb)BOOL: (
... |
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 ... | #C | C | #include <stdio.h>
#include <math.h>
#define N 5
double Pi;
double lroots[N];
double weight[N];
double lcoef[N + 1][N + 1] = {{0}};
void lege_coef()
{
int n, i;
lcoef[0][0] = lcoef[1][1] = 1;
for (n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (i = 1; i <= n; i++)
lcoef[n][i] = ((... |
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... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Serialize.Employee Extends %SerialObject
{
Method %OnNew(ByRef pId As %Integer = 0, pDepartment As %String, pName As %String) As %Status
{
Do ..IDSet(pId)
Set pId=pId+1
Do ..DepartmentSet(pDepartment)
Do ..NameSet(pName)
Quit $$$OK
}
Method Print()
{
Write "[", ..%ClassName(), "]", !
Write "- ID: "_..I... |
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... | #Common_Lisp | Common Lisp | (defmacro with-serialization-to-file ((stream pathname) &body body)
`(with-open-file (,stream ,pathname
:element-type '(unsigned-byte 8)
:direction :output
:if-exists :supersede)
,@body))
(defclass entity ()
((name :initarg :... |
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... | #AutoHotkey | AutoHotkey | Animals := [["fly", "I don't know why she swallowed the "]
, ["spider", "That wriggled and jiggled and tickled inside her"]
, ["bird", "Quite absurd"]
, ["cat", "Fancy that"]
, ["dog", "What a hog"]
, ["pig", "Her mouth was so big"]
, ["goat", "She just opened her throat"]
, ["cow", "I don't know h... |
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... | #Raku | Raku | use Rat::Precise;
my $googol = 10**100;
«PAIRs 2 SCOres 20 DOZens 12 GRoss 144 GREATGRoss 1728 GOOGOLs $googol»
~~ m:g/ ((<.:Lu>+) <.:Ll>*) \s+ (\S+) /;
my %abr = |$/.map: {
my $abbrv = .[0].Str.fc;
my $mag = +.[1];
|map { $abbrv.substr( 0, $_ ) => $mag },
.[0][0].Str.chars .. $abbrv.chars
}
... |
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:
... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim units(1 To 13) As String = {"tochka", "liniya", "dyuim", "vershok", "piad", "fut", _
"arshin", "sazhen", "versta", "milia", _
"centimeter", "meter", "kilometer"}
' all expressed in centimeters
Dim convs(1 To 13) As Single = {0.025... |
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.
| #Haskell | Haskell | import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
main = do
getArgsAndInitialize
createWindow "Triangle"
displayCallback $= display
matrixMode $= Projection
loadIdentity
ortho2D 0 30 0 30
matrixMode $= Modelview 0
mainLoop
display = do
clear [ColorBuffer]
renderPrimitive Triangles $ d... |
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... | #D | D | import std.stdio, std.random, std.algorithm;
// Zero-based line numbers.
int oneOfN(in int n) {
int choice = 0;
foreach (immutable i; 1 .. n)
if (!uniform(0, i + 1))
choice = i;
return choice;
}
void main() {
int[10] bins;
foreach (immutable i; 0 .. 1_000_000)
bins[10... |
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
... | #Racket | Racket | #lang racket
(define disjorder
(match-lambda**
(((list) n) '())
((m (list)) m)
(((list h m-tail ...) (list h n-tail ...))
(list* h (disjorder m-tail n-tail)))
;; the (not g/h) below stop greedy matching of the list which
;; would pick out orderings from the right first.
(((list h (an... |
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
... | #Raku | Raku | sub order-disjoint-list-items(\M, \N) {
my \bag = N.BagHash;
M.map: { bag{$_}-- ?? N.shift !! $_ }
}
# Testing:
for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]})
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 ... |
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
... | #jq | jq | def bar: 2 *.;
def foo: {"a": bar}; |
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
... | #Julia | Julia | sorttable(T; ordering=<, column=1, reverse=false) =
sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering)
sorttable(T, ordering=<, column=1, reverse=false) =
sorttable(T, ordering=ordering, column=column, reverse=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... | #Go | Go | package main
import "fmt"
// If your numbers happen to be in the range of Unicode code points (0 to 0x10ffff), this function
// satisfies the task:
func lessRune(a, b []rune) bool {
return string(a) < string(b) // see also bytes.Compare
}
// Otherwise, the following function satisfies the task for all integer... |
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... | #X86_Assembly | X86 Assembly |
%include "io.inc"
section .text
global CMAIN
CMAIN:
mov ebx, 7 ;size
call mloop
ret
mloop:
mov edx, 0 ;edx stands for the nth line
looping:
push ebx
push edx
call line
pop edx
pop ebx
inc edx
cmp edx, ebx
jl looping
xor eax, eax
ret
line:
mov ecx, 0 ;ecx stands for the nth character in each line
... |
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... | #Quackery | Quackery | (function arguments ...) |
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... | #Racket | Racket | (function arguments ...) |
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... | #Raku | Raku | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ... |
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... | #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
)
func main() {
// read into memory in one chunk
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
fmt.Println(err)
return
}
// split at line ends
bss := bytes.Split(b, []byte{'\n'})
// accumulate resul... |
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 ... | #Phix | Phix | function is_palindrome(sequence s)
return s==reverse(s)
end function
?is_palindrome("rotator") -- prints 1
?is_palindrome("tractor") -- prints 0
constant punctuation = " `~!@#$%^&*()-=_+[]{}\\|;:',.<>/?",
nulls = repeat("",length(punctuation))
function extra_credit(sequence s)
s = utf8_to_utf32(l... |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #ALGOL_68 | ALGOL 68 | # MODE representing a uncertain number #
MODE UNCERTAIN = STRUCT( REAL v, uncertainty );
# add a costant and an uncertain value #
OP + = ( INT c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF u + c, uncertainty OF u );
OP + = ( UNCERTAIN u, INT c )UNCERTAIN: c + u;
OP + = ( REAL c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Go | Go | package main
import (
"fmt"
"math"
"rcu"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
// recursively permutates the list of squares to seek a matching sum
func soms(n int, f []int) bool {
if n <= 0 {... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
... |
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... | #ALGOL_W | ALGOL W | begin
string(20) state;
string(20) nextState;
integer generation;
generation := 0;
state := "_###_##_#_#_#_#__#__";
while begin
write( i_w := 1, s_w := 1, "Generation ", generation, state );
nextState := "____________________";
for cPos := 1 until 18 do begin
... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #11l | 11l | F left_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x)
F mid_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x + h / 2)
F right_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x + h)
F trapezium((Float -> Float) f, Float x, Float h) -> Float
R (f(x) + f(x + h)) / 2.0
F sim... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #11l | 11l | F riseEqFall(=num)
‘Check whether a number belongs to sequence A296712.’
V height = 0
V d1 = num % 10
num I/= 10
L num != 0
V d2 = num % 10
height += (d1 < d2) - (d1 > d2)
d1 = d2
num I/= 10
R height == 0
V num = 0
F nextNum()
L
:num++
I riseEqFall(:num)
... |
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 ... | #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#include <cmath>
namespace Rosetta {
/*! Implementation of Gauss-Legendre quadrature
* http://en.wikipedia.org/wiki/Gaussian_quadrature
* http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
*
*/
template <int N>
class Gaus... |
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... | #D | D | package test;
message base1 {
required int32 i32 = 1;
}
message base2 {
repeated base1 rep = 1;
}
|
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... | #E | E | def makeEvent(time :int) {
return def event {
to __printOn(out) { out.print(`@@$time`) }
to __optUncall() { return [makeEvent, "run", [time]] }
to getTime() { return time }
}
}
def makeArrival(time :int, what :any, position :int) {
return def arrival extends makeEvent(time) {
... |
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... | #AWK | AWK |
# syntax: GAWK -f OLD_LADY_SWALLOWED_A_FLY.AWK
BEGIN {
arr[++i] = "fly/"
arr[++i] = "spider/That wriggled and jiggled and tickled inside her"
arr[++i] = "bird/Quite absurd@"
arr[++i] = "cat/Fancy that@"
arr[++i] = "dog/What a hog@"
arr[++i] = "pig/Her mouth was so big@"
arr[++i] = "goat/Op... |
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... | #REXX | REXX | /*REXX pgm converts numbers (with commas) with suffix multipliers──►pure decimal numbers*/
numeric digits 2000 /*allow the usage of ginormous numbers.*/
@.=; @.1= '2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre'
@.2= '1,567 +1.567k 0.1567e-2m'
@.3= '25.123kK 25.123m... |
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:
... | #Forth | Forth | create units s" kilometer" 2, s" meter" 2, s" centimeter" 2, s" tochka" 2, s" liniya" 2, s" diuym" 2, s" vershok" 2, s" piad" 2, s" fut" 2, s" arshin" 2, s" sazhen" 2, s" versta" 2, s" milia" 2,
create values 1000.0e f, 1.0e f, 0.01e f, 0.000254e f, 0.00254e f, 0.0254e f, 0.04445e f, 0.1778e f, 0.3048e f, 0.7112e f, 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:
... | #Frink | Frink | arshin := (2 + 1/3) ft
vershok := 1/16 arshin
sazhen := 3 arshin
verst := 1500 arshin
versta := verst
do
{
valstr = input["Enter unit of measure: ", "1 arshin"]
val = eval[valstr]
if ! (val conforms length)
println["$valstr is not a unit of length."]
} until val conforms length
println["$valstr ... |
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.
| #J | J | coclass 'example'
(coinsert[require) 'jzopengl'
create=:3 :0
ogl=: ''conew'jzopengl'
wd 'pc p;cc c isigraph opengl rightmove bottommove;pas 0 0;pshow;'
)
p_close=: destroy=:3 :0
destroy__ogl''
wd'pclose'
codestroy''
)
corner=:4 :0
glColor3d x
glVertex2d y
)
p_c_paint=:3 :0
rc__ogl''
glClear GL... |
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... | #Delphi | Delphi |
class
APPLICATION
create
make
feature
make
-- Simulates one_of_n_lines a 1000000 times.
local
t: INTEGER
simulator: ARRAY [INTEGER]
do
create simulator.make_filled (0, 1, 10)
create one.make
across
1 |..| 1000000 as c
loop
t := one.one_of_n_lines (10)
simulator [t] := sim... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Simulates one_of_n_lines a 1000000 times.
local
t: INTEGER
simulator: ARRAY [INTEGER]
do
create simulator.make_filled (0, 1, 10)
create one.make
across
1 |..| 1000000 as c
loop
t := one.one_of_n_lines (10)
simulator [t] := sim... |
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
... | #REXX | REXX | /*REXX program orders a disjoint list of M items with a list of N items. */
used = '0'x /*indicates that a word has been parsed*/
@. = /*placeholder indicates end─of─array, */
@.1 = " the cat sat on the mat | ... |
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
... | #Klingphix | Klingphix | include ..\Utilitys.tlhy
:mypower
1 tolist flatten len
1 equal
( [pop drop 2]
[pop pop drop]
) if
power
;
"2 ^2 = " print 2 mypower ?
"2 ^3 = " print ( 2 3 ) mypower ?
"End " input |
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
... | #Kotlin | Kotlin | // version 1.1.51
typealias Table = List<List<String>>
/* Note that if ordering is specified, first two parameters are ignored */
fun Table.sort(
column: Int = 0,
reverse: Boolean = false,
ordering: Comparator<List<String>> =
if (!reverse) compareBy { it[column] }
else compareByDescendi... |
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... | #Groovy | Groovy | class CList extends ArrayList implements Comparable {
CList() { }
CList(Collection c) { super(c) }
int compareTo(Object that) {
assert that instanceof List
def n = [this.size(), that.size()].min()
def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] }
comp ... |
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... | #XBasic | XBasic |
PROGRAM "pascal"
VERSION "0.0001"
DECLARE FUNCTION Entry()
FUNCTION Entry()
r@@ = UBYTE(INLINE$("Number of rows? "))
FOR i@@ = 0 TO r@@ - 1
c%% = 1
FOR k@@ = 0 TO i@@
PRINT FORMAT$("####", c%%);
c%% = c%% * (i@@ - k@@) / (k@@ + 1)
NEXT k@@
PRINT
NEXT i@@
END FUNCTION
END PROGRAM
... |
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... | #REALbasic | REALbasic | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ... |
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... | #REXX | REXX | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ... |
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... | #Ring | Ring |
The next table present operators from higher precedence (Evaluated first) to lower precedence.
Operator
. [] () {}
- ~ :Literal [list items]
++ - -
Start:End
* / %
+ -
<< >>
&
| ^
< > <= >=
= !=
not
and or
Assignment = += -= *= /= %=>>= <<= &= ^= |=
Example:
See 3+5*4 # prints 23
|
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... | #Groovy | Groovy | def isOrdered = { word -> def letters = word as List; letters == ([] + letters).sort() }
assert isOrdered('abbey')
assert !isOrdered('cat')
def dictUrl = new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt')
def orderedWords = dictUrl.readLines().findAll { isOrdered(it) }
def owMax = orderedWords*.size().max(... |
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 ... | #PHP | PHP | <?php
function is_palindrome($string) {
return $string == strrev($string);
}
?> |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #C | C |
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #jq | jq | #def squares: range(1; infinite) | . * .;
# sums of distinct squares (sods)
# Output: a stream of [$n, $sums] where $sums is the array of sods based on $n
def sods:
# input: [$n, $sums]
def next:
. as [$n, $sums]
| (($n+1)*($n+1)) as $next
| reduce $sums[] as $s ($sums + [$next];
if index($s +... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Julia | Julia | #=
Here we show all the 128 < numbers < 400 can be expressed as a sum of distinct squares. Now
11 * 11 < 128 < 12 * 12. It is also true that we need no square less than 144 (12 * 12) to
reduce via subtraction of squares all the numbers above 400 to a number > 128 and < 400 by
subtracting discrete squares of numbers ove... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SumOfSquareable]
SumOfSquareable[n_Integer] := MemberQ[Total /@ Subsets[Range[1, Floor[Sqrt[n]]]^2, {1, \[Infinity]}], n]
notsummable = {};
i = 1;
Do[
If[SumOfSquareable[i],
If[i > 1,
If[i - Max[notsummable] > Max[notsummable],
Break[]
]
]
,
AppendTo[notsummable, i]
];
i++
,
{\[Infini... |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Ma... | #Pascal | Pascal | program practicalnumbers;
{$IFDEF Windows} {$APPTYPE CONSOLE} {$ENDIF}
var
HasSum: array of byte;
function FindLongestContiniuosBlock(startIdx,MaxIdx:NativeInt):NativeInt;
var
hs0 : pByte;
l : NativeInt;
begin
l := 0;
hs0 := @HasSum[0];
for startIdx := startIdx to MaxIdx do
Begin
IF hs0[startIdx]=0 t... |
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... | #Ceylon | Ceylon |
String[] meaning = ["what,", "is,", "the;", "meaning,", "of:", "life."];
String[] kansas = ["we,", "are,", "not,", "in,", "kansas;", "any,", "more."];
shared void run() {
print("".join(reverseWords(meaning)));
print("".join(reverseWords(kansas)));
}
String[] reverseWords(String[] words)
=> recursiveRe... |
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... | #Clojure | Clojure | (defn next-char []
(char (.read *in*)))
(defn forward []
(let [ch (next-char)]
(print ch)
(if (Character/isLetter ch)
(forward)
(not= ch \.))))
(defn backward []
(let [ch (next-char)]
(if (Character/isLetter ch)
(let [result (backward)]
(print ch)
result)
(f... |
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... | #Arturo | Arturo | evolve: function [arr][
ary: [0] ++ arr ++ [0]
ret: new []
loop 1..(size ary)-2 'i [
a: ary\[i-1]
b: ary\[i]
c: ary\[i+1]
if? 2 = a+b+c -> 'ret ++ 1
else -> 'ret ++ 0
]
ret
]
printIt: function [arr][
print replace replace join map arr => [to :... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #ActionScript | ActionScript | function leftRect(f:Function, a:Number, b:Number, n:uint):Number
{
var sum:Number = 0;
var dx:Number = (b-a)/n;
for (var x:Number = a; n > 0; n--, x += dx)
sum += f(x);
return sum * dx;
}
function rightRect(f:Function, a:Number, b:Number, n:uint):Number
{
var sum:Number = 0;
var dx:Number = (b-a)/n;
for (va... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #8080_Assembly | 8080 Assembly | puts: equ 9 ; CP/M calls
putch: equ 2
org 100h
;;; Print first 200 numbers
lxi d,first
mvi c,puts
call 5
mvi b,200 ; 200 numbers
f200: push b
call next ; Get next number
call pnum ; Print the number
pop b ; Restore counter
dcr b ; Are we there yet?
jnz f200 ; If not, next number
;;; Find 10,000,000th number... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #8086_Assembly | 8086 Assembly | puts: equ 9 ; MS-DOS print string
cpu 8086
bits 16
org 100h
section .text
mov bp,98h ; BP:DI = 989680h = ten million
mov di,9680h
;;; Print first 200 numbers
mov dx,first ; Print message
mov ah,puts
int 21h
n200: call next ; Get next number
call pnum ; Print the number
cmp di,95B8h ; Have we had 200 yet?... |
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 ... | #C.23 | C# |
using System;
//Works in .NET 6+
//Tested using https://dotnetfiddle.net because im lazy
public class Program {
public static double[][] legeCoef(int N) {
//Initialising Jagged Array
double[][] lcoef = new double[N+1][];
for (int i=0; i < lcoef.Length; ++i)
lcoef[i] = new ... |
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... | #EchoLisp | EchoLisp |
(define (person->string self) (format "%a : person." (person-name self)))
(define (writer->string self) (format "%a: writer of %a."
(person-name self)
(writer-books self)))
(define (father->string self) (format "%a: father of %a."
(person-name self)
(map person-name (father-children self))))
; 'clas... |
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... | #Erlang | Erlang |
-module( object_serialization ).
-export( [task/0] ).
-record( entity, {name, date} ).
-record( person, {entity, email} ).
task() ->
Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"},
print( Person ),
Entity = #entity{name="Entity", date=20111111},
print( E... |
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... | #Babel | Babel | ((main {fly !})
(fly
{{"There was an old lady who swallowed a " <<
iter 1 - dup
<- 0 animal ! nl << ->
1 animal ! <<
{iter 10 ~=}{
" " <<
{iter 1 =}{last}{fnord} ifte
iter 1 - 0 animal ! nl <<
{"She swallowed the " <<
... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%== An "ugly" pseudo-array ===%
set pseudo=^
fly/@^
spider/That_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,@^
goat/She_just_opened_her_throat_and_swallowed_that_... |
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... | #Wren | Wren | import "/big" for BigRat
import "/str" for Str
import "/fmt" for Fmt
var abbrevs = {
"PAIRs": [4, 2], "SCOres": [3, 20], "DOZens": [3, 12],
"GRoss": [2, 144], "GREATGRoss": [7, 1728], "GOOGOLs": [6, 1e100]
}
var metric = {
"K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18,
"Z": 1e21, ... |
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:
... | #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
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.
| #Java | Java | import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class OpenGlExample {
public void run() throws LWJGLException {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
glMatrixMode(GL_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... | #Elixir | Elixir | defmodule One_of_n_lines_in_file do
def task do
dict = Enum.reduce(1..1000000, %{}, fn _,acc ->
Map.update( acc, one_of_n(10), 1, &(&1+1) )
end)
Enum.each(Enum.sort(Map.keys(dict)), fn x ->
:io.format "Line ~2w selected: ~6w~n", [x, dict[x]]
end)
end
def one_of_n( n ), do: loop( n, 2... |
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... | #Erlang | Erlang |
-module( one_of_n_lines_in_file ).
-export( [one_of_n/1, task/0] ).
one_of_n( N ) -> loop( N, 2, random:uniform(), 1 ).
task() ->
Dict = lists:foldl( fun update_counter/2, dict:new(), lists:seq(1, 1000000) ),
[io:fwrite("Line ~p selected: ~p~n", [X, dict:fetch(X, Dict)]) || X <- lists:sort(dict:fetch_keys(D... |
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
... | #Ruby | Ruby | def order_disjoint(m,n)
print "#{m} | #{n} -> "
m, n = m.split, n.split
from = 0
n.each_slice(2) do |x,y|
next unless y
sd = m[from..-1]
if x > y && (sd.include? x) && (sd.include? y) && (sd.index(x) > sd.index(y))
new_from = m.index(x)+1
m[m.index(x)+from], m[m.index(y)+from] = m[m.inde... |
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
... | #Lasso | Lasso | define sortarray( // params are set by position
items::array, // required param
ordering::string = 'lexicographic', // optional param
column::integer = 1,
reverse::boolean = false
) => {
// sorting process
local(sorteditems = array)
// Lasso has no build in method to sort an array of arrays by position in the c... |
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
... | #Logo | Logo | to sort :table [:column 1] [:ordering "before?] [:reverse "false]
; ...
end |
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... | #Haskell | Haskell | Prelude> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False |
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... | #XPL0 | XPL0 | include c:\cxpl\codes;
proc Pascal(N); \Display the first N rows of Pascal's triangle
int N; \if N<=0 then nothing is displayed
int Row, I, Old(40), New(40);
[for Row:= 0 to N-1 do
[New(0):= 1;
for I:= 1 to Row do New(I):= Old(I-1) + Old(I);
for I:= 1 to (N-Row-1)*2 d... |
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... | #Ruby | Ruby | $ syntax expr: .(). + .() is -> 7; |
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... | #Scala | Scala | $ syntax expr: .(). + .() is -> 7; |
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... | #Scheme | Scheme | $ syntax expr: .(). + .() is -> 7; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.