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/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
#Java
Java
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { t...
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,...
#Python
Python
from collections import namedtuple   class Card(namedtuple('Card', 'face, suit')): def __repr__(self): return ''.join(self)     suit = '♥ ♦ ♣ ♠'.split() # ordered strings of faces faces = '2 3 4 5 6 7 8 9 10 j q k a' lowaces = 'a 2 3 4 5 6 7 8 9 10 j q k' # faces as lists face = faces.split() lowace = l...
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 ...
#Fermat
Fermat
Func Popcount(n) = if n = 0 then 0 else if 2*(n\2)=n then Popcount(n\2) else Popcount((n-1)\2)+1 fi fi. Func Odiousness(n) = p:=Popcount(n);if 2*(p\2) = p then 0 else 1 fi.   for n=0 to 29 do !Popcount(3^n);!' ' od e:=0 n:=0 while e<30 do if Odiousness(n)=0 then !n;!' ';e:=e+1 fi; n:=n+1 od e:=0 n:=0 while e<30 do if O...
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...
#Phix
Phix
-- demo\rosetta\Polynomial_long_division.exw with javascript_semantics function degree(sequence p) for i=length(p) to 1 by -1 do if p[i]!=0 then return i end if end for return -1 end function function poly_div(sequence n, d) d = deep_copy(d) while length(d)<length(n) do d &=0 end while ...
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...
#OCaml
OCaml
open Base open Stdio   let mean fa = let open Float in (Array.reduce_exn fa ~f:(+)) / (of_int (Array.length fa))   let regression xs ys = let open Float in let xm = mean xs in let ym = mean ys in let x2m = Array.map xs ~f:(fun x -> x * x) |> mean in let x3m = Array.map xs ~f:(fun x -> x * x * x) |> mean i...
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...
#Go
Go
package main   import ( "fmt" "strconv" "strings" )   // types needed to implement general purpose sets are element and set   // element is an interface, allowing different kinds of elements to be // implemented and stored in sets. type elem interface { // an element must be distinguishable from other e...
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 ...
#Crystal
Crystal
Mathematicaly basis of Prime Generators https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
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 ...
#K
K
  le:- 0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0 out: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1   pf:{out@_bin[le;-x]}'  
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 ...
#Kotlin
Kotlin
// version 1.0.6   fun rescale(price: Double): Double = when { price < 0.06 -> 0.10 price < 0.11 -> 0.18 price < 0.16 -> 0.26 price < 0.21 -> 0.32 price < 0.26 -> 0.38 price < 0.31 -> 0.44 price < 0.36 -> 0.50 price < 0.41 -> 0.54 pric...
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...
#Pascal
Pascal
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; const MAXPROPERDIVS = 1920; type tRes = array[0..MAXPROPERDIVS] of LongWord; tPot = record potPrim, potMax :LongWord; end;   tprimeFac = record pfPrims : array[1..10] of tPot; ...
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...
#Ursala
Ursala
#import std #import nat #import flo   outcomes = <'aleph ','beth ','gimel ','daleth','he ','waw ','zayin ','heth '> probabilities = ^lrNCT(~&,minus/1.+ plus:-0) div/*1. float* skip/5 iota12   simulation =   ^(~&rn,div+ float~~rmPlX)^*D/~& iota; ^A(~&h,length)*K2+ * stochasm@p/probabilities !* outcomes   format ...
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...
#PicoLisp
PicoLisp
# Insert item into priority queue (de insertPQ (Queue Prio Item) (idx Queue (cons Prio Item) T) )   # Remove and return top item from priority queue (de removePQ (Queue) (cdar (idx Queue (peekPQ Queue) NIL)) )   # Find top element in priority queue (de peekPQ (Queue) (let V (val Queue) (while (cadr V) ...
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 ...
#Groovy
Groovy
def factorize = { long target ->   if (target == 1) return [1L]   if (target < 4) return [1L, target]   def targetSqrt = Math.sqrt(target) def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 } if (lowfactors == []) return [1L, target] def nhalf = lowfactors.size() - ((lowfactors[-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....
#M2000_Interpreter
M2000 Interpreter
  Module Pairs { \\ written in version 9.5 rev. 13 \\ use Gdi+ antialiasing (not work with Wine in Linux, but we get no error) smooth on Const center=2, right=3, left=1, blue=1, angle=0, dotline=3 Const size9pt=9, size11pt=11 Cls ,0 ' use current background color, set split scree...
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
#JavaScript
JavaScript
/* create new Point in one of these ways: * var p = new Point(x,y); * var p = new Point(a_point); * default value for x,y is 0 */ function Point() { var arg1 = arguments[0]; var arg2 = arguments[1];   if (arg1 instanceof Point) { this.x = arg1.x; this.y = arg1.y; } else { ...
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,...
#Racket
Racket
#lang racket (require (only-in srfi/1 car+cdr))   ;;; -------------------------------------------------------------------------------------------------- ;;; The analyser is first... the rest of it is prettiness surrounding strings and parsing! ;;; ------------------------------------------------------------------------...
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 ...
#Forth
Forth
: popcnt ( n -- u) 0 swap BEGIN dup WHILE tuck 1 AND + swap 1 rshift REPEAT DROP ; : odious? ( n -- t|f) popcnt 1 AND ; : evil? ( n -- t|f) odious? 0= ;   CREATE A 30 , : task1 1 0 ." 3**i popcnt: " BEGIN dup A @ < WHILE over popcnt . 1+ swap 3 * swap REPEAT DROP DROP CR ; : task2 0 0 ....
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...
#PicoLisp
PicoLisp
(de degree (P) (let I NIL (for (N . C) P (or (=0 C) (setq I N)) ) (dec I) ) )   (de divPoly (N D) (if (lt0 (degree D)) (quit "Div/0" D) (let (Q NIL Diff) (while (ge0 (setq Diff (- (degree N) (degree D)))) (setq Q (need (- -1 Diff) Q 0)) (let E D ...
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...
#Python
Python
# -*- coding: utf-8 -*-   from itertools import izip   def degree(poly): while poly and poly[-1] == 0: poly.pop() # normalize return len(poly)-1   def poly_div(N, D): dD = degree(D) dN = degree(N) if dD < 0: raise ZeroDivisionError if dN >= dD: q = [0] * dN while dN >= ...
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...
#Octave
Octave
x = [0:10]; y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; coeffs = polyfit(x, y, 2)
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...
#Groovy
Groovy
  def powerSetRec(head, tail) { if (!tail) return [head] powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail()) }   def powerSet(set) { powerSetRec([], set as List) as Set}  
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 ...
#D
D
import std.stdio, std.algorithm, std.range, std.math;   bool isPrime1(in int n) pure nothrow { if (n == 2) return true; if (n <= 1 || (n & 1) == 0) return false;   for(int i = 3; i <= real(n).sqrt; i += 2) if (n % i == 0) return false; return true; }   void main() { ...
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 ...
#langur
langur
# using an implied parameter .f ... val .pricefrac = f given .f { case >= 0.00, < 0.06: 0.10 case >= 0.06, < 0.11: 0.18 case >= 0.11, < 0.16: 0.26 case >= 0.16, < 0.21: 0.32 case >= 0.21, < 0.26: 0.38 case >= 0.26, < 0.31: 0.44 case >= 0.31, < 0.36: 0.50 case >= 0.36, < 0.41: 0.54 ca...
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...
#Perl
Perl
use ntheory qw/divisors/; sub proper_divisors { my $n = shift; # Like Pari/GP, divisors(0) = (0,1) and divisors(1) = () return 1 if $n == 0; my @d = divisors($n); pop @d; # divisors are in sorted order, so last entry is the input @d; } say "$_: ", join " ", proper_divisors($_) for 1..10; # 1. For the max, ...
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...
#VBScript
VBScript
  item = Array("aleph","beth","gimel","daleth","he","waw","zayin","heth") prob = Array(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720) Dim cnt(7)   'Terminate script if sum of probabilities <> 1. sum = 0 For i = 0 To UBound(prob) sum = sum + prob(i) Next   If sum <> 1 Then WScript.Quit End If   For tri...
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...
#Prolog
Prolog
priority-queue :- TL0 = [3-'Clear drains', 4-'Feed cat'],   % we can create a priority queue from a list list_to_heap(TL0, Heap0),   % alternatively we can start from an empty queue % get from empty_heap/1.   % now we add the other elements add_to_heap(Heap0, 5, 'Make tea', Heap1), add_to_heap(...
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 ...
#Haskell
Haskell
factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ] -- [2..n] >>= (\p-> [p|isPrime p]) >>= divs n where divs n p | rem n p == 0 = p : divs (quot n p) p | otherwise = []
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....
#Maple
Maple
x := Vector([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): y := Vector([2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]): plot(x,y,style="point");
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....
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
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}; ListPlot[{x, y} // Transpose]
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
#jq
jq
  def Point(x;y): {"type": "Point", "x": x, "y": y}; def Point(x): Point(x;0); def Point: Point(0);   def Circle(x;y;r): {"type": "Circle", "x": x, "y": y, "r": r}; def Circle(x;y): Circle(x;y;0); def Circle(x): Circle(x;0); def Circle: Circle(0);   def print: if .type == "Circle" then "\(.type)(\(.x); \(.y); \(.r))...
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
#Julia
Julia
mutable struct Point x::Float64 y::Float64 end   Base.show(io::IO, p::Point) = print(io, "Point($(p.x), $(p.y))")   getx(p::Point) = p.x gety(p::Point) = p.y   setx(p::Point, x) = (p.x = x) sety(p::Point, y) = (p.y = y)   mutable struct Circle x::Float64 y::Float64 r::Float64 end   getx(c::Circle) = c.x gety(c::Ci...
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,...
#Raku
Raku
use v6;   grammar PokerHand {   # Raku Grammar to parse and rank 5-card poker hands # E.g. PokerHand.parse("2♥ 3♥ 2♦ 3♣ 3♦"); # 2013-12-21: handle 'joker' wildcards; maximum of two   rule TOP { :my %*PLAYED; { %*PLAYED = () } [ <face-card> | <joker> ]**5 }   token face...
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 ...
#Fortran
Fortran
program population_count implicit none   integer, parameter :: i64 = selected_int_kind(18) integer(i64) :: x integer :: i, n   x = 1 write(*, "(a8)", advance = "no") "3**i :" do i = 1, 30 write(*, "(i3)", advance = "no") popcnt(x) x = x * 3 end do   write(*,*) write(*, "(a8)", advance = "no"...
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...
#R
R
polylongdiv <- function(n,d) { gd <- length(d) pv <- vector("numeric", length(n)) pv[1:gd] <- d if ( length(n) >= gd ) { q <- c() while ( length(n) >= gd ) { q <- c(q, n[1]/pv[1]) n <- n - pv * (n[1]/pv[1]) n <- n[2:length(n)] pv <- pv[1:(length(pv)-1)] } list(q=q, r=n) ...
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...
#PARI.2FGP
PARI/GP
polinterpolate([0,1,2,3,4,5,6,7,8,9,10],[1,6,17,34,57,86,121,162,209,262,321])
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...
#Haskell
Haskell
import Data.Set import Control.Monad   powerset :: Ord a => Set a -> Set (Set a) powerset = fromList . fmap fromList . listPowerset . toList   listPowerset :: [a] -> [[a]] listPowerset = filterM (const [True, False])
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 ...
#Delphi
Delphi
function IsPrime(aNumber: Integer): Boolean; var I: Integer; begin Result:= True; if(aNumber = 2) then Exit;   Result:= not ((aNumber mod 2 = 0) or (aNumber <= 1)); if not Result then Exit;   for I:=3 to Trunc(Sqrt(aNumber)) do if(aNumber mod I = 0) then begin Result:= False; Br...
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 ...
#Liberty_BASIC
Liberty BASIC
  dim DR(38) 'decimal range dim PF(38) 'corresponding price fraction range$="0.06 0.11 0.16 0.21 0.26 0.31 0.36 0.41 0.46 0.51 0.56 0.61 0.66 0.71 0.76 0.81 0.86 0.91 0.96 0.01" frac$="0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62 0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00" for i = 1 to 38 DR(i)=val(...
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...
#Phix
Phix
global function factors(atom n, integer include1=0) -- -- returns a list of all integer factors of n -- if include1 is 0 (the default), result does not contain either 1 or n -- if include1 is 1 the result contains 1 and n -- if include1 is -1 the result contains 1 but not n -- if n=0 then return {} end if ...
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...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var letters = ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"] var actual = [0] * 8 var probs = [1/5, 1/6, 1/7, 1/8, 1/9, 1/10, 1/11, 0] var cumProbs = [0] * 8   cumProbs[0] = probs[0] for (i in 1..6) cumProbs[i] = cumProbs[i-1] + probs[i] cumPr...
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...
#PureBasic
PureBasic
Structure taskList List description.s() ;implements FIFO queue EndStructure   Structure task *tl.tList ;pointer to a list of task descriptions Priority.i ;tasks priority, lower value has more priority EndStructure   Structure priorityQueue maxHeapSize.i ;increases as needed heapItemCount.i ;number of eleme...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main() factors := primedecomp(2^43-1) # a big int end   procedure primedecomp(n) #: return a list of factors local F,o,x F := []   every writes(o,n|(x := genfactors(n))) do { \o := "*" /o := "=" put(F,x) # build a list of factors to satisfy the task } write() return F end   link factor...
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....
#MATLAB
MATLAB
>> 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]; >> plot(x,y,'.-')
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....
#Maxima
Maxima
(%i1) ".." (m, n) := makelist (i, i, m, n); infix ("..")$ (%i2) x: 0 .. 9$ y:[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]$ (%i3) plot2d(['discrete, x, y], [style, [points,5,1,1]], [gnuplot_term, png], [gnuplot_out_file, "qsort-range-10-9.png"])$
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
#Kotlin
Kotlin
// version 1.1.2   open class Point(var x: Int, var y: Int) { constructor(): this(0, 0)   constructor(x: Int) : this(x, 0)   constructor(p: Point) : this(p.x, p.y)   open protected fun finalize() = println("Finalizing $this...")   override fun toString() = "Point at ($x, $y)"   open fun print() ...
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,...
#REXX
REXX
/* REXX --------------------------------------------------------------- * 10.12.2013 Walter Pachl *--------------------------------------------------------------------*/   d.1='2h 2d 2s ks qd'; x.1='three-of-a-kind' d.2='2h 5h 7d 8s 9d'; x.2='high-card' d.3='ah 2d 3s 4s 5s'; x.3='straight' d.4='2h 3h 2d 3s 3d'; x.4='fu...
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 ...
#Free_Pascal
Free Pascal
program populationCount(input, output, stdErr); var // general advice: iterator variables are _signed_ iterator: int64; // the variable we’d like to count the set bits in number: qWord; // how many evil numbers we’ve already found evilCount: int64; // odious numbers odiousNumber: array[1..30] of qWord; odiousI...
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...
#Racket
Racket
  #lang racket (define (deg p) (for/fold ([d -inf.0]) ([(pi i) (in-indexed p)]) (if (zero? pi) d i))) (define (lead p) (vector-ref p (deg p))) (define (mono c d) (build-vector (+ d 1) (λ(i) (if (= i d) c 0)))) (define (poly*cx^n c n p) (vector-append (make-vector n 0) (for/vector ([pi p]) (* c pi)))) (define (po...
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...
#Perl
Perl
use strict; use warnings; use Statistics::Regression;   my @x = <0 1 2 3 4 5 6 7 8 9 10>; my @y = <1 6 17 34 57 86 121 162 209 262 321>;   my @model = ('const', 'X', 'X**2');   my $reg = Statistics::Regression->new( '', [@model] ); $reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1; my @coeff = $reg->theta(...
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...
#Icon_and_Unicon
Icon and Unicon
  procedure power_set (s) result := set () if *s = 0 then insert (result, set ()) # empty set else { head := set(?s) # take a random element # and find powerset of remaining part of set tail_pset := power_set (x -- head) result ++:= tail_pset # add powerset of remainder to results ...
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 ...
#E
E
def isPrime(n :int) { if (n == 2) { return true } else if (n <= 1 || n %% 2 == 0) { return false } else { def limit := (n :float64).sqrt().ceil() var divisor := 1 while ((divisor += 2) <= limit) { if (n %% divisor == 0) { return false ...
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 ...
#Lua
Lua
scaleTable = { {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} }   fu...
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...
#PHP
PHP
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } }   assert([1, 2, 4, ...
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...
#XPL0
XPL0
include c:\cxpl\codes; def Size = 10_000_000; int Tbl(12+1); int I, J, N; real X, S0, S1; [for J:= 5 to 12 do Tbl(J):= 0; for I:= 0 to 1_000_000-1 do \generate one million items [N:= Ran(Size); for J:= 5 to 11 do [N:= N - Size/J; if N < 0 then [Tbl(J):...
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...
#Yabasic
Yabasic
dim letters$(7) data "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth" letters$(0) = "aleph" letters$(1) = "beth" letters$(2) = "gimel" letters$(3) = "daleth" letters$(4) = "he" letters$(5) = "waw" letters$(6) = "zayin" letters$(7) = "heth" dim actual(7) dim probs(7) probs(0) = 1/5.0 probs(1) = 1/6.0 pro...
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...
#Python
Python
>>> import queue >>> pq = queue.PriorityQueue() >>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")): pq.put(item)     >>> while not pq.empty(): print(pq.get_nowait())     (1, 'Solve RC tasks') (2, 'Tax return') (3, 'Clear drains') (4, 'Feed cat') (5, 'Ma...
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 ...
#J
J
q:
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....
#Nim
Nim
import gnuplot   let 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]   plot(x, y, "Coordinate pairs") discard stdin.readChar # Needed as when the program exits, “gnuplot” is closed.
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....
#OCaml
OCaml
#load "graphics.cma" open Graphics   let round x = int_of_float (floor(x +. 0.5))   let x = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9] and y = [2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0]   let () = open_graph ""; List.iter2 (fun x y -> (* scale to fit in the window *) let _x = x * 30 an...
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
#Lua
Lua
-- Point local Point = {x = 0, y = 0}   function Point:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end   function Point:print() print("Point(" .. self.x .. ", " .. self.y .. ")") end   function Point:copy() return Point:new{x = self.x, y = self.y} end   -- Circle local ...
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,...
#Ruby
Ruby
class Card include Comparable attr_accessor :ordinal attr_reader :suit, :face   SUITS = %i(♥ ♦ ♣ ♠) FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)   def initialize(str) @face, @suit = parse(str) @ordinal = FACES.index(@face) end   def <=> (other) #used for sorting self.ordinal <=> other.ordinal e...
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 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
  #define NTERMS 30   function popcount( n as ulongint ) as uinteger if n = 0 then return 0 if n = 1 then return 1 if n mod 2 = 0 then return popcount(n/2) return 1 + popcount( (n - 1)/2 ) end function   dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_ odious(0 to NTERM...
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...
#Raku
Raku
sub poly_long_div ( @n is copy, @d ) { return [0], |@n if +@n < +@d;   my @q = gather while +@n >= +@d { @n = @n Z- flat ( ( @d X* take ( @n[0] / @d[0] ) ), 0 xx * ); @n.shift; }   return @q, @n; }   sub xP ( $power ) { $power>1 ?? "x^$power" !! $power==1 ?? 'x' !! '' } sub poly_print ( ...
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...
#Phix
Phix
-- demo\rosetta\Polynomial_regression.exw with javascript_semantics constant x = {0,1,2,3,4,5,6,7,8,9,10}, y = {1,6,17,34,57,86,121,162,209,262,321}, n = length(x) function regression() atom xm = 0, ym = 0, x2m = 0, x3m = 0, x4m = 0, xym = 0, x2ym = 0 for i=1 to n do atom xi = x[i], ...
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...
#J
J
ps =: #~ 2 #:@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 ...
#EchoLisp
EchoLisp
(lib 'sequences)   ;; Try divisors iff n = 2k + 1 (define (is-prime? p) (cond [(< p 2) #f] [(zero? (modulo p 2)) (= p 2)] [else (for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))   (filter is-prime? (range 1 100)) → (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)   ;; 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 ...
#Maple
Maple
priceFraction := proc(price) local values, standard, newPrice, i; values := [0, 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01]; standard := [0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62, 0.66, 0.70, 0.74, 0.78, 0.82, 0.8...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PriceFraction[x_]:=Piecewise[{{.1, 0 <= x < 0.06}, {.18, x < .11}, {.26,x < 0.16}, {.32, x < .21}, {.38, x < .26}, {.44, x < 0.31}, {.5, x < .36}, {.54, x < .41}, {.58, x < .46}, {.62, x < .51}, {.66, x < .56}, {.70, x < .61}, {.74, x < .66}, {.78, x < .71}, {.82, x < .76}, {.86, x < .81}, {.90, x < .86}, {.94, x < ...
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...
#Picat
Picat
go => println(11111=proper_divisors(11111)), nl, foreach(N in 1..10) println(N=proper_divisors(N)) end, nl,   find_most_divisors(20_000), nl.   % Proper divisors of number N proper_divisors(N) = Divisors => Div1 = [ I : I in 1..ceiling(sqrt(N)), N mod I == 0], Divisors = (Div1 ++ [N div I : I in ...
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...
#zkl
zkl
var names=T("aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"); var ptable=T(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0).apply('/.fp(1.0)); ptable=ptable.append(1.0-ptable.sum(0.0)); // add last weight to sum to 1.0 var [const] N=ptable.len();   fcn ridx{ i:=0; s:=(0.0).random(1); while((s-=ptable[i]) >...
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...
#Quackery
Quackery
( ***** priotity queue ***** )   [ stack ] is heap.pq ( --> s )   [ stack ] is comp.pq ( --> s )   [ unpack comp.pq put heap.pq put ] is pq->stacks ( p --> )   [ heap.pq take comp.pq take 2 pack ] is stacks->pq ...
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 ...
#Java
Java
public boolean prime(BigInteger i);
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....
#Octave
Octave
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]; plot(x,y,"o"); pause;
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
#M2000_Interpreter
M2000 Interpreter
  \\ block For This {}, or For object [, object2] { }, where object is a group, or a pointer to group, or an item from an array contains a group \\ This is "this context". For This { \\ any new definition here has a temporary use \\ can be nested, but if we use object then we can use dots to access members of it. If we...
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
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   -- ----------------------------------------------------------------------------- class RCPolymorphism public final   method main(args = String[]) public constant   parry = [Point - Point() ...
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,...
#Rust
Rust
  fn main() { let hands = vec![ "🂡 🂮 🂭 🂫 🂪", "🃏 🃂 🂢 🂮 🃍", "🃏 🂵 🃇 🂨 🃉", "🃏 🃂 🂣 🂤 🂥", "🃏 🂳 🃂 🂣 🃃", "🃏 🂷 🃂 🂣 🃃", "🃏 🂷 🃇 🂧 🃗", "🃏 🂻 🂽 🂾 🂱", "🃏 🃔 🃞 🃅 🂪", "🃏 🃞 🃗 🃖 🃔", "🃏 🃂 🃟 🂤 🂥"...
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 ...
#FreeBASIC
FreeBASIC
  #define NTERMS 30   function popcount( n as ulongint ) as uinteger if n = 0 then return 0 if n = 1 then return 1 if n mod 2 = 0 then return popcount(n/2) return 1 + popcount( (n - 1)/2 ) end function   dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_ odious(0 to NTERM...
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...
#REXX
REXX
/* REXX needed by some... */ z='1 -12 0 -42' /* Numerator */ n='1 -3' /* Denominator */ zx=z nx=n copies('0 ',words(z)-words(n)) qx='' /* Quotient */ Do Until words(zx)<words(n) Parse Value div(zx,nx) With q zx qx=qx q nx=subword(nx,1,words(nx)-1) End Say '('show(z)')/('show(n)')=('show...
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...
#PowerShell
PowerShell
  function qr([double[][]]$A) { $m,$n = $A.count, $A[0].count $pm,$pn = ($m-1), ($n-1) [double[][]]$Q = 0..($m-1) | foreach{$row = @(0) * $m; $row[$_] = 1; ,$row} [double[][]]$R = $A | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})} foreach ($h in 0..$pn) { [double[]]$u = $R[$h..$pm] | ...
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...
#Java
Java
public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps) { if(n<0) { return null; } if(n==0) { if(ps==null) ps=new ArrayList<String>(); ps.add(" "); return ps; } ps=getpower...
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 ...
#Eiffel
Eiffel
class APPLICATION   create make   feature   make -- Tests the feature is_prime. do io.put_boolean (is_prime (1)) io.new_line io.put_boolean (is_prime (2)) io.new_line io.put_boolean (is_prime (3)) io.new_line io.put_boolean (is_prime (4)) io.new_line io.put_boolean (is_pr...
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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function y = rescale(x)   L = [0,.06:.05:1.02]; V = [.1,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.9,.94,.98,1];   y = x; for k=1:numel(x); y(k) = V(sum(L<=x(k))); end; end;   t=0:0.001:1; plot(t,rescale(t));
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 ...
#Mercury
Mercury
:- module price. :- interface. :- import_module int. :- type price == int. :- func standard(price) = price.   :- implementation. :- import_module require, list.   standard(P) = SP :- require(P >= 0, "P must be positive"), Cents = P `mod` 100, P + adjust(Cents) = SP.   :- func adjust(int) = int. ...
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...
#PicoLisp
PicoLisp
# Generate all proper divisors. (de propdiv (N) (head -1 (filter '((X) (=0 (% N X))) (range 1 N) )) )   # Obtaining the values from 1 to 10 inclusive. (mapcar propdiv (range 1 10)) # Output: # (NIL (1) (1) (1 2) (1) (1 2 3) (1) (1 2 4) (1 3) (1 2 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...
#R
R
PriorityQueue <- function() { keys <- values <- NULL insert <- function(key, value) { ord <- findInterval(key, keys) keys <<- append(keys, key, ord) values <<- append(values, value, ord) } pop <- function() { head <- list(key=keys[1],value=values[[1]]) values <<- values[-1] keys <<- keys...
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 ...
#JavaScript
JavaScript
function run_factorize(input, output) { var n = new BigInteger(input.value, 10); var TWO = new BigInteger("2", 10); var divisor = new BigInteger("3", 10); var prod = false;   if (n.compareTo(TWO) < 0) return;   output.value = "";   while (true) { var qr = n.divideAndRemaind...
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....
#Ol
Ol
  ; define input arrays (define x '(0 1 2 3 4 5 6 7 8 9)) (define y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0))   ; render (import (lib gl2)) (glOrtho 0 10 0 200 0 1)   (gl:set-renderer (lambda (mouse) (glClear GL_COLOR_BUFFER_BIT) (glColor3f 0 1 0) (glBegin GL_LINE_STRIP) (map glVertex2f 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
#Nim
Nim
type Point = object x, y: float   Circle = object center: Point radius: float   # Constructors proc createPoint(x, y = 0.0): Point = result.x = x result.y = y   proc createCircle(x, y = 0.0, radius = 1.0): Circle = result.center.x = x result.center.y = y result.radius = radius   var p1 = creat...
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
#Objeck
Objeck
  bundle Default { class Point { @x : Int; @y : Int;   New() { @x := 0; @y := 0; }   New(x : Int, y : Int) { @x := x; @y := y; }   New(p : Point) { @x := p->GetX(); @y := p->GetY(); }   method : public : GetX() ~ Int { return @x; }...
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,...
#Scala
Scala
val faces = "23456789TJQKA" val suits = "CHSD" sealed trait Card object Joker extends Card case class RealCard(face: Int, suit: Char) extends Card val allRealCards = for { face <- 0 until faces.size suit <- suits } yield RealCard(face, suit)   def parseCard(str: String): Card = { if (str == "joker") { Joker ...
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 ...
#Gambas
Gambas
Public Sub Main() Dim sEvil, sOdious As String 'To store the output for printing Evil and Odious Dim iCount, iEvil, iOdious As Integer 'Counters   Print "First 30 numbers ^3\t"; 'Print title   For iCount = 0 To 29 'Count 30 ti...
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...
#Ruby
Ruby
def polynomial_long_division(numerator, denominator) dd = degree(denominator) raise ArgumentError, "denominator is zero" if dd < 0 if dd == 0 return [multiply(numerator, 1.0/denominator[0]), [0]*numerator.length] end   q = [0] * numerator.length   while (dn = degree(numerator)) >= dd d = shift_right...
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...
#Python
Python
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] >>> coeffs = numpy.polyfit(x,y,deg=2) >>> coeffs array([ 3., 2., 1.])
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...
#JavaScript
JavaScript
function powerset(ary) { var ps = [[]]; for (var i=0; i < ary.length; i++) { for (var j = 0, len = ps.length; j < len; j++) { ps.push(ps[j].concat(ary[i])); } } return ps; }   var res = powerset([1,2,3,4]);   load('json2.js'); print(JSON.stringify(res));
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 ...
#Elixir
Elixir
defmodule RC do def is_prime(2), do: true def is_prime(n) when n<2 or rem(n,2)==0, do: false def is_prime(n), do: is_prime(n,3)   def is_prime(n,k) when n<k*k, do: true def is_prime(n,k) when rem(n,k)==0, do: false def is_prime(n,k), do: is_prime(n,k+2) end   IO.inspect for n <- 1..50, RC.is_prime(n), do: n
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 ...
#MUMPS
MUMPS
PRICFRAC(X)  ;Outputs a specified value dependent upon the input value  ;The non-inclusive upper limits are encoded in the PFMAX string, and the values  ;to convert to are encoded in the PFRES string. NEW PFMAX,PFRES,I,RESULT SET PFMAX=".06^.11^.16^.21^.26^.31^.36^.41^.46^.51^.56^.61^.66^.71^.76^.81^.86^.91^.96^1.01"...
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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ----------------------------------------------------------------------------- method runSample(arg) public static parse arg in_val . if in_val \= '' then test_vals = [in_val] else test_vals = ...
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...
#PL.2FI
PL/I
*process source xref; (subrg): cpd: Proc Options(main); p9a=time(); Dcl (p9a,p9b) Pic'(9)9'; Dcl cnt(3) Bin Fixed(31) Init((3)0); Dcl x Bin Fixed(31); Dcl pd(300) Bin Fixed(31); Dcl sumpd Bin Fixed(31); Dcl npd Bin Fixed(31); Dcl hi Bin Fixed(31) Init(0); Dcl (xl(10),xi) Bin Fixed(31); Dcl i ...
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...
#Racket
Racket
  #lang racket (require data/heap)   (define pq (make-heap (λ(x y) (<= (second x) (second y)))))   (define (insert! x pri) (heap-add! pq (list pri x)))   (define (remove-min!) (begin0 (first (heap-min pq)) (heap-remove-min! pq)))   (insert! 3 "Clear drains") (insert! 4 "Feed cat") (insert! 5 "Make tea") (...
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 ...
#jq
jq
def factors: . as $in | [2, $in, false] | recurse( . as [$p, $q, $valid, $s] | if $q == 1 then empty elif $q % $p == 0 then [$p, $q/$p, true] elif $p == 2 then [3, $q, false, $s] else ($s // ($q | sqrt)) as $s | if $p + 2 <= $s then [$p + 2, $q, false, $s] ...