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/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Nim
Nim
import math, strformat import bignum   func solvePell(n: int): (Int, Int) = let x = newInt(sqrt(n.toFloat).int) var (y, z, r) = (x, newInt(1), x shl 1) var (e1, e2) = (newInt(1), newInt(0)) var (f1, f2) = (newInt(0), newInt(1))   while true: y = r * z - y z = (n - y * y) div z r = (x + y) div z   ...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Pascal
Pascal
  program Pell_console; uses SysUtils, uIntX; // uIntX is a unit in the library IntXLib4Pascal. // uIntX.TIntX is an arbitrarily large integer.   // For the given n: if there are non-trivial solutions of x^2 - n*y^2 = 1 // in non-negative integers (x,y), return the smallest. // Else return the trivia...
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#SPL
SPL
mx,my = #.scrsize() xc = mx/2 yc = my/2 mr = #.min(mx,my)/3 #.angle(#.degrees) #.drawcolor(1,0,0) #.drawsize(10) > r, mr..0,-1 #.drawline(xc,yc-r,xc,yc-r) > a, 54..630,144 #.drawline(r*#.cos(a)+xc,r*#.sin(a)+yc) < #.drawcolor(1,1,0) #.drawsize(1) <
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Tcl
Tcl
  package require Tk 8.6 ;# lmap is new in Tcl/Tk 8.6   set pi [expr 4*atan(1)]   pack [canvas .c] -expand yes -fill both ;# create the canvas   update ;# draw everything so the dimensions are accurate   set w [winfo width .c] ;# calculate appropriate dimensions set h [winfo height .c] set r [e...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#11l
11l
T.enum Piece EMPTY BLACK WHITE   F isAttacking(queen, pos) R queen.x == pos.x | queen.y == pos.y | abs(queen.x - pos.x) == abs(queen.y - pos.y)   F place(m, n, &pBlackQueens, &pWhiteQueens) I m == 0 R 1B   V placingBlack = 1B L(i) 0 .< n L(j) 0 .< n V pos = (i, j) ...
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...
#Applesoft_BASIC
Applesoft BASIC
1 N=1 2 L=8 3 M$=CHR$(13) 4 D$=CHR$(4) 5 S$(0)="S" 6 F$="A FILE" 7 C$(1)=" (CURRENT OPTION)" 8 DEF FN R(T)=ASC(MID$(G$(T),INT(RND(1)*LEN(G$(T))+1),1)) 9 GOSUB 750 10 FOR Q = 0 TO 1 STEP 0 20 GOSUB 50CHOOSE 30 NEXT Q 40 END   REM *** CHOOSE *** 50 PRINT M$M$"1 GEN 2 DISP 3 FILE 4 LEN 5 NUM 6 SEED" 60 PRINT "7 CHR 8 ...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Qi
Qi
  (define insert L 0 E -> [E|L] [L|Ls] N E -> [L|(insert Ls (- N 1) E)])   (define seq Start Start -> [Start] Start End -> [Start|(seq (+ Start 1) End)])   (define append-lists [] -> [] [A|B] -> (append A (append-lists B)))   (define permutate [] -> [[]] [H|T] -> (append-lists (map (/. P ...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#IS-BASIC
IS-BASIC
100 PROGRAM "PeanoC.bas" 110 OPTION ANGLE DEGREES 120 SET VIDEO MODE 5:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27 130 OPEN #101:"video:" 140 DISPLAY #101:AT 1 FROM 1 TO 27 150 PLOT 280,240,ANGLE 90; 160 CALL PEANO(28,90,6) 170 DEF PEANO(D,A,LEV) 180 IF LEV=0 THEN EXIT DEF 190 PLOT RIGHT A; 200 CALL PEANO(D,-...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#J
J
load'viewmat' hp=: 3 : '(|.,]) 1 (0 _2 _2 ,&.> _2 _1 0 + #y) } (,.|:) y' HP=: 3 3 $ 0 0 0 0 1 WR=: 16777215 16711680 viewrgb WR {~ hp ^:7 HP
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Java
Java
import java.io.*;   public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.curre...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#D
D
void main() { import std.stdio, std.random, std.algorithm, std.string, std.conv, std.range, core.thread;   immutable first = uniform(0, 2) == 0;   string you, me; if (first) { me = 3.iota.map!(_ => "HT"[uniform(0, $)]).text; writefln("I choose first and will win on first seein...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Excel
Excel
A1: 2 A2: -4 A3: =111-1130/A2+3000/(A2*A1) A4: =111-1130/A3+3000/(A3*A2) ...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Perl
Perl
sub solve_pell { my ($n) = @_;   use bigint try => 'GMP';   my $x = int(sqrt($n)); my $y = $x; my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   for (; ;) {   $y = $r * $z - $y; $z = int(($n - $y * $y) / $z); $r = int(($x + $y) / $...
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#VBA
VBA
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Wren
Wren
import "graphics" for Canvas, Color, Point import "dome" for Window   class Game { static init() { Window.title = "Pentagram" var width = 640 var height = 640 Window.resize(width, height) Canvas.resize(width, height) Canvas.cls(Color.white) var col = Color.hex...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#ATS
ATS
(********************************************************************)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_define.hats" #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   #define NIL list_vt_nil () #define :: list_vt_cons   #ifndef NDEBUG #then (* Safety is relatively un...
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...
#Arturo
Arturo
lowercase: `a`..`z` uppercase: `A`..`Z` digits: `0`..`9` other: map split "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" => [to :char]   any: lowercase ++ uppercase ++ digits ++ other   generate: function [length][ if length < 4 [ print (color #red "ERROR: ") ++ "password length too short" exit ]   chars...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Quackery
Quackery
[ stack ] is perms.min ( --> [ )   [ stack ] is perms.max ( --> [ )   forward is (perms)   [ over size perms.min share > if [ over temp take swap nested join temp put ] over size perms.max share < i...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#jq
jq
  # => = 0 degrees # ^ = 90 degrees # <= = 180 degrees # v = 270 degrees   # $start : [$x, $y] def turtle($start): $start | if type == "array" then "M \($start|join(","))" else "M 0,0" end | {svg: ., up:true, angle:0};   def turtleUp: .up=true; def turtleDown: .up=false;   def turtleRotate($angle): .angle...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Julia
Julia
using Gtk, Graphics, Colors   function peano(ctx, x, y, lg, i1, i2) if lg < 3 line_to(ctx, x - 250, y - 250) stroke(ctx) move_to(ctx, x - 250 , y - 250) else lg = div(lg, 3) peano(ctx, x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) peano(ctx, x + ((i1 - i2 + 1...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Elixir
Elixir
defmodule Penney do @toss [:Heads, :Tails]   def game(score \\ {0,0}) def game({iwin, ywin}=score) do IO.puts "Penney game score I : #{iwin}, You : #{ywin}" [i, you] = @toss coin = Enum.random(@toss) IO.puts "#{i} I start, #{you} you start ..... #{coin}" {myC, yC} = setup(coin) seq = for ...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Factor
Factor
USING: formatting fry io kernel locals math math.functions math.ranges sequences ; IN: rosetta-code.pathological   : next2 ( x y -- y z ) swap dupd dupd '[ 111 1130 _ / - 3000 _ _ * / + ] call ;   : pathological-sequence ( -- seq ) 2 -4 100 [ next2 dup ] replicate 2nip { 0 2 -4 } prepend ;   : show-sequence ( -...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Phix
Phix
with javascript_semantics include mpfr.e procedure fun(mpz a,b,t, integer c) -- {a,b} = {b,c*b+a} (and t gets trashed) mpz_set(t,a) mpz_set(a,b) mpz_mul_si(b,b,c) mpz_add(b,b,t) end procedure function SolvePell(integer n) integer x = floor(sqrt(n)), y = x, z = 1, r = x*2 mpz e1 = mpz_init(1), e2 =...
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...
#11l
11l
F e(&x, row, col) -> & R x[row * (row + 1) I/ 2 + col]   F iterate(&v, &diff, do_print = 1B) V tot = 0.0 L e(&v, 0, 0) = 151 e(&v, 2, 0) = 40 e(&v, 4, 1) = 11 e(&v, 4, 3) = 4   L(i) 1..4 L(j) 0..i e(&diff, i, j) = 0 I j < i e(&diff, ...
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#XPL0
XPL0
proc FillArea(X, Y, C0, C); \Replace area colored C0 with color C int X, Y, \starting coordinate for flood fill algorithm C0, C; \initial color, and color to replace it with def S=8000; \size of queue (must be an even number) int Q(S), \queue (FIFO) F, E; \fill and empty indexes  ...
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#zkl
zkl
const DIM=200, SIDES=5, A=360/SIDES, R=DIM.toFloat(); vs:=[0.0..360-A,A].apply("toRad"); // angles of vertices #<<< 0'|<?xml version="1.0" standalone="no" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd"> <svg height="%d" width="%d" style="" xmlns="http://www....
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>   enum Piece { Empty, Black, White, };   typedef struct Position_t { int x, y; } Position;   ///////////////////////////////////////////////   struct Node_t { Position pos; struct Node_t *next; };   void releaseNode(st...
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...
#AWK
AWK
  # syntax: GAWK -f PASSWORD_GENERATOR.AWK [-v mask=x] [-v xt=x] # # examples: # REM 4 character passwords using Rosetta Code default of: lower, upper, number, other # GAWK -f PASSWORD_GENERATOR.AWK # # REM 8 character passwords; Rosetta Code default plus another four # GAWK -f PASSWORD_GENERATOR.AWK -v mask=LU...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#R
R
next.perm <- function(a) { n <- length(a) i <- n while (i > 1 && a[i - 1] >= a[i]) i <- i - 1 if (i == 1) { NULL } else { j <- i k <- n while (j < k) { s <- a[j] a[j] <- a[k] a[k] <- s j <- j + 1 k <- k - 1 } s <- a[i - 1] j <- i while (a[j] <= s) ...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Lua
Lua
local PeanoLSystem = { axiom = "L", rules = { L = "LFRFL-F-RFLFR+F+LFRFL", R = "RFLFR+F+LFRFL-F-RFLFR" }, eval = function(self, n) local source, result = self.axiom for i = 1, n do result = "" for j = 1, #source do local ch = source:sub(j,j) result = result .. (self.r...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Factor
Factor
USING: arrays ascii io kernel math prettyprint random sequences strings ; IN: rosetta-code.penneys-game   ! Generate a random boolean. : t|f ( -- t/f ) 1 random-bits 0 = ;   ! Checks whether the sequence chosen by the human is valid. : valid-input? ( seq -- ? ) [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter lengt...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Fortran
Fortran
SUBROUTINE MULLER REAL*4 VN,VNL1,VNL2 !The exact precision and dynamic range REAL*8 WN,WNL1,WNL2 !Depends on the format's precise usage of bits. INTEGER I !A stepper. WRITE (6,1) !A heading. 1 FORMAT ("Muller's sequence should converge to six...",/ 1 " N Single ...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Prolog
Prolog
  % Find the square root as a continued fraction   cf_sqrt(N, Sz, [A0, Frac]) :- A0 is floor(sqrt(N)), (A0*A0 =:= N -> Sz = 0, Frac = [] ; cf_sqrt(N, A0, A0, 0, 1, 0, [], Sz, Frac)).   cf_sqrt(N, A, A0, M0, D0, Sz0, L, Sz, R) :- M1 is D0*A0 - M0, D1 is (N - M1*M1) div D0, A1 is (...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Pyramid_of_Numbers is   B_X, B_Y, B_Z : Integer := 0; -- Unknown variables   type Block_Value is record Known  : Integer := 0; X, Y, Z : Integer := 0; end record; X : constant Block_Value := (0, 1, 0, 0); Y : constant Block_Value := (0, 0, 1, 0)...
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#C.2B.2B
C++
#include <SDL2/SDL.h>   #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <memory> #include <random> #include <tuple> #include <vector>   auto now() { using namespace std::chrono; auto time = system_clock::now(); return duration_cast<milliseconds>(time.time_since_epoch())....
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#C.23
C#
using System; using System.Collections.Generic;   namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>;   enum Piece { Empty, Black, White }   class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.It...
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...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <time.h>   #define DEFAULT_LENGTH 4 #define DEFAULT_COUNT 1   char* symbols[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"}; int length = DEFAULT_LENGTH; int count = DEFAULT_COUNT; unsigned seed; char exS...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Racket
Racket
  #lang racket   ;; using a builtin (permutations '(A B C)) ;; -> '((A B C) (B A C) (A C B) (C A B) (B C A) (C B A))   ;; a random simple version (which is actually pretty good for a simple version) (define (perms l) (let loop ([l l] [tail '()]) (if (null? l) (list tail) (append-map (λ(x) (loop (remq x l)...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#M2000_Interpreter
M2000 Interpreter
  Module Peano_curve { Cls 1, 0 Const Center=2 Report Center, "Peano curve" let factor=.9, k=3, wi=k^4 let wi2=min.data(scale.x*factor, scale.y*factor), n=wi2/wi let (dx, dy)=((scale.x-wi2)/2, (scale.y-wi2)/2) dx+=k*1.2*twipsX dy+=k*1.2*twipsY move dx, dy pen 11 { Peano(0,0,wi,0, 0) }   sub Peano(x, y, lg, i1, i2...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Graphics[PeanoCurve[4]]
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#FreeBASIC
FreeBASIC
  Sub Jugador_elige(secuencia As String) Dim As String eleccion Dim As Byte valido, i Do valido = True Print !"\nIngresa una secuencia de 3 opciones, cada una de ellas H o T:"; Input " > ", secuencia If Len(secuencia) <> 3 Then valido = False If valido Then ...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' As FB's native types have only 64 bit precision at most we need to use the ' C library, GMP v6.1.0, for arbitrary precision arithmetic   #Include Once "gmp.bi" mpf_set_default_prec(640) '' 640 bit precision, enough for this exercise   Function v(n As UInteger, prev As __mpf_struct, prev2 As __mpf_...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Python
Python
import math   def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z   e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r   a, b = f2 * x + e2, f2 ...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#11l
11l
F partitions(n) V p = [BigInt(1)] [+] [BigInt(0)] * n L(i) 1 .. n V k = 0 L k++ V j = (k * (3 * k - 1)) I/ 2 I j > i L.break I k [&] 1 p[i] += p[i - j] E p[i] -= p[i - j] j = (k * (3 * k + 1)) I/ 2 I j >...
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...
#ALGOL_68
ALGOL 68
MODE FIELD = REAL, VEC = [0]REAL, MAT = [0,0]REAL; MODE BRICK = UNION(INT, CHAR);   FLEX[][]BRICK puzzle = ( ( 151), ( " ", " "), ( 40, " ", " "), ( " ", " ", " ", " "), ( "x", 11, "y", 4, "z") );   PROC mat col = (INT row, col)INT: row*(row-1)OVER 2 + col; INT col x = mat co...
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#Julia
Julia
using Dates, Colors, SimpleDirectMediaLayer.LibSDL2   mutable struct ParticleFountain particlenum::Int positions::Vector{Float64} velocities::Vector{Float64} lifetimes::Vector{Float64} points::Vector{SDL_Point} numpoints::Int saturation::Float64 spread::Float64 range::Float64 rec...
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Particle_fountain use warnings; use Tk;   my $size = 900; my @particles; my $maxparticles = 500; my @colors = qw( red green blue yellow cyan magenta orange white );   my $mw = MainWindow->new; my $c = $mw->Canvas( -width => $size, -height => $size, -bg => 'bl...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#C.2B.2B
C++
#include <iostream> #include <vector>   enum class Piece { empty, black, white };   typedef std::pair<int, int> position;   bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(...
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...
#C.23
C#
using System; using System.Linq;   class Program { const string Lower = "abcdefghijklmnopqrstuvwxyz"; const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string Digits = "0123456789"; const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; static readonly string[] Full = {Lower, Upper, Digits...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Raku
Raku
.say for <a b c>.permutations
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Nim
Nim
import imageman   const Width = 81   proc peano(points: var seq[Point]; x, y, lg, i1, i2: int) =   if lg == 1: points.add ((Width - x) * 10, (Width - y) * 10) return   let lg = lg div 3 points.peano(x + 2 * i1 * lg, y + 2 * i1 * lg, lg, i1, i2) points.peano(x + (i1 - i2 + 1) * lg, y + (i1 + i2) * lg, lg...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Perl
Perl
use SVG; use List::Util qw(max min);   use constant pi => 2 * atan2(1, 0);   # Compute the curve with a Lindemayer-system my %rules = ( L => 'LFRFL-F-RFLFR+F+LFRFL', R => 'RFLFR+F+LFRFL-F-RFLFR' ); my $peano = 'L'; $peano =~ s/([LR])/$rules{$1}/eg for 1..4;   # Draw the curve in SVG ($x, $y) = (0, 0); $theta ...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Go
Go
  package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==A...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { sequence() bank() rump() }   func sequence() { // exact computations using big.Rat var v, v1 big.Rat v1.SetInt64(2) v.SetInt64(-4) n := 2 c111 := big.NewRat(111, 1) c1130 := big.NewRat(1130, 1) c3000 := big.Ne...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Raku
Raku
use Lingua::EN::Numbers;   sub pell (Int $n) {   my $y = my $x = Int(sqrt $n); my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   loop { $y = $r * $z - $y; $z = Int(($n - $y²) / $z); $r = Int(($x + $y) / $z);   ($e1, $e2) = ($e2, $r * $...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#C
C
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h>   mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1,...
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...
#AutoHotkey
AutoHotkey
N1 := 11, N2 := 4, N3 := 40, N4 := 151 Z := (2*N4 - 7*N3 - 8*N2 + 6*N1) / 7 X := (N3 - 2*N1 - Z) / 2 MsgBox,, Pascal's Triangle, %X%`n%Z%
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#Phix
Phix
-- -- demo\rosetta\Particle_fountain.exw -- ================================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas constant title = "Particle fountain" constant help_text = """ Uparrow increases the saturation of the particle colors, downarrow decreases saturat...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#D
D
import std.array; import std.math; import std.stdio; import std.typecons;   enum Piece { empty, black, white, }   alias position = Tuple!(int, "i", int, "j");   bool place(int m, int n, ref position[] pBlackQueens, ref position[] pWhiteQueens) { if (m == 0) { return true; } bool placingB...
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...
#C.2B.2B
C++
#include <iostream> #include <string> #include <algorithm> #include <ctime>   const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" }; const std::string UNS = "O0l1I5S2Z";   std::string createPW( int len, bool...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#RATFOR
RATFOR
# Heap’s algorithm for generating permutations. Algorithm 2 in # Robert Sedgewick, 1977. Permutation generation methods. ACM # Comput. Surv. 9, 2 (June 1977), 137-164.   define(n, 3) define(n_minus_1, 2)   implicit none   integer a(1:n)   integer c(1:n) integer i, k integer tmp   10000 format ('(', I1, n_minus_1(' ', I...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Phix
Phix
-- -- demo\rosetta\peano_curve.exw -- ============================ -- -- Draws a peano curve. Space key toggles between switchback and meander curves. -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas bool meander = false -- space toggles (false==draw switchback curve) c...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Haskell
Haskell
import qualified Data.List as L import System.IO import System.Random   data CoinToss = H | T deriving (Read, Show, Eq)   parseToss :: String -> [CoinToss] parseToss [] = [] parseToss (s:sx) | s == 'h' || s == 'H' = H : parseToss sx | s == 't' || s == 'T' = T : parseToss sx | otherwise = parseToss sx   notToss ::...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { sequence() bank() rump() }   func sequence() { // exact computations using big.Rat var v, v1 big.Rat v1.SetInt64(2) v.SetInt64(-4) n := 2 c111 := big.NewRat(111, 1) c1130 := big.NewRat(1130, 1) c3000 := big.Ne...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#REXX
REXX
/*REXX program to solve Pell's equation for the smallest solution of positive integers. */ numeric digits 2200 /*ensure enough decimal digs for answer*/ parse arg $ /*obtain optional arguments from the CL*/ if $=='' | $=="," then $= 61 109 181 277 ...
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. ...
#11l
11l
F is_prime(a) R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))   F generate_primes(n) V r = [2] V i = 3 L I is_prime(i) r.append(i) I r.len == n L.break i += 2 R r   V primes = generate_primes(50'000)   F find_combo(k, x, m, n, &combo) I k >= m ...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h>   using big_int = mpz_class;   big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) ...
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...
#BBC_BASIC
BBC BASIC
INSTALL @lib$ + "ARRAYLIB"   REM Describe the puzzle as a set of simultaneous equations: REM a + b = 151 REM a - c = 40 REM -b + c + d = 0 REM e + f = 40 REM -c + f + g = 0 REM -d + g + h = 0 REM e - x = 11 REM f - y = 11 REM g - y = 4 REM...
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...
#C
C
  /* Pascal's pyramid solver * * [top] * [ ] [ ] * [mid] [ ] [ ] * [ ] [ ] [ ] [ ] * [ x ] [ a ] [ y ] [ b ] [ z ] * x + z = y * * This solution makes use of a little bit of mathematical observation, * such as the fact that top = 4(a+b) + 7(...
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#Raku
Raku
use NativeCall; use SDL2::Raw;   my int ($w, $h) = 800, 800; my SDL_Window $window; my SDL_Renderer $renderer;   my int $particlenum = 3000;     SDL_Init(VIDEO); $window = SDL_CreateWindow( "Raku Particle System!", SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, $w, $h, RESIZABLE ); $renderer ...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#Fortran
Fortran
program peaceful_queens_elements_generator use, intrinsic :: iso_fortran_env, only: int64 use, intrinsic :: iso_fortran_env, only: error_unit   implicit none   ! 64-bit integers, for boards up to 8-by-8. integer, parameter :: kind8x8 = int64   ! 128-bit integers, for boards up to 11-by-11. ! This value is...
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...
#Ceylon
Ceylon
  module rosetta.passwordgenerator "1.0.0" { import ceylon.random "1.2.2"; }    
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#REXX
REXX
/*REXX pgm generates/displays all permutations of N different objects taken M at a time.*/ parse arg things bunch inbetweenChars names /*obtain optional arguments from the CL*/ if things=='' | things=="," then things= 3 /*Not specified? Then use the default.*/ if bunch=='' | bunch=="," then bunch= thing...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Processing
Processing
  //Abhishek Ghosh, 28th June 2022   void Peano(int x, int y, int lg, int i1, int i2) {   if (lg == 1) { ellipse(x,y,1,1); return; }   lg = lg/3; Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); Peano(x+lg, y+lg, lg, i1, 1-i2); Peano(x+((i1+i2)*lg...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#J
J
require 'format/printf numeric'   randomize '' NB. randomize seed for new session   Vals=: 'HT' NB. valid values input=: 1!:1@<&1: NB. get input from user prompt=: input@echo NB. prompt user for input checkInput...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Icon_and_Unicon
Icon and Unicon
# # Pathological floating point problems # procedure main() sequence() chaotic() end   # # First task, sequence convergence # link printf procedure sequence() local l := [2, -4] local iters := [3, 4, 5, 6, 7, 8, 20, 30, 50, 100, 200] local i, j, k local n := 1   write("Sequence conver...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Ruby
Ruby
def solve_pell(n) x = Integer.sqrt(n) y = x z = 1 r = 2*x e1, e2 = 1, 0 f1, f2 = 0, 1   loop do y = r*z - y z = (n - y*y) / z r = (x + y) / z e1, e2 = e2, r*e2 + e1 f1, f2 = f2, r*f2 + f1 a, b = e2 + x*f2, f2 break a, b if a*a - n*b*b == 1 end end   [61, 109, 181, 277].each...
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. ...
#C
C
#include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h>   typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array;   bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array =...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Delphi
Delphi
  program Partition_function_P;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers, System.Diagnostics;   var p: TArray<BigInteger>; pd: TArray<Integer>;   function PartiDiffDiff(n: Integer): Integer; begin if n and 1 = 1 then exit((n + 1) div 2); Result := n + 1; end;   function partDi...
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...
#C.23
C#
  using System;   namespace Pyramid_of_Numbers { class Program { public static void Main(string[] args) { // Set console properties Console.Title = " Pyramid of Numbers / Pascal's triangle Puzzle"; Console.SetBufferSize(80,1000); Console.SetWindowSize(80,60); Console.ForegroundColor = Cons...
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. ...
#Wren
Wren
import "dome" for Window, Platform, Process import "graphics" for Canvas, Color import "math" for Math, Point import "random" for Random import "input" for Keyboard import "./dynamic" for Struct   var Start = Platform.time var Rand = Random.new()   var fields = [ "particleNum", "positions", "velocities",...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#Go
Go
package main   import "fmt"   const ( empty = iota black white )   const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' )   type position struct{ i, j int }   func iabs(i int) int { if i < 0 { return -i } return i }   func place(m, n int, pBlackQueens, pWhiteQu...
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...
#Clojure
Clojure
(ns pwdgen.core (:require [clojure.set :refer [difference]] [clojure.tools.cli :refer [parse-opts]]) (:gen-class))   (def minimum-length 4) (def cli-options [["-c" "--count NUMBER" "Number of passwords to generate"  :default 1  :parse-fn #(Integer/parseInt %)] ["-l" "--length NUMBER" "Length ...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Ring
Ring
  load "stdlib.ring"   list = 1:4 lenList = len(list) permut = [] for perm = 1 to factorial(len(list)) for i = 1 to len(list) add(permut,list[i]) next perm(list) next for n = 1 to len(permut)/lenList for m = (n-1)*lenList+1 to n*lenList see "" + permut[m] if m < n*lenList ...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Prolog
Prolog
main:- write_peano_curve('peano_curve.svg', 656, 4).   write_peano_curve(File, Size, Order):- open(File, write, Stream), format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n", [Size, Size]), write(Stream, "<rect width='100%' height='100%' fill='white'/>...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Java
Java
import java.util.*;   public class PenneysGame {   public static void main(String[] args) { Random rand = new Random();   String compChoice = "", playerChoice; if (rand.nextBoolean()) {   for (int i = 0; i < 3; i++) compChoice += "HT".charAt(rand.nextInt(2)); ...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#J
J
vn=: 111 +(_1130 % _1&{) + (3000 % _1&{ * _2&{)
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Rust
Rust
  use num_bigint::{ToBigInt, BigInt}; use num_traits::{Zero, One}; //use std::mem::replace in the loop if you want this to be more efficient   fn main() { test(61u64); test(109u64); test(181u64); test(277u64); }   struct Pair { v1: BigInt, v2: BigInt, }   impl Pair { pub fn make_pair(a: &Big...
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Scala
Scala
def pellFermat(n: Int): (BigInt,BigInt) = { import scala.math.{sqrt, floor}   val x = BigInt(floor(sqrt(n)).toInt)   var i = 0   // Use the Continued Fractions method def converge(y:BigInt, z:BigInt, r:BigInt, e1:BigInt, e2:BigInt, f1:BigInt, f2:BigInt ) : (BigInt,BigInt) = {   val a = f2 * x + e2 val...
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. ...
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class Rosetta { static void Main() { foreach ((int x, int n) in new [] { (99809, 1), (18, 2), (19, 3), (20, 4), (2017...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Elixir
Elixir
  use Bitwise, skip_operators: true   defmodule Partition do def init(), do:  :ets.new :pN, [:set, :named_table, :private]   def gpentagonals(), do: Stream.unfold {1, 0}, &next/1 defp next({m, n}) do a = case rem m, 2 do 0 -> div m, 2 1 -> m end {n, {m + 1, ...
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Erlang
Erlang
  -mode(compile).   main(_) -> ets:new(pN, [set, named_table, protected]), io:format("~w~n", [p(6666)]).   p(0) -> 1; p(N) -> case ets:lookup(pN, N) of [{N, Pn}] -> Pn; [] -> Terms = [p(N - G) || G <- gpentagonals(N)], Pn = sum_partitions(Terms), ets:inser...
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...
#C.2B.2B
C++
#include <iostream> #include <iomanip>   inline int sign(int i) { return i < 0 ? -1 : i > 0; }   inline int& E(int *x, int row, int col) { return x[row * (row + 1) / 2 + col]; }   int iter(int *v, int *diff) { // enforce boundary conditions E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; ...
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class Peaceful { enum Piece { Empty, Black, White, }   public static class Position { public int x, y;   public Position(int x, int y) { this.x = x; this.y = y...
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...
#Commodore_BASIC
Commodore BASIC
1 rem password generator 2 rem rosetta code 10 g$(1)="abcdefghijklmnopqrstuvwxyz" 15 g$(2)="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 20 g$(3)="0123456789" 25 g$(4)="<>!@#$%^&*()[];:'.?/" 30 print chr$(147);chr$(14) 35 print "Password Generator":print 40 print "Press H for help, or any":print "other key to begin.":print 45 get k$:if...
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Ring_2
Ring
    Another Solution   // Permutations -- Bert Mariani 2020-07-12 // Ask User for number of digits to permutate    ? "Enter permutations number : " Give n n = number(n) x = 1:n // array    ? "Permutations are : " count = 0   nPermutation(1,n) //===>>> ST...
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Python
Python
  import turtle as tt import inspect   stack = [] # Mark the current stacks in run. def peano(iterations=1): global stack   # The turtle Ivan: ivan = tt.Turtle(shape = "classic", visible = True)     # The app window: screen = tt.Screen() screen.title("Desenhin do Peano") screen.bgcolor("#232...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Julia
Julia
  const SLEN = 3   autobet() = randbool(SLEN) function autobet(ob::BitArray{1}) rlen = length(ob) 2 < rlen || return ~ob 3 < rlen || return [~ob[2], ob[1:2]] opt = falses(rlen) opt[1] = true opt[end-1:end] = true ob != opt || return ~opt return opt end autobet(ob::Array{Bool,1}) = autobe...
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random()   val optimum = mapOf( "HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT", "THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT" )   fun getUserSequence(): String { println("A sequence of three H or T should be entered") ...
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Java
Java
import java.math.BigDecimal; import java.math.RoundingMode;   public class FPProblems { public static void wrongConvergence() { int[] INDEXES = new int[] { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 };   // Standard 64-bit floating point double[] fpValues = new double[100]; fpValues[0] = 2.0;...