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/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 ...
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;; Is the $-terminated string at DE a palindrome? ;;; Returns: zero flag set if palindrome palin: mov h,d ; Find end of string mov l,e mvi a,'$' cmp m ; The empty string is a palindrome rz pend: inx h ; Scan until terminator found cmp m jnz pend dcx h ; Move to last byte of text ptest: lda...
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...
#Factor
Factor
USING: formatting fry io kernel lists lists.lazy locals math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.palindromic-gapful-numbers   ! Palindromic numbers are relatively rare compared to gapful ! numbers, so our strategy for finding palindromic gapful ! numbers is to filter gapf...
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...
#Java
Java
import java.util.Stack;   public class ShuntingYard {   public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix:  %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); }   static String infixToPostfix(Stri...
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...
#Kotlin
Kotlin
// version 1.1.4-3   import java.math.BigInteger   const val MAX_N = 250 const val BRANCHES = 4   val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO } val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO } val c = Array(BRANCHES) { BigInteger.ZERO }   fun tree...
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...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { allChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; print isPangram("The quick brown fox jumps over the lazy dog."); print isPangram("The quick brown fo."); }   function isPangram(string) { delete X; for (k=1; k<length(string); k++) { X[toupper(substr(string,k,1))]++; # histogram ...
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...
#BASIC
BASIC
DECLARE FUNCTION IsPangram! (sentence AS STRING)   DIM x AS STRING   x = "My dog has fleas." GOSUB doIt x = "The lazy dog jumps over the quick brown fox." GOSUB doIt x = "Jackdaws love my big sphinx of quartz." GOSUB doIt x = "What's a jackdaw?" GOSUB doIt   END   doIt: PRINT IsPangram!(x), x RETURN   FUNCTION ...
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...
#Fortran
Fortran
module pascal   implicit none   contains function pascal_lower(n) result(a) integer :: n, i, j integer, allocatable :: a(:, :) allocate(a(n, n)) a = 0 do i = 1, n a(i, 1) = 1 end do do i = 2, n do j = 2, i a(i, j) = a(i ...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#PureBasic
PureBasic
UseSQLiteDatabase()   Procedure CheckDatabaseUpdate(database, query$) result = DatabaseUpdate(database, query$) If result = 0 PrintN(DatabaseError()) EndIf   ProcedureReturn result EndProcedure     If OpenConsole() If OpenDatabase(0, ":memory:", "", "") ;create players table with sample data Check...
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...
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include<cstdio> using namespace std; void Pascal_Triangle(int size) {   int a[100][100]; int i, j;   //first row and first coloumn has the same value=1 for (i = 1; i <= size; i++) { a[i][1] = a[1][i] = 1; }   //Generate the full Triangle for (i = 2; i <= size; i++) { ...
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Racket
Racket
  #lang racket   (require net/private/ip)   (define (bytes->hex bs) (string-append* (map (λ(n) (~r n #:base 16 #:min-width 2 #:pad-string "0")) (bytes->list bs))))   (define (parse-ip str) (define-values [ipstr portstr] (match str [(regexp #rx"^([0-9.]+):([0-9]+)$" (list _ i p)) (va...
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Wren
Wren
class BinaryTree { construct new(T, value) { if (!(T is Class)) Fiber.abort ("T must be a class.") if (value.type != T) Fiber.abort("Value must be of type T.") _kind = T _value = value _left = null _right = null }   // constructor overload to enable kind to be...
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....
#JavaScript
JavaScript
const Associativity = { /** a / b / c = (a / b) / c */ left: 0, /** a ^ b ^ c = a ^ (b ^ c) */ right: 1, /** a + b + c = (a + b) + c = a + (b + c) */ both: 2, }; const operators = { '+': { precedence: 2, associativity: Associativity.both }, '-': { precedence: 2, associativity: Associativ...
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 ...
#Lua
Lua
function map(f, ...) local t = {} for k, v in ipairs(...) do t[#t+1] = f(v) end return t end   function timestwo(n) return n * 2 end   function squared(n) return n ^ 2 end   function partial(f, arg) return function(...) return f(arg, ...) end end   timestwo_s = partial(ma...
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#Visual_Basic_.NET
Visual Basic .NET
' Partition an integer X into N primes - 29/03/2017 Option Explicit On   Module PartitionIntoPrimes Dim p(8), a(32), b(32), v, g, q As Long   Sub Main() Dim what, t1(), t2(), t3(), xx, nn As String Dim x, y, n, m As Long what = "99809 1 18 2 19 3 20 4 2017 24 22699 1-4 40355 3" ...
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Sidef
Sidef
# set up triangle var rows = 5 var tri = rows.of {|i| (i+1).of { Hash(x => 0, z => 0, v => 0, rhs => nil) } } tri[0][0]{:rhs} = 151 tri[2][0]{:rhs} = 40 tri[4][0]{:x} = 1 tri[4][1]{:v} = 11 tri[4][2]{:x} = 1 tri[4][2]{:z} = 1 tri[4][3]{:v} = 4 tri[4][4]{:z} = 1   # aggregate from bottom to top for row in (tri.len ^.. 1...
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...
#Phix
Phix
--with javascript_semantics -- not quite yet: without js -- (VALUECHANGED_CB not yet triggering) constant az = "abcdefghijklmnopqrstuvwxyz", AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", O9 = "1234567890", OT = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" function password(integer len, integer n, sequence exclud...
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...
#Java
Java
import javax.xml.bind.DatatypeConverter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;   /** * "Main Program" that does the parallel processing */ public class ParallelBrut...
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 ...
#JavaScript
JavaScript
  var onmessage = function(event) { postMessage({"n" : event.data.n, "factors" : factor(event.data.n), "id" : event.data.id}); };   function factor(n) { var factors = []; for(p = 2; p <= n; p++) { if((n % p) == 0) { factors[factors.length] = p; ...
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 ...
#Julia
Julia
  using Primes   factortodict(d, n) = (d[minimum(collect(keys(factor(n))))] = n)   # Numbers are from from the Raku example. numbers = [64921987050997300559, 70251412046988563035, 71774104902986066597, 83448083465633593921, 84209429893632345702, 87001033462961102237, 87762379890959854011, 895...
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...
#EchoLisp
EchoLisp
  ;; RPN (postfix) evaluator   (lib 'hash)   (define OPS (make-hash)) (hash-set OPS "^" expt) (hash-set OPS "*" *) (hash-set OPS "/" //) ;; float divide (hash-set OPS "+" +) (hash-set OPS "-" -)   (define (op? op) (hash-ref OPS op))   ;; algorithm : https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorit...
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 ...
#8086_Assembly
8086 Assembly
cpu 8086 org 100h section .text jmp demo ;;; Check if the $-terminated string in [DS:SI] is a palindrome. ;;; Returns with zero flag set if so. ;;; Destroyed: AL, CX, SI, DI, ES. palin: push es ; Set ES=DS. pop ds mov al,'$' ; Find end of string mov cx,-1 mov di,si repne scasb dec di ; Move back to last...
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...
#FreeBASIC
FreeBASIC
function is_gapful( n as uinteger ) as boolean if n<100 then return false dim as string ns = str(n) dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1)) if n mod gap = 0 then return true else return false end function   function is_palindrome( n as uinteger ) as boolean dim as string n...
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...
#JavaScript
JavaScript
function Stack() { this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.length = length; }   function push(element) { this.dataStore[this.top++] = element; }   function pop() { return this.dataStore[--this.top]; }   function peek() { return this.dataStore[this.to...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
s[m_, p_, n_] := CycleIndexPolynomial[SymmetricGroup[m], Table[ComposeSeries[p, x^i + O[x]^(n + 1)], {i, m}]]; G000598[n_] := Nest[1 + x s[3, #, n] &, 1 + O[x], n]; G000602[n_] := x s[4, #, n] - s[2, # - 1, n] + ComposeSeries[#, x^2 + O[x]^(n + 1)] &[G000598[n]]; A000602[n_] := SeriesCoefficient[G000602...
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...
#Nim
Nim
import bigints   const nMax: int32 = 250 nBranches = 4   var rooted, unrooted: array[nMax + 1, BigInt] rooted[0..1] = [1.initBigInt, 1.initBigInt] unrooted[0..1] = [1.initBigInt, 1.initBigInt] for i in 2 .. nMax: rooted[i] = 0.initBigInt unrooted[i] = 0.initBigInt   proc choose(m: BigInt; k: int32): BigInt = ...
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...
#BASIC256
BASIC256
function isPangram$(texto$) longitud = Length(texto$) if longitud < 26 then return "is not a pangram" t$ = lower(texto$) print "'"; texto$; "' "; for i = 97 to 122 if instr(t$, chr(i)) = 0 then return "is not a pangram" next i return "is a pangram" end function   print isPangram$("Th...
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...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   %===The Main Thing===% call :pangram "The quick brown fox jumps over the lazy dog." call :pangram "The quick brown fox jumped over the lazy dog." echo. pause exit /b 0   %===The Function===% :pangram set letters=abcdefgihjklmnopqrstuvwxyz set cnt=0 set inp=%~1 set str=!inp:...
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...
#FreeBASIC
FreeBASIC
  sub print_matrix( M() as integer ) 'displays a matrix for row as integer = 0 to ubound(M, 1) for col as integer = 0 to ubound(M, 2) print using "#### ";M(row, col); next col print next row return end sub   function fact( n as uinteger ) as uinteger 'quick and ...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Python
Python
import sqlite3   db = sqlite3.connect(':memory:')   # setup db.execute('create temp table players (name, score, active, jerseyNum)') db.execute('insert into players values ("name",0,"false",99)') db.execute('insert into players values ("name",0,"false",100)')   # demonstrate parameterized SQL   # example 1 -- simple pl...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Racket
Racket
  #lang racket/base (require sql db)   (define pgc  ; Don't actually inline sensitive data ;) (postgresql-connect #:user "resu" #:database "esabatad" #:server "example.com" #:port 5432 #:password "s3>r37P455"))   (defin...
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...
#Clojure
Clojure
(defn pascal [n] (let [newrow (fn newrow [lst ret] (if lst (recur (rest lst) (conj ret (+ (first lst) (or (second lst) 0)))) ret)) genrow (fn genrow [n lst] (when (< 0 n) (do ...
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Raku
Raku
grammar IP_Addr { token TOP { ^ [ <IPv4> | <IPv6> ] $ }   token IPv4 { [ <d8> +% '.' ] <?{ $<d8> == 4 }> <port>? { @*by8 = @$<d8> } }   token IPv6 { | <ipv6> | '[' <ipv6> ']' <port> }   token ipv6 { | <h16> +% ':' <?{ $<h16> == 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....
#Julia
Julia
  function parseRPNstring(rpns) infix = [] rpn = split(rpns) for tok in rpn if all(isnumber, tok) push!(infix, parse(Int, tok)) else last = pop!(infix) prev = pop!(infix) push!(infix, Expr(:call, Symbol(tok), prev, last)) println("C...
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....
#Kotlin
Kotlin
// version 1.2.0   import java.util.Stack   class Expression(var ex: String, val op: String = "", val prec: Int = 3) {   constructor(e1: String, e2: String, o: String) : this("$e1 $o $e2", o, OPS.indexOf(o) / 2)   override fun toString() = ex   companion object { const val OPS = "-+/*^" ...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
fs[f_, s_] := Map[f, s] f1 [n_] := n*2 f2 [n_] := n^2 fsf1[s_] := fs[f1, s] fsf2[s_] := fs[f2, s]
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 ...
#Mercury
Mercury
:- module partial_function_application. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list.   main(!IO) :- io.write((fsf1)([0, 1, 2, 3]), !IO), io.nl(!IO), io.write((fsf2)([0, 1, 2, 3]), !IO), io.nl(!IO), io.write((fsf1)([2, 4, 6, 8]),...
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#Wren
Wren
import "/math" for Int, Nums import "/fmt" for Fmt   var primes = Int.primeSieve(1e5) var foundCombo = false   var findCombo // recursive findCombo = Fn.new { |k, x, m, n, combo| if (k >= m) { if (Nums.sum(combo.map { |i| primes[i] }.toList) == x) { var s = (m > 1) ? "s" : "" Fmt.wri...
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#SystemVerilog
SystemVerilog
program main;   class Triangle; rand bit [7:0] a,b,c,d,e,f,g,h,X,Y,Z;   function new(); randomize; $display(" [%0d]", 151); $display(" [%0d][%0d]", a, b); $display(" [%0d][%0d][%0d]", 40,c,d); $display(" [%0d][%0d][%0d][%0d]", e,f,g,h...
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...
#PicoLisp
PicoLisp
#!/usr/bin/pil   # Default seed (seed (in "/dev/urandom" (rd 8)))   # Global defaults (setq *PwCount 1 *PwLength 12 *UppChars (mapcar char (range (char "A") (char "Z"))) *LowChars (mapcar lowc *UppChars) *Digits (mapcar format (range 0 9)) *Others (chop "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~") )   # Command...
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...
#Julia
Julia
@everywhere using SHA   @everywhere function bruteForceRange(startSerial, numberToDo) targets = ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c...
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...
#Kotlin
Kotlin
// version 1.1.51   import java.security.MessageDigest   fun stringHashToByteHash(hash: String): ByteArray { val ba = ByteArray(32) for (i in 0 until 64 step 2) ba[i / 2] = hash.substring(i, i + 2).toInt(16).toByte() return ba }   fun ByteArray.matches(other: ByteArray): Boolean { for (i in 0 until 32) ...
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 ...
#Kotlin
Kotlin
// version 1.1.51   import java.util.stream.Collectors   /* returns the number itself, its smallest prime factor and all its prime factors */ fun primeFactorInfo(n: Int): Triple<Int, Int, List<Int>> { if (n <= 1) throw IllegalArgumentException("Number must be more than one") if (isPrime(n)) return Triple(n, n, ...
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...
#Ela
Ela
open string generic monad io   type OpType = Push | Operate deriving Show   type Op = Op (OpType typ) input stack deriving Show   parse str = split " " str   eval stack [] = [] eval stack (x::xs) = op :: eval nst xs where (op, nst) = conv x stack conv "+"@x = operate x (+) conv "-"@x = opera...
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...
#Erlang
Erlang
-module(rpn). -export([eval/1]).   parse(Expression) -> parse(string:tokens(Expression," "),[]).   parse([],Expression) -> lists:reverse(Expression); parse(["+"|Xs],Expression) -> parse(Xs,[fun erlang:'+'/2|Expression]); parse(["-"|Xs],Expression) -> parse(Xs,[fun erlang:'-'/2|Expression]); parse(["*"|X...
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 ...
#ACL2
ACL2
(defun reverse-split-at-r (xs i ys) (if (zp i) (mv xs ys) (reverse-split-at-r (rest xs) (1- i) (cons (first xs) ys))))   (defun reverse-split-at (xs i) (reverse-split-at-r xs i nil))   (defun is-palindrome (str) (let* ((lngth (length str)) (idx (floor lngth 2))) ...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e }   func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
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...
#Julia
Julia
  function parseinfix2rpn(s) outputq = [] opstack = [] infix = split(s) for tok in infix if all(isnumber, tok) push!(outputq, tok) elseif tok == "(" push!(opstack, tok) elseif tok == ")" while !isempty(opstack) && (op = pop!(opstack)) != "(" ...
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...
#PARI.2FGP
PARI/GP
paraffin(p) = { local (P = p+1, R, U = R = Vec([1,1], P));   for (n = 1, p, ((B,n,C,S,l=n) -> my(b,c,i,s); for (b = 1, 4-B, if ((s = S + b * n) < P, c = R[n+1] * C * prod(i = 1, b-1, (R[n+1]+i)/(i+1)); if (l+l < s, U[s+1] += c); if (B+b < 4, R[s+1] += c; i = n; while ...
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...
#BBC_BASIC
BBC BASIC
FOR test% = 1 TO 2 READ test$ PRINT """" test$ """ " ; IF FNpangram(test$) THEN PRINT "is a pangram" ELSE PRINT "is not a pangram" ENDIF NEXT test% END   DATA "The quick brown fox jumped over the lazy dog" DATA "The five boxing wi...
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...
#BCPL
BCPL
get "libhdr"   // Test if s is a pangram. The ASCII character set is assumed. let pangram(s) = valof $( let letters = vec 25 for i=0 to 25 do letters!i := false for i=1 to s%0 do $( let c = (s%i | 32) - 'a' if c >= 0 & c < 26 then letters!c := true $) for i=0 to 25 unless lette...
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...
#Go
Go
package main   import ( "fmt" "strings" )   func binomial(n, k int) int { if n < k { return 0 } if n == 0 || k == 0 { return 1 } num := 1 for i := k + 1; i <= n; i++ { num *= i } den := 1 for i := 2; i <= n-k; i++ { den *= i } return nu...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Raku
Raku
use DBIish;   my $db = DBIish.connect('DBI:mysql:mydatabase:host','login','password');   my $update = $db.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");   my $rows-affected = $update.execute("Smith, Steve",42,'true',99);
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Ruby
Ruby
require 'sqlite3'   db = SQLite3::Database.new(":memory:")   # setup db.execute('create temp table players (name, score, active, jerseyNum)') db.execute('insert into players values ("name",0,"false",99)') db.execute('insert into players values ("name",0,"false",100)') db.execute('insert into players values ("name",0,"f...
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...
#CoffeeScript
CoffeeScript
  pascal = (n) -> width = 6 for r in [1..n] s = ws (width/2) * (n-r) # center row output = (n) -> s += pad width, n cell = 1 output cell # Compute binomial coefficients as you go # across the row. for c in [1...r] cell *= (r-c) / c output cell console.log s   ws = (n) -> ...
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#REXX
REXX
/*REXX program parses an IP address into ──► IPv4 or IPv6 format, optional pport.*/ _= "_"; say center('input IP address' , 30), center('hex IP address' , 32), center('decimal IP address' , 39) "space port" say copies(_, 30) copies(_, 32) copies(_, 3...
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....
#Lua
Lua
function tokenize(rpn) local out = {} local cnt = 0 for word in rpn:gmatch("%S+") do table.insert(out, word) cnt = cnt + 1 end return {tokens = out, pos = 1, size = cnt} end   function advance(lex) if lex.pos <= lex.size then lex.pos = lex.pos + 1 return true ...
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 ...
#min
min
'map :fs (dup +) :f1 (dup *) :f2 ('f1 fs) :fsf1 ('f2 fs) :fsf2   (0 1 2 3) fsf1 puts! (0 1 2 3) fsf2 puts! (2 4 6 8) fsf1 puts! (2 4 6 8) fsf2 puts!
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 ...
#Nemerle
Nemerle
using System; using System.Console;   module Partial { fs[T] (f : T -> T, s : list[T]) : list[T] { $[f(x)| x in s] }   f1 (x : int) : int { x * 2 }   f2 (x : int) : int { x * x }   curry[T, U, V] (f : T * U -> V, x : T) : U -> V { f(x, _) }...
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#zkl
zkl
// Partition integer N into M unique primes fcn partition(N,M,idx=0,ps=List()){ var [const] sieve=Utils.Generator(Import("sieve").postponed_sieve); var [const] primes=List(); while(sieve.peek()<=N){ primes.append(sieve.next()) } if(M<2){ z:=primes.find(N); return(if(Void!=z and z>=idx) ps.app...
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Tcl
Tcl
package require Tcl 8.5 namespace path ::tcl::mathop   set pyramid { {151.0 "" "" "" ""} {"" "" "" "" ""} {40.0 "" "" "" ""} {"" "" "" "" ""} {x 11.0 y 4.0 z} }   set equations {{1 -1 1 0}}   proc simplify {terms val} { set vars {0 0 0} set x 0 set y 1 set z 2 foreach term $terms...
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...
#PowerShell
PowerShell
  function New-RandomPassword { <# .SYNOPSIS Generates one or more passwords. .DESCRIPTION Generates one or more passwords. .PARAMETER Length The password length (default = 8). .PARAMETER Count The number of passwords to generate. .PARAMETER Source An array ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
testPassword[pass_String] := If[MemberQ[{16^^1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad, 16^^3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b, 16^^74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f}, Hash[pass, "SHA256"]], Print[pass]];   chars=CharacterR...
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...
#Modula-2
Modula-2
MODULE PBF; FROM FormatString IMPORT FormatString; FROM SHA256 IMPORT SHA256,Create,Destroy,HashBytes,Finalize,GetHash; FROM SYSTEM IMPORT ADR,ADDRESS,BYTE; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar; FROM Threads IMPORT Thread,CreateThread,WaitForThreadTermination;   PROCEDURE PrintHexBytes(str : ARRAY OF...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
hasSmallestFactor[data_List]:=Sort[Transpose[{ParallelTable[FactorInteger[x][[1, 1]], {x, data}],data}]][[1, 2]]
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 ...
#Nim
Nim
import strformat, strutils, threadpool   const Numbers = [576460752303423487, 576460752303423487, 576460752303423487, 112272537195293, 115284584522153, 115280098190773, 115797840077099, 112582718962171...
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...
#F.23
F#
let reduce op = function | b::a::r -> (op a b)::r | _ -> failwith "invalid expression"   let interprete s = function | "+" -> "add", reduce ( + ) s | "-" -> "subtr", reduce ( - ) s | "*" -> "mult", reduce ( * ) s | "/" -> "divide", reduce ( / ) s | "^" -> "exp", reduce ( ** ) s | str -> "push",...
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 ...
#Action.21
Action!
BYTE FUNC Palindrome(CHAR ARRAY s) BYTE l,r   l=1 r=s(0) WHILE l<r DO IF s(l)#s(r) THEN RETURN (0) FI l==+1 r==-1 OD RETURN (1)   BYTE FUNC IsIgnored(BYTE c) IF (c>=' AND c<='/) OR (c>=': AND c<='@) OR (c>='[ AND c<='_) THEN RETURN (1) FI RETURN (0)   BYTE FUNC ToUpper(BYTE c) I...
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...
#Go
Go
package main   import "fmt"   func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e }   func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
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...
#Kotlin
Kotlin
// version 1.2.0   import java.util.Stack   /* To find out the precedence, we take the index of the token in the OPS string and divide by 2 (rounding down). This will give us: 0, 0, 1, 1, 2 */ const val OPS = "-+/*^"   fun infixToPostfix(infix: String): String { val sb = StringBuilder() val s = Stack<Int>...
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...
#Pascal
Pascal
Program Paraffins;   uses gmp;   const max_n = 500; branch = 4;   var rooted, unrooted: array [0 .. max_n-1] of mpz_t; c: array [0 .. branch-1] of mpz_t; cnt, tmp: mpz_t; n: integer; fmt: pchar; sum: integer;   procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t); var b, m: integer; beg...
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...
#Befunge
Befunge
>~>:65*`!#v_:"`"`48*v>g+04p1\4p ^#*`\*93\`0<::-"@"-*<^40!%2g4:_ "pangram."<v*84<_v#-":"g40\" a" >>:#,_55+,@>"ton">48*>"si tahT"
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...
#Bracmat
Bracmat
(isPangram= k . low$!arg:?arg & a:?k & whl ' ( @(!arg:? !k ?) & chr$(1+asc$!k):?k:~>z ) & !k:>z & );
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...
#Haskell
Haskell
import Data.List (transpose) import System.Environment (getArgs) import Text.Printf (printf)   -- Pascal's triangle. pascal :: [[Int]] pascal = iterate (\row -> 1 : zipWith (+) row (tail row) ++ [1]) [1]   -- The n by n Pascal lower triangular matrix. pascLow :: Int -> [[Int]] pascLow n = zipWith (\row i -> row ++ repl...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" #mem execute("CREATE table players (name, score, active, jerseyNum)") #mem execute("INSERT INTO players VALUES ('Jones, Bob',0,'N',99)") #mem execute("INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)") #mem execute("INSERT INTO players VALUES ('Jello, Frank',0,'N',101)") sql$ = " UPDA...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Scala
Scala
import slick.jdbc.H2Profile.api._ import slick.sql.SqlProfile.ColumnOption.SqlType   import scala.concurrent.Await import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration   object PlayersApp extends App { lazy val playerRecords = TableQuery[PlayerRecords] val db = Databas...
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...
#Commodore_BASIC
Commodore BASIC
10 INPUT "HOW MANY";N 20 IF N<1 THEN END 30 DIM C(N) 40 DIM D(N) 50 LET C(1)=1 60 LET D(1)=1 70 FOR J=1 TO N 80 FOR I=1 TO N-J+1 90 PRINT " "; 100 NEXT I 110 FOR I=1 TO J 120 PRINT C(I)" "; 130 NEXT I 140 PRINT 150 IF J=N THEN END 160 C(J+1)=1 170 D(J+1)=1 180 FOR I=1 TO J-1 190 D(I+1)=C(I)+C(I+1) 200 NEXT I 210 FOR I...
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Ruby
Ruby
require 'ipaddr'     TESTCASES = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"]   output = [%w(String Address Port Family Hex), %w(------ ------- ---- ...
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....
#M2000_Interpreter
M2000 Interpreter
  Module Rpn_2_Infix { Rem Form 80,60 function rpn_to_infix$(a$) { def m=0 inventory precendence="-":=2,"+":=2,"*":=3,"/":=3,"^":=4 dim token$() token$()=piece$(a$," ") l=len(token$()) dim type(l)=0, right(l)=0, infix$(l) infix=-1 for i=0 to l-1 if exist(precendence, token$(i)) then type(i)=...
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....
#Nim
Nim
import tables, strutils   const nPrec = 9   let ops: Table[string, tuple[prec: int, rAssoc: bool]] = { "^": (4, true) , "*": (3, false) , "/": (3, false) , "+": (2, false) , "-": (2, false) }.toTable   proc parseRPN(e: string) = echo "postfix: ", e var stack = newSeq[tuple[prec: int, expr: string]]()   ...
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 ...
#Nim
Nim
import sequtils   type   Func = proc(n: int): int FuncS = proc(f: Func; s: seq[int]): seq[int]   proc fs(f: Func; s: seq[int]): seq[int] = s.map(f)   proc partial(fs: FuncS; f: Func): auto = result = proc(s: seq[int]): seq[int] = fs(f, s)   proc f1(n: int): int = 2 * n proc f2(n: int): int = n * n   when isMainMo...
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 ...
#OCaml
OCaml
# let fs f s = List.map f s let f1 value = value * 2 let f2 value = value * value   let fsf1 = fs f1 let fsf2 = fs f2 ;; val fs : ('a -> 'b) -> 'a list -> 'b list = <fun> val f1 : int -> int = <fun> val f2 : int -> int = <fun> val fsf1 : int list -> int list = <fun> val fsf2 : int list -> int list = <fun>   # fsf1 [0;...
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Wren
Wren
import "/fmt" for Fmt   var isIntegral = Fn.new { |x, tol| x.fraction.abs <= tol }   var pascal = Fn.new { |a, b, mid, top| var yd = (top - 4 * (a + b)) / 7 if (!isIntegral.call(yd, 0.0001)) return [0, 0, 0] var y = yd.truncate var x = mid - 2*a - y return [x, y, y - x] }   var sol = pascal.call(11,...
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...
#Prolog
Prolog
:- set_prolog_flag(double_quotes, chars). :- initialization(main, main).   main( Argv ) :- opt_spec( Spec ), opt_parse( Spec, Argv, Opts, _ ), ( member( help(true), Opts ) -> show_help ; member( length( Len ), Opts ), member( number( Num ), Opts ), print_set_of_p...
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...
#Nim
Nim
import strutils, threadpool import nimcrypto   const   # List of hexadecimal representation of target hashes. HexHashes = ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b6...
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...
#Perl
Perl
use Digest::SHA qw/sha256_hex/; use threads; use threads::shared; my @results :shared;   print "$_ : ",join(" ",search($_)), "\n" for (qw/ 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7...
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 ...
#Oforth
Oforth
import: parallel   : largeMinFactor dup mapParallel(#factors) zip maxFor(#[ second first ]) ;
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 ...
#ooRexx
ooRexx
/* Concurrency in ooRexx. Example of early reply */ object1 = .example~new object2 = .example~new say object1~primes(1,11111111111,11111111114) say object2~primes(2,11111111111,11111111114) say "Main ended at" time() exit ::class example ::method primes use arg which,bot,top reply "Start primes"which':' time() Select ...
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...
#Factor
Factor
IN: scratchpad 3 4 2 * 1 5 - 2 3 ^ ^ / +   --- Data stack: 3+1/8192
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...
#Forth
Forth
: ^ over swap 1 ?do over * loop nip ; s" 3 4 2 * 1 5 - 2 3 ^ ^ / +" evaluate .
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 ...
#ActionScript
ActionScript
function isPalindrome(str:String):Boolean { for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--) if(str.charAt(first) != str.charAt(second)) return false; return true; }
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...
#Haskell
Haskell
import Control.Monad (guard)   palindromic :: Int -> Bool palindromic n = d == reverse d where d = show n   gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n   result :: Int -> [Int] result d = do x <- [(d+100),(d+110)..]...
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...
#Liberty_BASIC
Liberty BASIC
  global stack$,queue$ stack$="" queue$=""   in$ = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" print "Input:" print in$   token$ = "#" print "No", "token", "stack", "queue"   while 1 i=i+1 token$ = word$(in$, i) if token$ = "" then i=i-1: exit while print i, token$, reverse$(stack$), queue$   select case c...
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...
#Perl
Perl
use Math::GMPz;   my $nmax = 250; my $nbranches = 4;   my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1;   sub tree { my($br, $n, $l, $sum, $cnt) = @_; for my $b ($br+1 .. $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...
#Brat
Brat
pangram? = { sentence | letters = [:a :b :c :d :e :f :g :h :i :j :k :l :m  :n :o :p :q :r :s :t :u :v :w :x :y :z]   sentence.downcase!   letters.reject! { l | sentence.include? l }   letters.empty? }   p pangram? 'The quick brown fox jumps over the lazy dog.' #Prints true p pangram? 'Probably ...
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...
#C
C
#include <stdio.h>   int is_pangram(const char *s) { const char *alpha = "" "abcdefghjiklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   char ch, wasused[26] = {0}; int total = 0;   while ((ch = *s++) != '\0') { const char *p; int idx;   if ((p = strchr(alpha, ch)) == NULL) continue;   idx = (p - alp...
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...
#J
J
 !/~ i. 5 1 1 1 1 1 0 1 2 3 4 0 0 1 3 6 0 0 0 1 4 0 0 0 0 1  !~/~ i. 5 1 0 0 0 0 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 (["0/ ! +/)~ i. 5 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 70
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "sql_base.s7i";   const proc: main is func local var database: testDb is database.value; var sqlStatement: statement is sqlStatement.value; var string: name is "Smith, Steve"; begin testDb := openDatabase(DB_SQLITE, "test", "test", "test"); execute(testDb, "cr...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#SQL
SQL
-- This works in Oracle's SQL*Plus command line utility   VARIABLE P_NAME VARCHAR2(20); VARIABLE P_SCORE NUMBER; VARIABLE P_ACTIVE VARCHAR2(5); VARIABLE P_JERSEYNUM NUMBER;   BEGIN   :P_NAME := 'Smith, Steve'; :P_SCORE := 42; :P_ACTIVE := 'TRUE'; :P_JERSEYNUM := 99;   END; /   DROP TABLE players;   CREATE TABLE players...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#SQL_PL
SQL PL
  --#SET TERMINATOR @   CREATE TABLE PLAYERS ( NAME VARCHAR(32), SCORE INT, ACTIVE SMALLINT, JERSEYNUM INT ) @   CREATE PROCEDURE UPDATE_PLAYER ( IN PLAYER_NAME VARCHAR(32), IN PLAYER_SCORE INT, IN PLAYER_ACTIVE SMALLINT, IN JERSEY_NUMBER INT ) BEGIN UPDATE PLAYERS SET NAME = PLAYER_NAME, SCORE =...
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...
#Common_Lisp
Common Lisp
(defun pascal (n) (genrow n '(1)))   (defun genrow (n l) (when (< 0 n) (print l) (genrow (1- n) (cons 1 (newrow l)))))   (defun newrow (l) (if (> 2 (length l)) '(1) (cons (+ (car l) (cadr l)) (newrow (cdr l)))))