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/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#E
E
pragma.syntax("0.9") pragma.enable("accumulator") def superscript(x, out) { if (x >= 10) { superscript(x // 10) } out.print("⁰¹²³⁴⁵⁶⁷⁸⁹"[x %% 10]) } def makePolynomial(initCoeffs :List) { def degree := { var i := initCoeffs.size() - 1 while (i >= 0 && initCoeffs[i] <=> 0) { i -= 1 } ...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Groovy
Groovy
class T implements Cloneable { String property String name() { 'T' } T copy() { try { super.clone() } catch(CloneNotSupportedException e) { null } } @Override boolean equals(that) { this.name() == that?.name() && this.property == that?.property } }   class S extends T { @Over...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Python
Python
import math   import pygame from pygame.locals import *   pygame.init() screen = pygame.display.set_mode((1024, 600))   pygame.display.set_caption("Polyspiral")   incr = 0   running = True   while running: pygame.time.Clock().tick(60) for event in pygame.event.get(): if event.type==QUIT: running = False break...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#FreeBASIC
FreeBASIC
#Include "crt.bi" 'for rounding only   Type vector Dim As Double element(Any) End Type   Type matrix Dim As Double element(Any,Any) Declare Function inverse() As matrix Declare Function transpose() As matrix private: Declare Function GaussJordan(As vector) As vector End Type   'mult operators O...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#C.2B.2B
C++
#include <iostream> #include <set> #include <vector> #include <iterator> #include <algorithm> typedef std::set<int> set_type; typedef std::set<set_type> powerset_type;   powerset_type powerset(set_type const& set) { typedef set_type::const_iterator set_iter; typedef std::vector<set_iter> vec; typedef vec::iterato...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#BASIC256
BASIC256
for i = 1 to 99 if isPrime(i) then print string(i); " "; next i end   function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v mod d = 0 then return False else d += 2 end while return True end fu...
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Elixir
Elixir
defmodule Price do @table [ {0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32}, {0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54}, {0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70}, {0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86}, {0.86, 0.90}, {0.91, 0.94}, {0.96...
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#GFA_Basic
GFA Basic
  OPENW 1 CLEARW 1 ' ' Array f% is used to hold the divisors DIM f%(SQR(20000)) ! cannot redim arrays, so set size to largest needed ' ' 1. Show proper divisors of 1 to 10, inclusive ' FOR i%=1 TO 10 num%=@proper_divisors(i%) PRINT "Divisors for ";i%;":"; FOR j%=1 TO num% PRINT " ";f%(j%); NEXT j% PRINT N...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Nim
Nim
import tables, random, strformat, times   var start = cpuTime()   const NumTrials = 1_000_000 Probabilities = {"aleph": 1 / 5, "beth": 1 / 6, "gimel": 1 / 7, "daleth": 1 / 8, "he": 1 / 9, "waw": 1 / 10, "zayin": 1 / 11, "heth": 1759 / 27720}.toTable   var samples: CountTable[string]   randomize()...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#OCaml
OCaml
let p = [ "Aleph", 1.0 /. 5.0; "Beth", 1.0 /. 6.0; "Gimel", 1.0 /. 7.0; "Daleth", 1.0 /. 8.0; "He", 1.0 /. 9.0; "Waw", 1.0 /. 10.0; "Zayin", 1.0 /. 11.0; "Heth", 1759.0 /. 27720.0; ]   let rec take k = function | (v, p)::tl -> if k < p then v else take (k -. p) tl ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Julia
Julia
  using Base.Collections   test = ["Clear drains" 3; "Feed cat" 4; "Make tea" 5; "Solve RC tasks" 1; "Tax return" 2]   task = PriorityQueue(Base.Order.Reverse) for i in 1:size(test)[1] enqueue!(task, test[i,1], test[i,2]) end   println("Tasks, completed according to priority:") while...
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#VBA
VBA
  Option Explicit Option Base 0   Private Const intBase As Integer = 0   Private Type tPoint X As Double Y As Double End Type Private Type tCircle Centre As tPoint Radius As Double End Type   Private Sub sApollonius() Dim Circle1 As tCircle Dim Circle2 As tCircle Dim Circle3 As tCircle Dim CTanTanTa...
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#Wren
Wren
import "/dynamic" for Tuple   var Circle = Tuple.create("Circle", ["x", "y", "r"])   var solveApollonius = Fn.new { |c1, c2, c3, s1, s2, s3| var x1 = c1.x var y1 = c1.y var r1 = c1.r   var x2 = c2.x var y2 = c2.y var r2 = c2.r   var x3 = c3.x var y3 = c3.y var r3 = c3.r   var v11...
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Yabasic
Yabasic
print peek$("program_name")   s$ = system$("cd") n = len(s$) print left$(s$, n - 2), "\\", peek$("program_name")
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Zig
Zig
const std = @import("std");   const debug = std.debug; const heap = std.heap; const process = std.process;   pub fn main() !void { var args = process.args();   const program_name = try args.next(heap.page_allocator) orelse unreachable; defer heap.page_allocator.free(program_name);   debug.warn("{}\n", ....
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#zkl
zkl
#!/Homer/craigd/Bin/zkl println(System.argv);
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Scheme
Scheme
(use srfi-42)   (define (py perim) (define prim 0) (values (sum-ec (: c perim) (: b c) (: a b) (if (and (<= (+ a b c) perim) (= (square c) (+ (square b) (square a))))) (begin (when (= 1 (gcd a b)) (inc! prim))) 1) prim))
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Scala
Scala
if (problem) { // sys.exit returns type "Nothing" sys.exit(0) // conventionally, error code 0 is the code for "OK", // while anything else is an actual problem }  
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Scheme
Scheme
(if problem (exit)) ; exit successfully
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#REXX
REXX
/*REXX pgm tests for primality via Wilson's theorem: a # is prime if p divides (p-1)! +1*/ parse arg LO zz /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 120 /*Not specified? Then use the default.*/ if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 ...
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const func set of integer: eratosthenes (in integer: n) is func result var set of integer: sieve is EMPTY_SET; local var integer: i is 0; var integer: j is 0; begin sieve := {2 .. n}; for i range 2 to sqrt(n) do if i in sieve then ...
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Delphi
Delphi
  program Prime_decomposition;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function IsPrime(n: UInt64): Boolean; var i: Integer; begin if n <= 1 then exit(False);   i := 2; while i < Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end;   Result := True; end;   function Get...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
var p *int // declare p to be a pointer to an int i = &p // assign i to be the int value pointed to by p
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Haskell
Haskell
  import Data.STRef   example :: ST s () example = do p <- newSTRef 1 k <- readSTRef p writeSTRef p (k+1)  
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Clojure
Clojure
(use '(incanter core stats charts)) (def x (range 0 10)) (def y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) (view (xy-plot x y))  
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Ceylon
Ceylon
import ceylon.language { consolePrint = print }   shared void run() {   class Point {   shared variable Integer x; shared variable Integer y;   shared new(Integer x = 0, Integer y = 0) { this.x = x; this.y = y; }   shared new copy(Point p) { ...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Elixir
Elixir
defmodule Card do @faces ~w(2 3 4 5 6 7 8 9 10 j q k a) @suits ~w(♥ ♦ ♣ ♠) # ~w(h d c s) @ordinal @faces |> Enum.with_index |> Map.new   defstruct ~w[face suit ordinal]a   def new(str) do {face, suit} = String.split_at(str, -1) if face in @faces and suit in @suits do ...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#BASIC256
BASIC256
print "Pop cont (3^x): "; for i = 0 to 29 print population(3^i); " "; #los últimos números no los muestra correctamente next i   print : print print "Evil numbers: "; call EvilOdious(30, 0)   print : print print "Odious numbers: "; call EvilOdious(30, 1) end   subroutine EvilOdious(limit, type) i = 0 : cont =...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Elixir
Elixir
defmodule Polynomial do def division(_, []), do: raise ArgumentError, "denominator is zero" def division(_, [0]), do: raise ArgumentError, "denominator is zero" def division(f, g) when length(f) < length(g), do: {[0], f} def division(f, g) do {q, r} = division(g, [], f) if q==[], do: q = [0] if r==[...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Icon_and_Unicon
Icon and Unicon
class T() method a(); write("This is T's a"); end end   class S: T() method a(); write("This is S's a"); end end   procedure main() write("S:",deepcopy(S()).a()) end   procedure deepcopy(A, cache) #: return a deepcopy of A local k   /cache := table() # used to handle multireferenced objects ...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Racket
Racket
#lang racket   (require 2htdp/universe pict racket/draw)   (define ((polyspiral width height segment-length-increment n-segments) tick/s/28) (define turn-angle (degrees->radians (/ tick/s/28 8))) (pict->bitmap (dc (λ (dc dx dy) (define old-brush (send dc get-brush)) (define old-pen (send dc get...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Raku
Raku
use SVG; my $w = 600; my $h = 600;   for 3..33 -> $a { my $angle = $a/τ; my $x1 = $w/2; my $y1 = $h/2; my @lines;   for 1..144 { my $length = 3 * $_; my ($x2, $y2) = ($x1, $y1) «+« |cis($angle * $_).reals».round(.01) »*» $length ; @lines.push: 'line' => [:x1($x1.clone), :y1(...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#GAP
GAP
PolynomialRegression := function(x, y, n) local a; a := List([0 .. n], i -> List(x, s -> s^i)); return TransposedMat((a * TransposedMat(a))^-1 * a * TransposedMat([y]))[1]; end;   x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; y := [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];   # Return coefficients in...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Clojure
Clojure
(use '[clojure.math.combinatorics :only [subsets] ])   (def S #{1 2 3 4})   user> (subsets S) (() (1) (2) (3) (4) (1 2) (1 3) (1 4) (2 3) (2 4) (3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4) (1 2 3 4))
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#BBC_BASIC
BBC BASIC
FOR i% = -1 TO 100 IF FNisprime(i%) PRINT ; i% " is prime" NEXT END   DEF FNisprime(n%) IF n% <= 1 THEN = FALSE IF n% <= 3 THEN = TRUE IF (n% AND 1) = 0 THEN = FALSE LOCAL t% FOR t% = 3 TO SQR(n%) STEP 2 IF n% MOD t% = 0 THEN = FALSE NEXT ...
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Erlang
Erlang
priceFraction(N) when N < 0 orelse N > 1 -> erlang:error('Values must be between 0 and 1.'); priceFraction(N) when N < 0.06 -> 0.10; priceFraction(N) when N < 0.11 -> 0.18; priceFraction(N) when N < 0.16 -> 0.26; priceFraction(N) when N < 0.21 -> 0.32; priceFraction(N) when N < 0.26 -> 0.38; priceFraction(N) when N...
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Go
Go
package main   import ( "fmt" "strconv" )   func listProperDivisors(limit int) { if limit < 1 { return } width := len(strconv.Itoa(limit)) for i := 1; i <= limit; i++ { fmt.Printf("%*d -> ", width, i) if i == 1 { fmt.Println("(None)") continue ...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#PARI.2FGP
PARI/GP
pc()={ my(v=[5544,10164,14124,17589,20669,23441,25961,27720],u=vector(8),e); for(i=1,1e6, my(r=random(27720)); for(j=1,8, if(r<v[j], u[j]++; break) ) ); e=precision([1/5,1/6,1/7,1/8,1/9,1/10,1/11,1759/27720]*1e6,9); \\ truncate to 9 decimal places print("Totals: "u); print("Expected: "e); ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Kotlin
Kotlin
import java.util.PriorityQueue   internal data class Task(val priority: Int, val name: String) : Comparable<Task> { override fun compareTo(other: Task) = when { priority < other.priority -> -1 priority > other.priority -> 1 else -> 0 } }   private infix fun String.priority(priority: Int)...
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#zkl
zkl
class Circle{ fcn init(xpos,ypos,radius){ var [const] x=xpos.toFloat(), y=ypos.toFloat(),r=radius.toFloat(); } fcn toString{ "Circle(%f,%f,%f)".fmt(x,y,r) } fcn apollonius(c2,c3,outside=True){ s1:=s2:=s3:=outside and 1 or -1;   v11:=2.0*(c2.x - x); v12:=2.0*(c2.y - y); v13:=x.p...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Scratch
Scratch
$ include "seed7_05.s7i"; include "bigint.s7i";   var bigInteger: total is 0_; var bigInteger: prim is 0_; var bigInteger: max_peri is 10_;   const proc: new_tri (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func local var bigInteger: p is 0_; begin p := a + b + c; if p <= max_peri then ...
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin # whatever logic is required in your main procedure if some_condition then exit(PROGRAM); end if; end func;
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#SenseTalk
SenseTalk
  if problemCondition then exit all  
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Ring
Ring
  load "stdlib.ring"   decimals(0) limit = 19   for n = 2 to limit fact = factorial(n-1) + 1 see "Is " + n + " prime: " if fact % n = 0 see "1" + nl else see "0" + nl ok next  
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Ruby
Ruby
def w_prime?(i) return false if i < 2 ((1..i-1).inject(&:*) + 1) % i == 0 end   p (1..100).select{|n| w_prime?(n) }  
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Sidef
Sidef
var primes = (^Inf -> lazy.grep{.is_prime})   var upto = 1e6 var conspiracy = Hash()   primes.first(upto+1).reduce { |a,b| var d = b%10 conspiracy{"#{a} → #{d}"} := 0 ++ d }   for k,v in (conspiracy.sort_by{|k,_v| k }) { printf("%s count: %6s\tfrequency: %2.2f %\n", k, v.commify, v / upto * 100) }
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#E
E
def primes := { var primesCache := [2] /** A collection of all prime numbers. */ def primes { to iterate(f) { primesCache.iterate(f) for x in (int > primesCache.last()) { if (isPrime(x)) { f(primesCache.size(), x) primes...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Icon_and_Unicon
Icon and Unicon
public class Foo { public int x = 0; }   void somefunction() { Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null a = new Foo(); // this assigns a to point to a new Foo object Foo b = a; // this declares another reference to point to the same object t...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#J
J
public class Foo { public int x = 0; }   void somefunction() { Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null a = new Foo(); // this assigns a to point to a new Foo object Foo b = a; // this declares another reference to point to the same object t...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Delphi
Delphi
  program Plot_coordinate_pairs;   {$APPTYPE CONSOLE}   uses System.SysUtils, Boost.Process;   var x: TArray<Integer>; y: TArray<Double>;   begin x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0];   var plot := TPipe.Create('gnuplot -p', True); plot...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Clojure
Clojure
(defprotocol Printable (print-it [this] "Prints out the Printable."))   (deftype Point [x y] Printable (print-it [this] (println (str "Point: " x " " y))))   (defn create-point "Redundant constructor function." [x y] (Point. x y))   (deftype Circle [x y r] Printable (print-it [this] (println (str "Circl...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#F.23
F#
  type Card = int * int   type Cards = Card list   let joker = (69,69)   let rankInvalid = "invalid", 99   let allCards = {0..12} |> Seq.collect (fun x->({0..3} |> Seq.map (fun y->x,y)))   let allSame = function | y::ys -> List.forall ((=) y) ys | _-> false   let straightList (xs:int list) = xs |> List.sort |> List.map...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#BCPL
BCPL
get "libhdr"   // Definitions let popcount(n) = n=0 -> 0, (n&1) + popcount(n >> 1) let evil(n) = (popcount(n) & 1) = 0 let odious(n) = (popcount(n) & 1) = 1   // The BCPL word size is implementation-dependent, // but very unlikely to be big enough to store 3^29. // This implements a 48-bit integer using byte stri...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#F.23
F#
  let rec shift n l = if n <= 0 then l else shift (n-1) (l @ [0.0]) let rec pad n l = if n <= 0 then l else pad (n-1) (0.0 :: l) let rec norm = function | 0.0 :: tl -> norm tl | x -> x let deg l = List.length (norm l) - 1   let zip op p q = let d = (List.length p) - (List.length q) in List.map2 op (pad (-d) p) (pad...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#J
J
def=: abc
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Java
Java
class T implements Cloneable { public String name() { return "T"; } public T copy() { try { return (T)super.clone(); } catch (CloneNotSupportedException e) { return null; } } }   class S extends T { public String name() { return "S"; } }   public class Pol...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Ring
Ring
  # Project : Polyspiral   load "guilib.ring"   paint = null incr = 1 x1 = 1000 y1 = 1080 angle = 10 length = 10   new qapp { win1 = new qwidget() { setwindowtitle("") setgeometry(10,10,1000,1080) label1 = new qlabel(win1) { ...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Scala
Scala
import java.awt._ import java.awt.event.ActionEvent   import javax.swing._   object PolySpiral extends App {   SwingUtilities.invokeLater(() => new JFrame("PolySpiral") {   class PolySpiral extends JPanel { private var inc = 0.0   override def paintComponent(gg: Graphics): Unit = { ...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#gnuplot
gnuplot
# The polynomial approximation f(x) = a*x**2 + b*x + c   # Initial values for parameters a = 0.1 b = 0.1 c = 0.1   # Fit f to the following data by modifying the variables a, b, c fit f(x) '-' via a, b, c 0 1 1 6 2 17 3 34 4 57 5 86 6 121 7 162 8 209 9 262 10 321 e   print sprint...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#CoffeeScript
CoffeeScript
  print_power_set = (arr) -> console.log "POWER SET of #{arr}" for subset in power_set(arr) console.log subset   power_set = (arr) -> result = [] binary = (false for elem in arr) n = arr.length while binary.length <= n result.push bin_to_arr binary, arr i = 0 while true if binary[i] ...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#bc
bc
/* Return 1 if n is prime, 0 otherwise */ define p(n) { auto i   if (n < 2) return(0) if (n == 2) return(1) if (n % 2 == 0) return(0) for (i = 3; i * i <= n; i += 2) { if (n % i == 0) return(0) } return(1) }
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Euphoria
Euphoria
constant table = { {0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32}, {0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54}, {0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70}, {0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86}, {0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00} } ...
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Haskell
Haskell
import Data.Ord import Data.List   divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]   main :: IO () main = do putStrLn "divisors of 1 to 10:" mapM_ (print . divisors) [1 .. 10] putStrLn "a number with the most divisors within 1 to 20000 (number, count):" print $ m...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Perl
Perl
use List::Util qw(first sum); use constant TRIALS => 1e6;   sub prob_choice_picker { my %options = @_; my ($n, @a) = 0; while (my ($k,$v) = each %options) { $n += $v; push @a, [$n, $k]; } return sub { my $r = rand; ( first {$r <= $_->[0]} @a )->[1]; }; }   my %ps = (aleph => 1/5, ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Lasso
Lasso
define priorityQueue => type { data store = map, cur_priority = void   public push(priority::integer, value) => { local(store) = .`store`->find(#priority)   if(#store->isA(::array)) => { #store->insert(#value) return } .`store`->inse...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   var bigInteger: total is 0_; var bigInteger: prim is 0_; var bigInteger: max_peri is 10_;   const proc: new_tri (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func local var bigInteger: p is 0_; begin p := a + b + c; if p <= max_peri then ...
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Sidef
Sidef
if (problem) { Sys.exit(code); }
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Simula
Simula
IF terminallyIll THEN terminate_program;
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Rust
Rust
fn factorial_mod(mut n: u32, p: u32) -> u32 { let mut f = 1; while n != 0 && f != 0 { f = (f * n) % p; n -= 1; } f }   fn is_prime(p: u32) -> bool { p > 1 && factorial_mod(p - 1, p) == p - 1 }   fn main() { println!(" n | prime?\n------------"); for p in vec![2, 3, 9, 15, 29...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Sidef
Sidef
func is_wilson_prime_slow(n) { n > 1 || return false (n-1)! % n == n-1 }   func is_wilson_prime_fast(n) { n > 1 || return false factorialmod(n-1, n) == n-1 }   say 25.by(is_wilson_prime_slow) #=> [2, 3, 5, ..., 83, 89, 97] say 25.by(is_wilson_prime_fast) #=> [2, 3, 5, ..., 83, 89, 97]   say is_w...
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#VBA
VBA
  Option Explicit   Sub Main() Dim Dict As Object, L() As Long Dim t As Single   Init Dict L = ListPrimes(100000000) t = Timer PrimeConspiracy L, Dict, 1000000 Debug.Print "----------------------------" Debug.Print "Execution time : " & Format(Timer - t, "0.000s.") Debug.Print "" Init Dict t = Timer Prim...
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#EchoLisp
EchoLisp
(prime-factors 1024) → (2 2 2 2 2 2 2 2 2 2)   (lib 'bigint) ;; 2^59 - 1 (prime-factors (1- (expt 2 59))) → (179951 3203431780337)   (prime-factors 100000000000000000037) → (31 821 66590107 59004541)
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Java
Java
public class Foo { public int x = 0; }   void somefunction() { Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null a = new Foo(); // this assigns a to point to a new Foo object Foo b = a; // this declares another reference to point to the same object t...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Julia
Julia
x = [1, 2, 3, 7]   parr = pointer(x)   xx = unsafe_load(parr, 4)   println(xx) # Prints 7  
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#EasyLang
EasyLang
x[] = [ 0 1 2 3 4 5 6 7 8 9 ] y[] = [ 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 ] # clear linewidth 0.5 move 10 3 line 10 95 line 95 95 textsize 3 n = len x[] m = 0 for i range n m = higher y[i] m . linewidth 0.1 sty = m div 9 for i range 10 move 2 94 - i * 10 text i * sty move 10 95 - i * 10 line ...
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Common_Lisp
Common Lisp
(defclass point () ((x :initarg :x :initform 0 :accessor x) (y :initarg :y :initform 0 :accessor y)))   (defclass circle (point) ((radius :initarg :radius :initform 0 :accessor radius)))   (defgeneric shallow-copy (object)) (defmethod shallow-copy ((p point)) (make-instance 'point :x (x p) :y (y p))) (defmetho...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Factor
Factor
USING: formatting kernel poker sequences ; { "2H 2D 2C KC QD" "2H 5H 7D 8C 9S" "AH 2D 3C 4C 5D" "2H 3H 2D 3C 3D" "2H 7H 2D 3C 3D" "2H 7H 7D 7C 7S" "TH JH QH KH AH" "4H 4S KS 5D TS" "QC TC 7C 6C 4C" } [ dup string>hand-name "%s: %s\n" printf ] each
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#BQN
BQN
PopCount ← {(2|𝕩)+𝕊⍟×⌊𝕩÷2} Odious ← 2|PopCount Evil ← ¬Odious   _List ← {𝕩↑𝔽¨⊸/↕2×𝕩} >⟨PopCount¨ 3⋆↕30, Evil _List 30, Odious _List 30⟩
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Factor
Factor
USE: math.polynomials   { -42 0 -12 1 } { -3 1 } p/mod ptrim [ . ] bi@
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#JavaScript
JavaScript
function clone(obj){ if (obj == null || typeof(obj) != 'object') return obj;   var temp = {}; for (var key in obj) temp[key] = clone(obj[key]); return temp; }
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Julia
Julia
  abstract type Jewel end   mutable struct RoseQuartz <: Jewel carats::Float64 quality::String end   mutable struct Sapphire <: Jewel color::String carats::Float64 quality::String end   color(j::RoseQuartz) = "rosepink" color(j::Jewel) = "Use the loupe." color(j::Sapphire) = j.color   function testt...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#SPL
SPL
width,height = #.scrsize() #.angle(#.degrees) #.scroff() incr = 0 > incr = (incr+0.05)%360 x = width/2 y = height/2 length = 5 angle = incr #.scrclear() #.drawline(x,y,x,y) > i, 1..150 x += length*#.cos(angle) y += length*#.sin(angle) #.drawcolor(#.hsv2rgb(angle,1,1):3) #.drawline(x,y) ...
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#SVG
SVG
  <svg viewBox="0 0 100 100" stroke="#000" stroke-width="0.3"> <g> <line x1="50" y1="50" x2="54" y2="50"></line> <animateTransform attributeName="transform" type="rotate" from="-120 50 50" to="240 50 50" dur="2400s" repeatCount="indefinite"></animateTransform> <g> <line x1="54" y1="50" x2="58.16" y2...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Go
Go
package main   import ( "fmt" "log"   "gonum.org/v1/gonum/mat" )   func main() { var ( x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}   degree = 2   a = Vandermonde(x, degree+1) b = mat.NewDense(len(y), 1, y) c = mat.NewDense(degree+1, 1, nil...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#ColdFusion
ColdFusion
public array function powerset(required array data) { var ps = [""]; var d = arguments.data; var lenData = arrayLen(d); var lenPS = 0; for (var i=1; i LTE lenData; i++) { lenPS = arrayLen(ps); for (var j = 1; j LTE lenPS; j++) { arrayAppend(ps, listAppend(ps[j], d[i])); } } return ...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#BCPL
BCPL
get "libhdr"   let sqrt(s) = s <= 1 -> 1, valof $( let x0 = s >> 1 let x1 = (x0 + s/x0) >> 1 while x1 < x0 $( x0 := x1 x1 := (x0 + s/x0) >> 1 $) resultis x0 $)   let isprime(n) = n < 2 -> false, (n & 1) = 0 -> n = 2, valof $( for i = 3 to sqrt(n) by 2 i...
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#F.23
F#
let cin = [ 0.06m .. 0.05m ..1.01m ] let cout = [0.1m; 0.18m] @ [0.26m .. 0.06m .. 0.44m] @ [0.50m .. 0.04m .. 0.98m] @ [1.m]   let priceadjuster p = let rec bisect lo hi = if lo < hi then let mid = (lo+hi)/2. let left = p < cin.[int mid] bisect (if left then lo else mid...
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#J
J
factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ properDivisors=: factors -. ]
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Phix
Phix
with javascript_semantics constant lim = 1000000, {names, probs} = columnize({{"aleph", 1/5}, {"beth", 1/6}, {"gimel", 1/7}, {"daleth", 1/8}, {"he", 1/9}, {"waw", ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Lua
Lua
PriorityQueue = { __index = { put = function(self, p, v) local q = self[p] if not q then q = {first = 1, last = 0} self[p] = q end q.last = q.last + 1 q[q.last] = v end, pop = function(self) ...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Sidef
Sidef
func triples(limit) { var primitive = 0 var civilized = 0   func oyako(a, b, c) { (var perim = a+b+c) > limit || ( primitive++ civilized += int(limit / perim) oyako( a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c) oyako( a + 2*b + 2*c, 2*a + b + 2*c,...
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Slate
Slate
problem ifTrue: [exit: 1].
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#SNOBOL4
SNOBOL4
&code = condition errlevel :s(end)
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Swift
Swift
import BigInt   func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 }   return stride(from: n, to: 0, by: -1).reduce(1, *) }     func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool { guard n >= 2 else { return false }   return (factorial(n - 1) + 1) % n == 0 }   print((1......
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Tiny_BASIC
Tiny BASIC
PRINT "Number to test" INPUT N IF N < 0 THEN LET N = -N IF N = 2 THEN GOTO 30 IF N < 2 THEN GOTO 40 LET F = 1 LET J = 1 10 LET J = J + 1 REM exploits the fact that (F mod N)*J = (F*J mod N) REM to do the factorial without overflowing LET F = F * J GOSUB 20 IF J < N - 1...
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   var wilson = Fn.new { |p| if (p < 2) return false return (Int.factorial(p-1) + 1) % p == 0 }   for (p in 1..19) { Fmt.print("$2d -> $s", p, wilson.call(p) ? "prime" : "not prime") }
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int import "/sort" for Sort   var reportTransitions = Fn.new { |transMap, num| var keys = transMap.keys.toList Sort.quick(keys) System.print("First %(Fmt.dc(0, num)) primes. Transitions prime \% 10 -> next-prime \% 10.") for (key in keys) { var count = tr...
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Eiffel
Eiffel
class PRIME_DECOMPOSITION   feature   factor (p: INTEGER): ARRAY [INTEGER] -- Prime decomposition of 'p'. require p_positive: p > 0 local div, i, next, rest: INTEGER do create Result.make_empty if p = 1 then Resu...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Kotlin
Kotlin
// Kotlin Native v0.3   import kotlinx.cinterop.*   fun main(args: Array<String>) { // allocate space for an 'int' on the native heap and wrap a pointer to it in an IntVar object val intVar: IntVar = nativeHeap.alloc<IntVar>() intVar.value = 3 // set its value println(intVar.value) ...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#EchoLisp
EchoLisp
  (lib 'plot)   (define ys #(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0) ) (define (f n) [ys n])   (plot-sequence f 9) → (("x:auto" 0 9) ("y:auto" 2 198)) (plot-grid 1 20) (plot-text " Rosetta plot coordinate pairs" 0 10 "white")