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/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Icon_and_Unicon | Icon and Unicon | procedure main()
EvalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
end
link printf
invocable all
procedure EvalRPN(expr) #: evaluate (and trace stack) an RPN string
stack := []
expr ? until pos(0) do {
tab(many(' ')) # consume previous seperator
token := tab(upto(' ')|0)... |
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 ... | #ARM_Assembly | ARM Assembly | @ Check whether the ASCII string in [r0] is a palindrome
@ Returns with zero flag set if palindrome.
palin: mov r1,r0 @ Find end of string
1: ldrb r2,[r1],#1 @ Grab character and increment pointer
tst r2,r2 @ Zero yet?
bne 1b @ If not try next byte
sub r1,r1,#2 @ Move R1 to last actual character.
2: cmp r0,r1 @ ... |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Pascal | Pascal | 9 : 96878077087869
9 : 9687870990787869
9 : 968787783387787869 |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #PicoLisp | PicoLisp | (de operator (Op)
(member Op '("\^" "*" "/" "+" "-")) )
(de leftAssoc (Op)
(member Op '("*" "/" "+" "-")) )
(de precedence (Op)
(case Op
("\^" 4)
(("*" "/") 3)
(("+" "-") 2) ) )
(de shuntingYard (Str)
(make
(let (Fmt (-7 -30 -4) Stack)
(tab Fmt "Token" "Output" "Stack... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #PL.2FI | PL/I |
cvt: procedure options (main); /* 15 January 2012. */
declare (in, stack, out) character (100) varying;
declare (ch, chs) character (1);
declare display bit (1) static initial ('0'b);
in = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3';
in = '(' || in || ' ) '; /* Initialize with parenth... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #Ruby | Ruby | MAX_N = 500
BRANCH = 4
def tree(br, n, l=n, sum=1, cnt=1)
for b in br+1 .. BRANCH
sum += n
return if sum >= MAX_N
# prevent unneeded long math
return if l * 2 >= sum and b >= BRANCH
if b == br + 1
c = $ra[n] * cnt
else
c = c * ($ra[n] + (b - br - 1)) / (b - br)
end
$unroo... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Component_Pascal | Component Pascal |
MODULE BbtPangramChecker;
IMPORT StdLog,DevCommanders,TextMappers;
PROCEDURE Check(str: ARRAY OF CHAR): BOOLEAN;
CONST
letters = 26;
VAR
i,j: INTEGER;
status: ARRAY letters OF BOOLEAN;
resp : BOOLEAN;
BEGIN
FOR i := 0 TO LEN(status) -1 DO status[i] := FALSE END;
FOR i := 0 TO LEN(str) - 1 DO
j := ORD(C... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Lua | Lua | function factorial (n)
local f = 1
for i = 2, n do
f = f * i
end
return f
end
function binomial (n, k)
if k > n then return 0 end
return factorial(n) / (factorial(k) * factorial(n - k))
end
function pascalMatrix (form, size)
local matrix = {}
for row = 1, size do
mat... |
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... | #E | E | def pascalsTriangle(n, out) {
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
for y in 1..n {
out.print("<tr>")
row.push(1)
def skip := n - y
if (skip > 0) {
out.print(`<td colspan="$skip"></td>`)
... |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Ruby | Ruby | rpn = RPNExpression.new("3 4 2 * 1 5 - 2 3 ^ ^ / +")
infix = rpn.to_infix
ruby = rpn.to_ruby |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Sidef | Sidef | func p(pair, prec) {
pair[0] < prec ? "( #{pair[1]} )" : pair[1]
}
func rpm_to_infix(string) {
say "#{'='*17}\n#{string}"
var stack = []
string.each_word { |w|
if (w ~~ /\d/) {
stack << [9, Num(w)]
}
else {
var y = stack.pop
var x = stack.pop... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Raku | Raku | sub fs ( Code $f, @s ) { @s.map: { .$f } }
sub f1 ( $n ) { $n * 2 }
sub f2 ( $n ) { $n ** 2 }
my &fsf1 := &fs.assuming(&f1);
my &fsf2 := &fs.assuming(&f2);
for [1..3], [2, 4 ... 8] X &fsf1, &fsf2 -> ($s, $f) {
say $f.($s);
} |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Ring | Ring |
# Project : Password generator
chars = list(4)
strp = list(2)
password = ""
chars[1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars[2] = "abcdefghijklmnopqrstuvwxyz"
chars[3] = "0123456789"
chars[4] = "!\#$%&'()*+,-./:;<=>?@[]^_{|}~"
init()
plen = number(strp[1])
for n = 1 to strp[2]
passwords(chars)
see "passw... |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your p... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Function Matches(a As Byte(), b As Byte()) As Boolean
For i = 0 To 31
If a(i) <> b(i) Then
Return False
End If
Next
Return True
End Function
Function StringHashToByteArray(s As String) As Byte()
... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Rust | Rust |
//! This solution uses [rayon](https://github.com/rayon-rs/rayon), a data-parallelism library.
//! Since Rust guarantees that a program has no data races, adding parallelism to a sequential
//! computation is as easy as importing the rayon traits and calling the `par_iter()` method.
extern crate rayon;
extern cra... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #SequenceL | SequenceL | import <Utilities/Conversion.sl>;
import <Utilities/Math.sl>;
import <Utilities/Sequence.sl>;
main(args(2)) :=
let
inputs := stringToInt(args);
factored := primeFactorization(inputs);
minFactors := vectorMin(factored);
indexOfMax := firstIndexOf(minFactors, vectorMax(minFactors));
in
"Number " ++ intT... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #J | J | a: , <;._1 ' ' , '3 4 2 * 1 5 - 2 3 ^ ^ / +'
┌┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
││3│4│2│*│1│5│-│2│3│^│^│/│+│
└┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Java_2 | Java |
import java.util.LinkedList;
public class RPN{
public static void main(String[] args) {
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +");
}
private static void evalRPN(String expr){
LinkedList<Double> stack = new LinkedList<Double>();
System.out.println("Input\tOperation\tStack after");
for (String token : expr.sp... |
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 ... | #Arturo | Arturo | palindrome?: $[seq] -> seq = reverse seq
loop ["abba" "boom" "radar" "civic" "great"] 'wrd [
print [wrd ": palindrome?" palindrome? wrd]
] |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use constant Inf => 1e10;
sub is_p_gapful {
my($d,$n) = @_;
return '' unless 0 == $n % 11;
my @digits = split //, $n;
$d eq $digits[0] and (0 == $n % ($digits[0].$digits[-1])) and $n eq join '', reverse @digits;
}
for ([1, 20], [86, 15]) {
my($offs... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Python | Python | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(p... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #Scala | Scala | object Paraffins extends App {
val (nMax, nBranches) = (250, 4)
val rooted, unrooted = Array.tabulate(nMax + 1)(i => if (i < 2) BigInt(1) else BigInt(0))
val (unrooted, c) = (rooted.clone(), new Array[BigInt](nBranches))
for (n <- 1 to nMax) {
def tree(br: Int, n: Int, l: Int, inSum: Int, cnt: BigInt): Un... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Cowgol | Cowgol | include "cowgol.coh";
sub pangram(str: [uint8]): (r: uint8) is
var letters: uint8[26];
MemZero(&letters[0], 26);
loop
var chr := [str];
if chr == 0 then break; end if;
str := @next str;
chr := (chr | 32) - 'a';
if chr >= 26 then continue; end if;
letters[c... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Crystal | Crystal | def pangram?(sentence)
('a'..'z').all? {|c| sentence.downcase.includes?(c) }
end
p pangram?("not a pangram")
p pangram?("The quick brown fox jumps over the lazy dog.") |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Maple | Maple |
PascalUT := proc(n::integer)
local M := Matrix(n,n):
local i:
local j:
M[1,1..n] := 1:
for j from 2 to n do
for i from 2 to n do
M[i,j] := M[i,j-1] + M[i-1,j-1]:
end:
end:
return M:
end proc:
PascalUT(5);
PascalLT := proc(n::integer)
local M := Matrix(n,n):
local i:
local j:
M[1..n,1] := 1:
for... |
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... | #Eiffel | Eiffel |
note
description : "Prints pascal's triangle"
output : "[
Per requirements of the RosettaCode example, execution will print the first n rows of pascal's triangle
]"
date : "19 December 2013"
authors : "Sandro Meier", "Roman Brunner"
revision : "1.0"
libraries... |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Tcl | Tcl | package require Tcl 8.5
# Helpers
proc precassoc op {
dict get {^ {4 right} * {3 left} / {3 left} + {2 left} - {2 left}} $op
}
proc pop stk {
upvar 1 $stk s
set val [lindex $s end]
set s [lreplace $s end end]
return $val
}
proc rpn2infix rpn {
foreach token $rpn {
switch $token {
"^" -... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #REXX | REXX | /*REXX program demonstrates a method of a partial function application. */
s=; do a=0 to 3 /*build 1st series of some low integers*/
s=strip(s a) /*append to the integer to the S list*/
end /*a*/
call fs 'f1',s; say 'for f1: series=' s", r... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Ruby | Ruby | ARRS = [("a".."z").to_a,
("A".."Z").to_a,
("0".."9").to_a,
%q(!"#$%&'()*+,-./:;<=>?@[]^_{|}~).chars] # " quote to reset clumsy code colorizer
ALL = ARRS.flatten
def generate_pwd(size, num)
raise ArgumentError, "Desired size too small" unless size >= ARRS.size
num.times.map do
arr = A... |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your p... | #Wren | Wren | import "/crypto" for Sha256
var hashes = [
"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
]
var findHash = Fn.new { |i|
var bytes = List.filled(... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Sidef | Sidef | var nums = [1275792312878611, 12345678915808973,
1578070919762253, 14700694496703910,];
var factors = nums.map {|n| prime_factors.ffork(n) }.map { .wait }
say ((nums ~Z factors)->max_by {|m| m[1][0] }) |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Standard_ML | Standard ML |
structure TTd = Thread.Thread ;
structure TTm = Thread.Mutex ;
val threadedBigPrime = fn input:IntInf.int list =>
let
(* --------------------- code from prime decomposition page ------------------- *)
val factor = fn n :IntInf.int =>
let
val unfactored = fn (u,_,_) => u; val factors = fn... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #JavaScript | JavaScript |
const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
const s = [], tokens = e.split(' ');
for (const t of tokens) {
const n = Number(t);
if (!isNaN(n)) {
s.push(n);
} else {
if (s.length < 2) {
throw new Error(`${t}: ${s}: insufficient operands.`);
}
const o2 = s.pop(), o1 = s.pop();
switch (t) {
... |
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 ... | #AutoHotkey | AutoHotkey | IsPalindrome(Str){
Loop, Parse, Str
ReversedStr := A_LoopField . ReversedStr
return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False"
} |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Phix | Phix | with javascript_semantics
function reverse_n(atom s)
atom e = 0
while s>0 do
e = e*10 + remainder(s,10)
s = floor(s/10)
end while
return e
end function
constant mx = 1000,
data = {{1, 20, "%7d "}, {86, 100, "%8d "}, {991, 1000, "%10d "}}
include builtins\ordinal.e
function ... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Racket | Racket |
#lang racket
;print column of width w
(define (display-col w s)
(let* ([n-spaces (- w (string-length s))]
[spaces (make-string n-spaces #\space)])
(display (string-append s spaces))))
;print columns given widths (idea borrowed from PicoLisp)
(define (tab ws . ss) (for-each display-col ws ss) (newline))... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const integer: max_n is 500;
const integer: branch is 4;
var array bigInteger: rooted is max_n times 0_;
var array bigInteger: unrooted is max_n times 0_;
const proc: tree (in integer: br, in integer: n, in integer: l, in var integer: sum, in bigInteger: cnt) is f... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #Tcl | Tcl | package require Tcl 8.5
set maxN 200
set rooted [lrepeat $maxN 0]
lset rooted 0 1; lset rooted 1 1
set unrooted $rooted
proc choose {m k} {
if {$k == 1} {
return $m
}
for {set r $m; set i 1} {$i < $k} {incr i} {
set r [expr {$r * ($m+$i) / ($i+1)}]
}
return $r
}
proc tree {br n cnt sum l} {
... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #D | D | bool isPangram(in string text) pure nothrow @safe @nogc {
uint bitset;
foreach (immutable c; text) {
if (c >= 'a' && c <= 'z')
bitset |= (1u << (c - 'a'));
else if (c >= 'A' && c <= 'Z')
bitset |= (1u << (c - 'A'));
}
return bitset == 0b11_11111111_11111111_11... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | symPascal[size_] := NestList[Accumulate, Table[1, {k, size}], size - 1]
upperPascal[size_] := CholeskyDecomposition[symPascal@size]
lowerPascal[size_] := Transpose@CholeskyDecomposition[symPascal@size]
Column[MapThread[
Labeled[Grid[#1@5], #2, Top] &, {{upperPascal, lowerPascal,
symPascal}, {"Upper", "Lowe... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Nim | Nim | import math, sequtils, strutils
type SquareMatrix = seq[seq[Natural]]
func newSquareMatrix(n: Positive): SquareMatrix =
## Create a square matrix.
newSeqWith(n, newSeq[Natural](n))
func pascalUpperTriangular(n: Positive): SquareMatrix =
## Create an upper Pascal matrix.
result = newSquareMatrix(n)
for i... |
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... | #Elixir | Elixir | defmodule Pascal do
def triangle(n), do: triangle(n,[1])
def triangle(0,list), do: list
def triangle(n,list) do
IO.inspect list
new_list = Enum.zip([0]++list, list++[0]) |> Enum.map(fn {a,b} -> a+b end)
triangle(n-1,new_list)
end
end
Pascal.triangle(8) |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #TXR | TXR | ;; alias for circumflex, which is reserved syntax
(defvar exp (intern "^"))
(defvar *prec* ^((,exp . 4) (* . 3) (/ . 3) (+ . 2) (- . 2)))
(defvar *asso* ^((,exp . :right) (* . nil)
(/ . :left) (+ . nil) (- . :left)))
(defun debug-print (label val)
(format t "~a: ~a\n" label val)
val)
(defun... |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Visual_Basic_.NET | Visual Basic .NET | Option Strict On
Imports System.Text.RegularExpressions
Module Module1
Class Operator_
Sub New(t As Char, p As Integer, Optional i As Boolean = False)
Token = t
Precedence = p
IsRightAssociative = i
End Sub
Property Token As Char
Get
... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Ruby | Ruby | fs = proc { |f, s| s.map &f }
f1 = proc { |n| n * 2 }
f2 = proc { |n| n ** 2 }
fsf1 = fs.curry[f1]
fsf2 = fs.curry[f2]
[0..3, (2..8).step(2)].each do |e|
p fsf1[e]
p fsf2[e]
end |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Run_BASIC | Run BASIC | a$(1) = "0123456789"
a$(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a$(3) = "abcdefghijklmnopqrstuvwxyz"
a$(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~"
a$(0) = a$(1) + a$(2) + a$(3) + a$(4)
[main]
print "----------- Password Generator -----------"
input "Number of Characters:";howBig
if howBig < 1 then goto [exit]
input "How many... |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your p... | #zkl | zkl | var [const] MsgHash=Import.lib("zklMsgHash");
var [const] gotEm=Atomic.Int(); // global signal for all threads
const THREADS=9, // how we will split task, THREADS<=26
CHR_a="a".toAsc();
fcn crack(c,n,hashes){ // thread
sha256:=MsgHash.SHA256; // the SHA-256 hash method, byte bucket
bytes,hash := Data(... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Swift | Swift | import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
va... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Tcl | Tcl | package require Tcl 8.6
package require Thread
# Pooled computation engine; runs event loop internally
namespace eval pooled {
variable poolSize 3; # Needs to be tuned to system size
proc computation {computationDefinition entryPoint values} {
variable result
variable poolSize
# Add communication shim
a... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Julia | Julia | function rpn(s)
stack = Any[]
for op in map(eval, map(parse, split(s)))
if isa(op, Function)
arg2 = pop!(stack)
arg1 = pop!(stack)
push!(stack, op(arg1, arg2))
else
push!(stack, op)
end
println("$op: ", join(stack, ", "))
end
... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Kotlin | Kotlin | // version 1.1.2
fun rpnCalculate(expr: String) {
if (expr.isEmpty()) throw IllegalArgumentException("Expresssion cannot be empty")
println("For expression = $expr\n")
println("Token Action Stack")
val tokens = expr.split(' ').filter { it != "" }
val stack = mutableListOf<Dou... |
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 ... | #AutoIt | AutoIt | ;== AutoIt Version: 3.3.8.1
Global $aString[7] = [ _
"In girum imus nocte, et consumimur igni", _ ; inexact palindrome
"Madam, I'm Adam.", _ ; inexact palindrome
"salàlas", _ ; exact palindrome
"radar", _ ; exact palindrome
"... |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Prolog | Prolog | init_palindrome(Digit, p(10, Next, 0)):-
Next is Digit * 10 - 1.
next_palindrome(Digit, p(Power, Next, Even), p(Power1, Next2, Even1), Palindrome):-
Next1 is Next + 1,
(Next1 is Power * (Digit + 1) ->
(Even == 1 -> Power1 is Power * 10 ; Power1 = Power),
Next2 is Digit * Power1,
Ev... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Raku | Raku | my %prec =
'^' => 4,
'*' => 3,
'/' => 3,
'+' => 2,
'-' => 2,
'(' => 1;
my %assoc =
'^' => 'right',
'*' => 'left',
'/' => 'left',
'+' => 'left',
'-' => 'left';
sub shunting-yard ($prog) {
my @inp = $prog.words;
my @ops;
my @res;
sub report($op) { printf "... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var branches = 4
var nMax = 250
var rooted = List.filled(nMax + 1, BigInt.zero)
var unrooted = List.filled(nMax + 1, BigInt.zero)
var c = List.filled(branches, BigInt.zero)
var tree
tree = Fn.new { |br, n, l, sum, cnt|
var b = br + 1
while (b <= branches) {
... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Delphi | Delphi | program PangramChecker;
{$APPTYPE CONSOLE}
uses StrUtils;
function IsPangram(const aString: string): Boolean;
var
c: char;
begin
for c := 'a' to 'z' do
if not ContainsText(aString, c) then
Exit(False);
Result := True;
end;
begin
Writeln(IsPangram('The quick brown fox jumps over the lazy dog'... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Draco | Draco | proc nonrec pangram(*char s) bool:
ulong letters;
char c;
byte b;
byte A = pretend('a', byte);
byte Z = pretend('z', byte);
letters := 0L0;
while
c := s*;
s := s + 1;
c /= '\e'
do
b := pretend(c, byte) | 32;
if b >= A and b <= Z then
... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #PARI.2FGP | PARI/GP |
Pl(n)={matpascal(n-1)}
printf("%d",Pl(5))
|
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... | #Emacs_Lisp | Emacs Lisp | (require 'cl-lib)
(defun next-row (row)
(cl-mapcar #'+ (cons 0 row)
(append row '(0))))
(defun triangle (row rows)
(if (= rows 0)
'()
(cons row (triangle (next-row row) (- rows 1))))) |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Wren | Wren | import "/seq" for Stack
import "/pattern" for Pattern
class Expression {
static ops { "-+/*^" }
construct new(ex, op, prec) {
_ex = ex
_op = op
_prec = prec
}
static build(e1, e2, o) { new("%(e1) %(o) %(e2)", o, (ops.indexOf(o)/2).floor) }
ex { _ex }
ex=(other) { ... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Scala | Scala | def fs[X](f:X=>X)(s:Seq[X]) = s map f
def f1(x:Int) = x * 2
def f2(x:Int) = x * x
def fsf[X](f:X=>X) = fs(f) _
val fsf1 = fsf(f1) // or without the fsf intermediary: val fsf1 = fs(f1) _
val fsf2 = fsf(f2) // or without the fsf intermediary: val fsf2 = fs(f2) _
assert(fsf1(List(0,1,2,3)) == List(0,2,4,6))
assert(fsf... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Sidef | Sidef | func fs(f) {
func(*args) {
args.map {f(_)}
}
}
func double(n) { n * 2 };
func square(n) { n ** 2 };
var fs_double = fs(double);
var fs_square = fs(square);
var s = (0 .. 3);
say "fs_double(#{s}): #{fs_double(s...)}";
say "fs_square(#{s}): #{fs_square(s...)}";
s = [2, 4, 6, 8];
say "fs_double(#{... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Rust | Rust |
use rand::distributions::Alphanumeric;
use rand::prelude::IteratorRandom;
use rand::{thread_rng, Rng};
use std::iter;
use std::process;
use structopt::StructOpt;
const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
// the core logic that creates our password
fn generate_password(length: u8) -> String {
... |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Wren | Wren | /* parallel_calculations.wren */
import "./math" for Int
class C {
static minPrimeFactor(n) { Int.primeFactors(n)[0] }
static allPrimeFactors(n) { Int.primeFactors(n) }
} |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #zkl | zkl | fcn factorize(x,y,z,etc){
xyzs:=vm.arglist;
fs:=xyzs.apply(factors.strand) // queue up factorizing for x,y,...
.apply("noop") // wait for all threads to finish factoring
.apply(fcn{ (0).min(vm.arglist) }); // find minimum factor for x,y...
[0..].zip(fs).filter(fcn([(n,x)],M){ x==M }.fp1((0).ma... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Lambdatalk | Lambdatalk |
{calc 3 4 2 * 1 5 - 2 3 pow pow / +}
->
3:
4: 3
2: 4 3
*: 2 4 3
1: 8 3
5: 1 8 3
-: 5 1 8 3
2: -4 8 3
3: 2 -4 8 3
pow: 3 2 -4 8 3
pow: 8 -4 8 3
/: 65536 8 3
+: 0.0001220703125 3
-> 3.0001220703125
where
{def calc
{def calc.r
{lambda {:x :s}
{if {empty? :x}
then -> {car :s}
... |
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 ... | #AWK | AWK | function is_palindro(s)
{
if ( s == reverse(s) ) return 1
return 0
} |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Python | Python | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_ge... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #REXX | REXX | /*REXX pgm converts infix arith. expressions to Reverse Polish notation (shunting─yard).*/
parse arg x /*obtain optional argument from the CL.*/
if x='' then x= '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' /*Not specified? Then use the default.*/
ox=x
x='(' space(x) ") " ... |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bo... | #zkl | zkl | var BN=Import("zklBigNum");
const nMax=100, nBranches=4;
var rooted =(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0)),
unrooted=(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0));
rooted[0]=BN(1); rooted[1]=BN(1); unrooted[0]=BN(1); unrooted[1]=BN(1);
fcn tree(br,n,l,inSum,cnt){
var c=(nBranches).... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #E | E | def isPangram(sentence :String) {
return ("abcdefghijklmnopqrstuvwxyz".asSet() &! sentence.toLowerCase().asSet()).size() == 0
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #EDSAC_order_code | EDSAC order code |
[Pangram checker for Rosetta Code.
EDSAC program, Initial Orders 2.]
[Outline: Make a table, one entry per 5-bit character code.
Initialize entry for each letter to 1.
When a letter is read, convert its entry to 0.]
[Subroutine to read string from the input and
store it with character codes in low 5 ... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Pascal | Pascal | program Pascal_matrix(Output);
const N = 5;
type NxN_Matrix = array[0..N,0..N] of integer;
var PM,PX : NxN_Matrix;
function Pascal_sym(x : integer; p : NxN_Matrix) : NxN_Matrix;
var I,J : integer;
begin
for I := 1 to x do
begin
for J := 1 to x do p[I,J] := p[I-1,J]+p[I,J-1]
end;
Pascal_s... |
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... | #Erlang | Erlang |
-import(lists).
-export([pascal/1]).
pascal(1)-> [[1]];
pascal(N) ->
L = pascal(N-1),
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
|
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #zkl | zkl | tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +","1 2 + 3 4 + ^ 5 6 + ^");
var opa=D(
"^",T(4, True),
"*",T(3, False), "/",T(3, False),
"+",T(2, False), "-",T(2, False) );
const nPrec = 9;
foreach t in (tests) { parseRPN(t) }
fcn parseRPN(e){
println("\npostfix:", e);
stack:=L();
foreach tok in (e.split(... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Smalltalk | Smalltalk |
| f1 f2 fs fsf1 fsf2 partial |
partial := [ :afs :af | [ :s | afs value: af value: s ] ].
fs := [ :f :s | s collect: [ :x | f value: x ]].
f1 := [ :x | x * 2 ].
f2:= [ :x | x * x ].
fsf1 := partial value: fs value: f1.
fsf2 := partial value: fs value: f2.
fsf1 value: (0 to: 3).
" #(0 2 4 6)"
fsf2 value: (0 to:... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Tcl | Tcl | package require Tcl 8.6
proc partial {f1 f2} {
variable ctr
coroutine __curry[incr ctr] apply {{f1 f2} {
for {set x [info coroutine]} 1 {} {
set x [{*}$f1 $f2 [yield $x]]
}
}} $f1 $f2
} |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Scala | Scala | object makepwd extends App {
def newPassword( salt:String = "", length:Int = 13, strong:Boolean = true ) = {
val saltHash = salt.hashCode & ~(1 << 31)
import java.util.Calendar._
val cal = java.util.Calendar.getInstance()
val rand = new scala.util.Random((cal.getTimeInMillis+saltHash).toLong)
... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Liberty_BASIC | Liberty BASIC |
global stack$
expr$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
print "Expression:"
print expr$
print
print "Input","Operation","Stack after"
stack$=""
token$ = "#"
i = 1
token$ = word$(expr$, i)
token2$ = " "+token$+" "
do
print "Token ";i;": ";token$,
select case
'operation
case instr("+-*/^",token$)<>0
... |
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 ... | #BaCon | BaCon |
OPTION COMPARE TRUE
INPUT "Enter your line... ", word$
IF word$ = REVERSE$(word$) THEN
PRINT "This is an exact palindrome!"
ELIF EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE) = REVERSE$(EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE)) THEN
PRINT "This is an inexact palindrome!"
ELSE
PRINT "Not a p... |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #Raku | Raku | constant @digits = '0','1','2','3','4','5','6','7','8','9';
# Infinite lazy iterator to generate palindromic "gap" numbers
my @npal = flat [ @digits ], [ '00','11','22','33','44','55','66','77','88','99' ],
{
sink @^previous, @^penultimate;
[ flat @digits.map: -> \digit { @penultimate.map: digit ~ * ~ digit... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Ruby | Ruby | rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3") |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Rust | Rust | type Number = f64;
#[derive(Debug, Copy, Clone, PartialEq)]
struct Operator {
token: char,
operation: fn(Number, Number) -> Number,
precedence: u8,
is_left_associative: bool,
}
#[derive(Debug, Clone, PartialEq)]
enum Token {
Digit(Number),
Operator(Operator),
LeftParen,
RightParen,
}... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Elixir | Elixir | defmodule Pangram do
def checker(str) do
unused = Enum.to_list(?a..?z) -- to_char_list(String.downcase(str))
Enum.empty?(unused)
end
end
text = "The quick brown fox jumps over the lazy dog."
IO.puts "#{Pangram.checker(text)}\t#{text}"
text = (Enum.to_list(?A..?Z) -- 'Test') |> to_string
IO.puts "#{Pangram... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Erlang | Erlang | -module(pangram).
-export([is_pangram/1]).
is_pangram(String) ->
ordsets:is_subset(lists:seq($a, $z), ordsets:from_list(string:to_lower(String))). |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
sub upper {
my ($i, $j) = @_;
my @m;
for my $x (0 .. $i - 1) {
for my $y (0 .. $j - 1) {
$m[$x][$y] = $x > $y ? 0
: ! $x || $x == $y ? 1
: $m[$x-... |
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... | #ERRE | ERRE |
PROGRAM PASCAL_TRIANGLE
PROCEDURE PASCAL(R%)
LOCAL I%,C%,K%
FOR I%=0 TO R%-1 DO
C%=1
FOR K%=0 TO I% DO
WRITE("###";C%;)
C%=(C%*(I%-K%)) DIV (K%+1)
END FOR
PRINT
END FOR
END PROCEDURE
BEGIN
PASCAL(9)
END PROGRAM
|
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #TXR | TXR | $ txr -p "(mapcar (op mapcar (op * 2)) (list (range 0 3) (range 2 8 2)))"
((0 2 4 6) (4 8 12 16))
$ txr -p "(mapcar (op mapcar (op * @1 @1)) (list (range 0 3) (range 2 8 2)))"
((0 1 4 9) (4 16 36 64)) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Visual_Basic_.NET | Visual Basic .NET | Module PartialApplication
Function fs(Of TSource, TResult)(f As Func(Of TSource, TResult), s As IEnumerable(Of TSource)) As IEnumerable(Of TResult)
' This is exactly what Enumerable.Select does.
Return s.Select(f)
End Function
Function f1(x As Integer) As Integer
Return x * 2
E... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: generate (in integer: length) is func
result
var string: password is "";
local
const set of char: allowed is {'!' .. '~'} - {'\\', '`'};
const set of char: special is allowed - {'A' .. 'Z'} | {'a' .. 'z'} | {'0' .. '9'};
var integer: index is 0;
var... |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #Lua | Lua |
local stack = {}
function push( a ) table.insert( stack, 1, a ) end
function pop()
if #stack == 0 then return nil end
return table.remove( stack, 1 )
end
function writeStack()
for i = #stack, 1, -1 do
io.write( stack[i], " " )
end
print()
end
function operate( a )
local s
if a == "... |
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 ... | #Bash | Bash |
#! /bin/bash
# very simple way to detect a palindrome in Bash
# output of bash --version -> GNU bash, version 4.4.7(1)-release x86_64 ...
echo "enter a string"
read input
size=${#input}
count=0
while (($count < $size))
do
array[$count]=${input:$count:1}
(( count+=1 ))
done
count=0
for ((i=0 ; i < $s... |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible mea... | #REXX | REXX | /*REXX program computes and displays palindromic gapful numbers, it also can show those */
/*─────────────────────── palindromic gapful numbers listed by their last decimal digit.*/
numeric digits 20 /*ensure enough decimal digits gapfuls.*/
parse arg palGaps ... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #Sidef | Sidef | var prec = Hash(
'^' => 4,
'*' => 3,
'/' => 3,
'+' => 2,
'-' => 2,
'(' => 1,
)
var assoc = Hash(
'^' => 'right',
'*' => 'left',
'/' => 'left',
'+' => 'left',
'-' => 'left',
)
func shunting_yard(prog) {
var inp = prog.words
var ops = []
var res = []
func ... |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Excel | Excel | ISPANGRAM
=LAMBDA(s,
LET(
abc, CHARS(LOWER("abcdefghijklmnopqrstuvwxyz")),
AND(
LAMBDA(c,
ISNUMBER(SEARCH(c, s, 1))
)(
abc
)
)
)
) |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #F.23 | F# | let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Phix | Phix | function pascal_upper(integer n)
sequence res = repeat(repeat(0,n),n)
res[1] = repeat(1,n)
for i=2 to n do
for j=2 to i do
res[j,i] = res[j,i-1]+res[j-1,i-1]
end for
end for
return res
end function
function pascal_lower(integer n)
sequence res = repeat(repeat(0,n),n... |
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... | #Euphoria | Euphoria | sequence row
row = {}
for m = 1 to 10 do
row = row & 1
for n = length(row)-1 to 2 by -1 do
row[n] += row[n-1]
end for
print(1,row)
puts(1,'\n')
end for |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Wren | Wren | var fs = Fn.new { |f, s| s.map { |e| f.call(e) }.toList }
var f1 = Fn.new { |n| 2 * n }
var f2 = Fn.new { |n| n * n }
var partial = Fn.new { |f, g| Fn.new { |x| f.call(g, x) } }
var ss = [[0, 1, 2, 3], [2, 4, 6, 8]]
for (s in ss) {
var fsf1 = partial.call(fs, f1)
var fsf2 = partial.call(fs, f2)
System.p... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #zkl | zkl | fcn fs(f,s){s.apply(f)} fcn f1(n){n*2} fcn f2(n){n*n}
var fsf1=fs.fp(f1), fsf2=fs.fp(f2);
fsf1([0..3]); //-->L(0,2,4,6)
fsf2([2..8,2]); //-->L(4,16,36,64) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.