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
#D
D
import std.stdio: writeln;   class Point { private int x, y; this(int x_=0, int y_=0) { x = x_; y = y_; } this(Point p_) { x = p_.getX(); y = p_.getY(); } int getX() { return x; } void setX(int x_) { this.x = x_; } int getY() { return y; } void setY(int y_) { this.y = y_; } }   class Circle : Point { private int r; this(int x_=0, int y_=0, int r_=0) { super(x_, y_); r = r_; } this(Point p, int r_=0) { super(p); r = r_; } this(Circle c_) { super(c_.getX(), c_.getY()); r = c_.getR(); } int getR() { return r; } void setR(int r0) { this.r = r0; } }   void main() { auto p = new Point(); auto c = new Circle(); writeln(p); writeln(c); }
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#Go
Go
package main   import ( "fmt" "sort" "strings" )   type card struct { face byte suit byte }   const faces = "23456789tjqka" const suits = "shdc"   func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted[i].face < sorted[j].face }) if sorted[0].face+4 == sorted[4].face { return true } if sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5 { return true } return false }   func isFlush(cards []card) bool { suit := cards[0].suit for i := 1; i < 5; i++ { if cards[i].suit != suit { return false } } return true }   func analyzeHand(hand string) string { temp := strings.Fields(strings.ToLower(hand)) splitSet := make(map[string]bool) var split []string for _, s := range temp { if !splitSet[s] { splitSet[s] = true split = append(split, s) } } if len(split) != 5 { return "invalid" } var cards []card   for _, s := range split { if len(s) != 2 { return "invalid" } fIndex := strings.IndexByte(faces, s[0]) if fIndex == -1 { return "invalid" } sIndex := strings.IndexByte(suits, s[1]) if sIndex == -1 { return "invalid" } cards = append(cards, card{byte(fIndex + 2), s[1]}) }   groups := make(map[byte][]card) for _, c := range cards { groups[c.face] = append(groups[c.face], c) }   switch len(groups) { case 2: for _, group := range groups { if len(group) == 4 { return "four-of-a-kind" } } return "full-house" case 3: for _, group := range groups { if len(group) == 3 { return "three-of-a-kind" } } return "two-pair" case 4: return "one-pair" default: flush := isFlush(cards) straight := isStraight(cards) switch { case flush && straight: return "straight-flush" case flush: return "flush" case straight: return "straight" default: return "high-card" } } }   func main() { hands := [...]string{ "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", "ah ah 7c 6c 4c", } for _, hand := range hands { fmt.Printf("%s: %s\n", hand, analyzeHand(hand)) } }
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#C
C
#include <stdio.h>   int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { // __builtin_popcount() for unsigned int // __builtin_popcountl() for unsigned long // __builtin_popcountll() for unsigned long long printf("%d ", __builtin_popcountll(n)); n *= 3; } printf("\n"); }   int od[30]; int ne = 0, no = 0; printf("evil  : "); for (int n = 0; ne+no < 60; n++) { if ((__builtin_popcount(n) & 1) == 0) { if (ne < 30) { printf("%d ", n); ne++; } } else { if (no < 30) { od[no++] = n; } } } printf("\n"); printf("odious: "); for (int i = 0; i < 30; i++) { printf("%d ", od[i]); } printf("\n");   return 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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#Fortran
Fortran
module Polynom implicit none   contains   subroutine poly_long_div(n, d, q, r) real, dimension(:), intent(in) :: n, d real, dimension(:), intent(out), allocatable :: q real, dimension(:), intent(out), allocatable, optional :: r   real, dimension(:), allocatable :: nt, dt, rt integer :: gn, gt, gd   if ( (size(n) >= size(d)) .and. (size(d) > 0) .and. (size(n) > 0) ) then allocate(nt(size(n)), dt(size(n)), rt(size(n)))   nt = n dt = 0 dt(1:size(d)) = d rt = 0 gn = size(n)-1 gd = size(d)-1 gt = 0   do while ( d(gd+1) == 0 ) gd = gd - 1 end do   do while( gn >= gd ) dt = eoshift(dt, -(gn-gd)) rt(gn-gd+1) = nt(gn+1) / dt(gn+1) nt = nt - dt * rt(gn-gd+1) gt = max(gt, gn-gd) do gn = gn - 1 if ( nt(gn+1) /= 0 ) exit end do dt = 0 dt(1:size(d)) = d end do   allocate(q(gt+1)) q = rt(1:gt+1) if ( present(r) ) then if ( (gn+1) > 0 ) then allocate(r(gn+1)) r = nt(1:gn+1) else allocate(r(1)) r = 0.0 end if end if deallocate(nt, dt, rt) else allocate(q(1)) q = 0 if ( present(r) ) then allocate(r(size(n))) r = n end if end if   end subroutine poly_long_div   subroutine poly_print(p) real, dimension(:), intent(in) :: p   integer :: i   do i = size(p), 1, -1 if ( i > 1 ) then write(*, '(F0.2,"x^",I0," + ")', advance="no") p(i), i-1 else write(*, '(F0.2)') p(i) end if end do   end subroutine poly_print   end module Polynom
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#Kotlin
Kotlin
// version 1.1.2   open class Animal(val name: String, var age: Int) { open fun copy() = Animal(name, age)   override fun toString() = "Name: $name, Age: $age" }   class Dog(name: String, age: Int, val breed: String) : Animal(name, age) { override fun copy() = Dog(name, age, breed)   override fun toString() = super.toString() + ", Breed: $breed" }   fun main(args: Array<String>) { val a: Animal = Dog("Rover", 3, "Terrier") val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog println("Dog 'a' = $a") // implicitly calls Dog.toString() println("Dog 'b' = $b") // ditto println("Dog 'a' is ${if (a === b) "" else "not"} the same object as Dog 'b'") }
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#Lua
Lua
T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }   function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end S1 = clone(T) S1.name=function(s) return "S1" end   function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end S2 = merge(clone(T), {name=function(s) return "S2" end})   function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end S3 = prototype(T, {name=function(s) return "S3" end})   print("T : "..T:tostring()) print("S1: " ..S1:tostring()) print("S2: " ..S2:tostring()) print("S3: " ..S3:tostring()) print("S3's parent: "..S3.prototype:tostring())
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   var Radians = Fn.new { |d| d * Num.pi / 180 }   class Polyspiral { construct new(width, height) { Window.title = "Polyspiral" Window.resize(width, height) Canvas.resize(width, height) _w = width _h = height _inc = 0 }   init() { drawSpiral(5, Radians.call(_inc)) }   drawSpiral(length, angleIncrement) { Canvas.cls(Color.white) var x1 = _w / 2 var y1 = _h / 2 var len = length var angle = angleIncrement for (i in 0...150) { var col = Color.hsv(i / 150 * 360, 1, 1) var x2 = x1 + Math.cos(angle) * len var y2 = y1 - Math.sin(angle) * len Canvas.line(x1.truncate, y1.truncate, x2.truncate, y2.truncate, col) x1 = x2 y1 = y2 len = len + 3 angle = (angle + angleIncrement) % (Num.pi * 2) } }   update() { _inc = (_inc + 0.05) % 360 }   draw(alpha) { drawSpiral(5, Radians.call(_inc)) } }   var Game = Polyspiral.new(640, 640)
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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Haskell
Haskell
import Data.List import Data.Array import Control.Monad import Control.Arrow import Matrix.LU   ppoly p x = map (x**) p   polyfit d ry = elems $ solve mat vec where mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d] vec = listArray (1,d) $ take d ry
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#Common_Lisp
Common Lisp
(defun powerset (s) (if s (mapcan (lambda (x) (list (cons (car s) x) x)) (powerset (cdr s))) '(())))
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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Befunge
Befunge
&>:48*:** \1`!#^_2v v_v#`\*:%*:*84\/*:*84::+< v >::48*:*/\48*:*%%!#v_1^ >0"seY" >:#,_@#: "No">#0<
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Factor
Factor
CONSTANT: dispensary-data { { 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 } }   : price-fraction ( n -- n ) dispensary-data [ first over >= ] find 2nip second ;   { 0 0.5 0.65 0.66 1 } [ price-fraction ] map
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Fantom
Fantom
  class Defn // to hold the three numbers from a 'row' in the table { Float low Float high Float value new make (Float low, Float high, Float value) { this.low = low this.high = high this.value = value } }   class PriceConverter { Defn[] defns := [,] new make (Str table) // process given table and store numbers from each row in a defn { table.split('\n').each |Str line| { data := line.split defns.add (Defn(Float.fromStr(data[1]), Float.fromStr(data[3]), Float.fromStr(data[5]))) } }   public Float convert (Float price) // convert by looking through list of defns { Float result := price defns.each |Defn defn| { if (price >= defn.low && price < defn.high) result = defn.value } return result } }   class Main { public static Void main () { table := ">= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00" converter := PriceConverter (table) 10.times // simple test with random values { price := (0..100).random.toFloat / 100 echo ("$price -> ${converter.convert (price)}") } } }  
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#Java
Java
import java.util.Collections; import java.util.LinkedList; import java.util.List;   public class Proper{ public static List<Integer> properDivs(int n){ List<Integer> divs = new LinkedList<Integer>(); if(n == 1) return divs; divs.add(1); for(int x = 2; x < n; x++){ if(n % x == 0) divs.add(x); }   Collections.sort(divs);   return divs; }   public static void main(String[] args){ for(int x = 1; x <= 10; x++){ System.out.println(x + ": " + properDivs(x)); }   int x = 0, count = 0; for(int n = 1; n <= 20000; n++){ if(properDivs(n).size() > count){ x = n; count = properDivs(n).size(); } } System.out.println(x + ": " + count); } }
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 involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Probabilistic_choice by Galileo, 05/2022 #/   include ..\Utilitys.pmt   ( ( "aleph" 0.200000 0 ) ( "beth" 0.166667 0 ) ( "gimel" 0.142857 0 ) ( "daleth" 0.125000 0 ) ( "he" 0.111111 0 ) ( "waw" 0.100000 0 ) ( "zayin" 0.090909 0 ) ( "heth" 0.063456 0 ) ) len 1 swap 2 tolist var lprob   1000000 var trial   trial for drop rand >ps 0 >ps lprob for var i ( i 2 ) sget ps> + tps swap dup >ps < if ( i 3 ) sget 1 + ( i 3 ) sset exitfor endif endfor ps> ps> drop drop endfor   ( "item" "\t" "actual" "\t\t" "theoretical" ) lprint nl nl lprob for drop pop swap 1 get "\t" rot 3 get trial / "\t" rot 2 get nip "\n" 6 tolist lprint endfor
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 involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#PicoLisp
PicoLisp
(let (Count 1000000 Denom 27720 N Denom) (let Probs (mapcar '((I S) (prog1 (cons N (*/ Count I) 0 S) (dec 'N (/ Denom I)) ) ) (range 5 12) '(aleph beth gimel daleth he waw zayin heth) ) (do Count (inc (cddr (rank (rand 1 Denom) Probs T))) ) (let Fmt (-6 12 12) (tab Fmt NIL "Probability" "Result") (for X Probs (tab Fmt (cdddr X) (format (cadr X) 6) (format (caddr X) 6) ) ) ) ) )
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#M2000_Interpreter
M2000 Interpreter
  Module UnOrderedArray { Class PriorityQueue { Private: Dim Item() many=0, level=0, first cmp = lambda->0 Module Reduce { if .many<.first*2 then exit If .level<.many/2 then .many/=2 : Dim .Item(.many) } Public: Module Clear { Dim .Item() \\ erase all .many<=0 \\ default .Level<=0 } Module PriorityQueue { If .many>0 then Error "Clear List First" Read .many, .cmp .first<=.many Dim .Item(.many) } Module Add { If .level=.many Then { If .many=0 then Error "Define Size First" Dim .Item(.many*2) .many*=2 } Read Item If .level=0 Then { .Item(0)=Item } Else.if .cmp(.Item(0), Item)=-1 Then { \\ Item is max .Item(.level)=Item swap .Item(0), .Item(.level) } Else .Item(.level)=Item .level++ } Function Peek { If .level=0 Then error "empty" =.Item(0) } Function Poll { If .level=0 Then error "empty" =.Item(0) If .level=2 Then { swap .Item(0), .Item(1) .Item(1)=0 .Level<=1 } Else.If .level>2 Then { .Level-- Swap .Item(.level), .Item(0) .Item(.level)=0 For I=.level-1 to 1 { If .cmp(.Item(I), .Item(I-1))=1 Then Swap .Item(I), .Item(I-1) } } else .level<=0 : .Item(0)=0 .Reduce } Module Remove { If .level=0 Then error "empty" Read Item k=true If .cmp(.Item(0), Item)=0 Then { Item=.Poll() K~ \\ k=false } Else.If .Level>1 Then { I2=.Level-1 For I=1 to I2 { If k Then { If .cmp(.Item(I), Item)=0 Then { If I<I2 Then Swap .Item(I), .Item(I2) .Item(I2)=0 k=false } } else exit } .Level-- } If k Then Error "Not Found" .Reduce } Function Size { If .many=0 then Error "Define Size First" =.Level } }   Class Item { X, S$ Module Item { Read .X, .S$} } Function PrintTop { M=Queue.Peek() : Print "Item ";M.X, M.S$ } Comp=Lambda -> { Read A,B : =COMPARE(A.X,B.X)}   Queue=PriorityQueue(100,Comp) Queue.Add Item(3, "Clear drains") Call Local PrintTop() Queue.Add Item(4 ,"Feed cat") Call Local PrintTop() Queue.Add Item(5 ,"Make tea") Call Local PrintTop() Queue.Add Item(1 ,"Solve RC tasks") Call Local PrintTop() Queue.Add Item(2 ,"Tax return") Call Local PrintTop() Print "remove items" While true { MM=Queue.Poll() Print MM.X, MM.S$ Print "Size="; Queue.Size() If Queue.Size()=0 Then exit Call Local PrintTop() } } UnOrderedArray  
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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Swift
Swift
var total = 0 var prim = 0 var maxPeri = 100   func newTri(s0:Int, _ s1:Int, _ s2: Int) -> () {   let p = s0 + s1 + s2 if p <= maxPeri { prim += 1 total += maxPeri / p newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2) newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+s1+s2) + s2) newTri(-s0 + 2*( s1+s2), 2*(-s0+s2) + s1, 2*(-s0+s1+s2) + s2) } }   while maxPeri <= 100_000_000 { prim = 0 total = 0 newTri(3, 4, 5) print("Up to \(maxPeri) : \(total) triples \( prim) primitives.") maxPeri *= 10 }
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#SSEM
SSEM
00000000000000110000000000000000 Test 00000000000001110000000000000000 Stop
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Standard_ML
Standard ML
if problem then OS.Process.exit OS.Process.failure (* valid status codes include OS.Process.success and OS.Process.failure *) else ()
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Tcl
Tcl
if {$problem} { # Print a “friendly” message... puts stderr "some problem occurred" # Indicate to the caller of the program that there was a problem exit 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
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP fcn isWilsonPrime(p){ if(p<=1 or (p%2==0 and p!=2)) return(False); BI(p-1).factorial().add(1).mod(p) == 0 } fcn wPrimesW{ [2..].tweak(fcn(n){ isWilsonPrime(n) and n or Void.Skip }) }
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 the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#zkl
zkl
const CNT =0d1_000_000; sieve  :=Import("sieve.zkl",False,False,False).postponed_sieve; conspiracy:=Dictionary(); Utils.Generator(sieve).reduce(CNT,'wrap(digit,p){ d:=p%10; conspiracy.incV("%d → %d count:".fmt(digit,d)); d }); foreach key in (conspiracy.keys.sort()){ v:=conspiracy[key].toFloat(); println("%s%,6d\tfrequency: %2.2F%".fmt(key,v,v/CNT *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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Ela
Ela
open integer //arbitrary sized integers   decompose_prime n = loop n 2I where loop c p | c < (p * p) = [c] | c % p == 0I = p :: (loop (c / p) p) | else = loop c (p + 1I)   decompose_prime 600851475143I
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#Lua
Lua
local table1 = {1,2,3} local table2 = table1 table2[3] = 4 print(unpack(table1))
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#M2000_Interpreter
M2000 Interpreter
  A=10 Module Beta { Read &X X++ } Beta &A Print A=11  
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#Modula-3
Modula-3
TYPE IntRef = REF INTEGER;   VAR intref := NEW(IntRef);   intref^ := 10
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Erlang
Erlang
  -module( plot_coordinate_pairs ).   -export( [task/0, to_png_file/3] ).   task() -> Xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], Ys = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0], File = "plot_coordinate_pairs", to_png_file( File, Xs, Ys ).   to_png_file( File, Xs, Ys ) -> PNG = egd_chart:graph( [{File, lists:zip(Xs, Ys)}] ), file:write_file( File ++ ".png", 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
#Delphi
Delphi
type { TPoint }   TMyPoint = class private FX: Integer; FY: Integer; public constructor Create; overload; constructor Create(X0: Integer; Y0: Integer); overload; constructor Create(MyPoint: TMyPoint); overload; destructor Destroy; override;   procedure Print; virtual;   property X: Integer read FX write FX; property Y: Integer read FY write FY; end;   { TCircle }   TCircle = class(TMyPoint) private FR: Integer; public constructor Create(X0: Integer; Y0: Integer; R0: Integer); overload; constructor Create(MyPoint: TMyPoint; R0: Integer); overload; constructor Create(Circle: TCircle); overload; destructor Destroy; override;   procedure Print; override;   property R: Integer read FR write FR; end;   implementation   uses Dialogs;   { TCircle }   constructor TCircle.Create(X0: Integer; Y0: Integer; R0: Integer); begin inherited Create(X0, Y0); FR := R0; end;   constructor TCircle.Create(MyPoint: TMyPoint; R0: Integer); begin inherited Create(MyPoint); FR := R0; end;   constructor TCircle.Create(Circle: TCircle); begin Create; if not(Circle = Self) then begin FX := Circle.X; FY := Circle.Y; FR := Circle.R; end; end;   destructor TCircle.Destroy; begin inherited Destroy; end;   procedure TCircle.Print; begin ShowMessage('Circle'); end;   { TMyPoint }   constructor TMyPoint.Create; begin inherited Create; end;   constructor TMyPoint.Create(X0: Integer; Y0: Integer); begin Create; FX := X0; FY := Y0; end;   constructor TMyPoint.Create(MyPoint: TMyPoint); begin Create; if not(MyPoint = Self) then begin FX := MyPoint.X; FY := MyPoint.Y; end; end;   destructor TMyPoint.Destroy; begin inherited Destroy; end;   procedure TMyPoint.Print; begin ShowMessage('MyPoint'); end;
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#Haskell
Haskell
{-# LANGUAGE TupleSections #-}   import Data.Function (on) import Data.List (group, nub, any, sort, sortBy) import Data.Maybe (mapMaybe) import Text.Read (readMaybe)   data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)   data Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Show, Eq, Enum, Ord, Bounded)   data Card = Card { suit :: Suit, rank :: Rank } deriving (Show, Eq)   type Hand = [Card]   consumed = pure . (, "")   instance Read Suit where readsPrec d s = case s of "♥" -> consumed Heart "♦" -> consumed Diamond "♣" -> consumed Spade "♠" -> consumed Club "h" -> consumed Heart _ -> []   instance Read Rank where readsPrec d s = case s of "a" -> consumed Ace "2" -> consumed Two "3" -> consumed Three "4" -> consumed Four "5" -> consumed Five "6" -> consumed Six "7" -> consumed Seven "8" -> consumed Eight "9" -> consumed Nine "10" -> consumed Ten "j" -> consumed Jack "q" -> consumed Queen "k" -> consumed King _ -> []   instance Read Card where readsPrec d = fmap (, "") . mapMaybe card . lex where card (r, s) = Card <$> (readMaybe s :: Maybe Suit) <*> (readMaybe r :: Maybe Rank)   -- Special hand acesHigh :: [Rank] acesHigh = [Ace, Ten, Jack, Queen, King]   isSucc :: (Enum a, Eq a, Bounded a) => [a] -> Bool isSucc [] = True isSucc [x] = True isSucc (x:y:zs) = (x /= maxBound && y == succ x) && isSucc (y:zs)   nameHand :: Hand -> String nameHand [] = "Invalid Input" nameHand cards | invalidHand = "Invalid hand" | straight && flush = "Straight flush" | ofKind 4 = "Four of a kind" | ofKind 3 && ofKind 2 = "Full house" | flush = "Flush" | straight = "Straight" | ofKind 3 = "Three of a kind" | uniqRanks == 3 = "Two pair" | uniqRanks == 4 = "One pair" | otherwise = "High card" where sortedRank = sort $ rank <$> cards rankCounts = sortBy (compare `on` snd) $ (,) <$> head <*> length <$> group sortedRank uniqRanks = length rankCounts ofKind n = any ((==n) . snd) rankCounts straight = isSucc sortedRank || sortedRank == acesHigh flush = length (nub $ suit <$> cards) == 1 invalidHand = length (nub cards) /= 5   testHands :: [(String, Hand)] testHands = (,) <$> id <*> mapMaybe readMaybe . words <$> [ "2♥ 2♦ 2♣ k♣ q♦" , "2♥ 5♥ 7♦ 8♣ 9♠" , "a♥ 2♦ 3♣ 4♣ 5♦" , "2♥ 3♥ 2♦ 3♣ 3♦" , "2♥ 7♥ 2♦ 3♣ 3♦" , "2♥ 7♥ 7♦ 7♣ 7♠" , "10♥ j♥ q♥ k♥ a♥" , "4♥ 4♠ k♠ 5♦ 10♠" , "q♣ 10♣ 7♣ 6♣ 4♣" , "q♣ 10♣ 7♣ 6♣ 7♣" -- duplicate cards , "Bad input" ]   main :: IO () main = mapM_ (putStrLn . (fst <> const ": " <> nameHand . snd)) testHands
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#C.23
C#
  using System; using System.Linq;   namespace PopulationCount { class Program { private static int PopulationCount(long n) { string binaryn = Convert.ToString(n, 2); return binaryn.ToCharArray().Where(t => t == '1').Count(); }   static void Main(string[] args) { Console.WriteLine("Population Counts:"); Console.Write("3^n : ");   int count = 0;   while (count < 30) { double n = Math.Pow(3f, (double)count); int popCount = PopulationCount((long)n); Console.Write(string.Format("{0} ", popCount)); count++; }   Console.WriteLine(); Console.Write("Evil: ");   count = 0; int i = 0;   while (count < 30) { int popCount = PopulationCount(i);   if (popCount % 2 == 0) { count++; Console.Write(string.Format("{0} ", i)); }   i++; }   Console.WriteLine(); Console.Write("Odious: ");   count = 0; i = 0;   while (count < 30) { int popCount = PopulationCount(i);   if (popCount % 2 != 0) { count++; Console.Write(string.Format("{0} ", i)); }   i++; }   Console.ReadKey(); } } }  
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#FreeBASIC
FreeBASIC
#define EPS 1.0e-20   type polyterm degree as uinteger coeff as double end type   sub poly_print( P() as double ) dim as string outstr = "", sri for i as integer = ubound(P) to 0 step -1 if outstr<>"" then if P(i)>0 then outstr = outstr + " + " if P(i)<0 then outstr = outstr + " - " end if if P(i)=0 then continue for if abs(P(i))<>1 or i=0 then if outstr="" then outstr = outstr + str((P(i))) else outstr = outstr + str(abs(P(i))) end if end if if i>0 then outstr=outstr+"x" sri= str(i) if i>1 then outstr=outstr + "^" + sri next i print outstr end sub   function lc_deg( B() as double ) as polyterm 'gets the coefficent and degree of the leading term in a polynomial dim as polyterm ret for i as uinteger = ubound(B) to 0 step -1 if B(i)<>0 then ret.degree = i ret.coeff = B(i) return ret end if next i return ret end function   sub poly_multiply( byval k as polyterm, P() as double ) 'in-place multiplication of polynomial by a polynomial term dim i as integer for i = ubound(P) to k.degree step -1 P(i) = k.coeff*P(i-k.degree) next i for i = k.degree-1 to 0 step -1 P(i)=0 next i end sub   sub poly_subtract( P() as double, Q() as double ) 'in place subtraction of one polynomial from another dim as uinteger deg = ubound(P) for i as uinteger = 0 to deg P(i) -= Q(i) if abs(P(i))<EPS then P(i)=0 'stupid floating point subtraction, grumble grumble next i end sub   sub poly_add( P() as double, byval t as polyterm ) 'in-place addition of a polynomial term to a polynomial P(t.degree) += t.coeff end sub   sub poly_copy( source() as double, target() as double ) for i as uinteger = 0 to ubound(source) target(i) = source(i) next i end sub   sub polydiv( A() as double, B() as double, Q() as double, R() as double ) dim as polyterm s dim as double sB(0 to ubound(B)) poly_copy A(), R() dim as uinteger d = ubound(B), degr = lc_deg(R()).degree dim as double c = lc_deg(B()).coeff while degr >= d s.coeff = lc_deg(R()).coeff/c s.degree = degr - d poly_add Q(), s poly_copy B(), sB() redim preserve sB(0 to s.degree+ubound(sB)) as double poly_multiply s, sB() poly_subtract R(), sB() degr = lc_deg(R()).degree redim sB(0 to ubound(B)) wend end sub   dim as double N(0 to 4) = {-42, 0, -12, 1} 'x^3 - 12x^2 - 42 dim as double D(0 to 2) = {-3, 1} ' x - 3 dim as double Q(0 to ubound(N)), R(0 to ubound(N))   polydiv( N(), D(), Q(), R() )   poly_print Q() 'quotient poly_print R() 'remainder
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#MiniScript
MiniScript
T = {} T.foo = function() return "This is an instance of T" end function   S = new T S.foo = function() return "This is an S for sure" end function   instance = new S print "instance.foo: " + instance.foo   copy = {} copy = copy + instance // copies all elements print "copy.foo: " + copy.foo   // And to prove this is a copy, and not a reference: instance.bar = 1 copy.bar = 2 print "instance.bar: " + instance.bar print "copy.bar: " + copy.bar
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   -- ----------------------------------------------------------------------------- class RCPolymorphicCopy public   method copier(x = T) public static returns T return x.copy   method main(args = String[]) public constant obj1 = T() obj2 = S() System.out.println(copier(obj1).name) -- prints "T" System.out.println(copier(obj2).name) -- prints "S" return   -- ----------------------------------------------------------------------------- class RCPolymorphicCopy.T public implements Cloneable   method name returns String return T.class.getSimpleName   method copy public returns T dup = T   do dup = T super.clone catch ex = CloneNotSupportedException ex.printStackTrace end   return dup   -- ----------------------------------------------------------------------------- class RCPolymorphicCopy.S public extends RCPolymorphicCopy.T   method name returns String return S.class.getSimpleName  
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#XPL0
XPL0
  def Width=640., Height=480.; def Deg2Rad = 3.141592654/180.; real Incr, Angle, Length, X, Y, X1, Y1; int N; [SetVid($101); \VESA 640x480x8 graphics Incr:= 0.; repeat Incr:= Incr+1.; X:= Width/2.; Y:= Height/2.; Move(fix(X), fix(Y)); Length:= 5.; Angle:= Incr; for N:= 1 to 150 do [X1:= X + Length*Cos(Angle*Deg2Rad); Y1:= Y + Length*Sin(Angle*Deg2Rad); Line(fix(X1), fix(Y1), N+16); X:= X1; Y:= Y1; Length:= Length+3.; Angle:= Angle+Incr; ]; DelayUS(83_333); Clear; until KeyHit; ]
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#Yabasic
Yabasic
w = 1024 : h = 600 open window w, h color 255,0,0   incr = 0 : twopi = 2 * pi   while true incr = mod(incr + 0.05, twopi) x1 = w / 2 y1 = h / 2 length = 5 angle = incr   clear window   for i = 1 to 151 x2 = x1 + cos(angle) * length y2 = y1 + sin(angle) * length line x1, y1, x2, y2 x1 = x2 : y1 = y2 length = length + 3 angle = mod(angle + incr, twopi) next pause 1 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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#HicEst
HicEst
REAL :: n=10, x(n), y(n), m=3, p(m)   x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) y = (1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)   p = 2 ! initial guess for the polynom's coefficients   SOLVE(NUL=Theory()-y(nr), Unknown=p, DataIdx=nr, Iters=iterations)   WRITE(ClipBoard, Name) p, iterations   FUNCTION Theory() ! called by the solver of the SOLVE function. All variables are global Theory = p(1)*x(nr)^2 + p(2)*x(nr) + p(3) END
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#D
D
import std.algorithm; import std.range;   auto powerSet(R)(R r) { return (1L<<r.length) .iota .map!(i => r.enumerate .filter!(t => (1<<t[0]) & i) .map!(t => t[1]) ); }   unittest { int[] emptyArr; assert(emptyArr.powerSet.equal!equal([emptyArr])); assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]])); }   void main(string[] args) { import std.stdio; args[1..$].powerSet.each!writeln; }
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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Bracmat
Bracmat
( prime = incs n I inc . 4 2 4 2 4 6 2 6:?incs & 2:?n & 1 2 2 !incs:?I & whl ' ( !n*!n:~>!arg & div$(!arg.!n)*!n:~!arg & (!I:%?inc ?I|!incs:%?inc ?I) & !n+!inc:?n ) & !n*!n:>!arg ) & 100000000000:?p & whl ' ( !p+1:<100000000100:?p & ( prime$!p & out$!p | ) ) & ;
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Forth
Forth
: as begin parse-word dup while evaluate , repeat 2drop ;   create bounds as 96 91 86 81 76 71 66 61 56 51 46 41 36 31 26 21 16 11 6 0 create official as 100 98 94 90 86 82 78 74 70 66 62 58 54 50 44 38 32 26 18 10   : official@ ( a-bounds -- +n ) \ (a+n) - a + b = (a+n) + (b - a) = (b+n) [ official bounds - ] literal + @ ;   : round ( n-cents -- n-cents' ) >r bounds begin dup @ r@ > while cell+ repeat r> drop official@ ;
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Fortran
Fortran
program price_fraction   implicit none integer, parameter :: i_max = 10 integer :: i real, dimension (20), parameter :: in = & & (/0.00, 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/) real, dimension (20), parameter :: out = & & (/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/) real :: r   do i = 1, i_max call random_number (r) write (*, '(f8.6, 1x, f4.2)') r, out (maxloc (in, r >= in)) end do   end program price_fraction
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#JavaScript
JavaScript
(function () {   // Proper divisors function properDivisors(n) { if (n < 2) return []; else { var rRoot = Math.sqrt(n), intRoot = Math.floor(rRoot),   lows = range(1, intRoot).filter(function (x) { return (n % x) === 0; });   return lows.concat(lows.slice(1).map(function (x) { return n / x; }).reverse().slice((rRoot === intRoot) | 0)); } }   // [m..n] function range(m, n) { var a = Array(n - m + 1), i = n + 1; while (i--) a[i - 1] = i; return a; }   var tblOneToTen = [ ['Number', 'Proper Divisors', 'Count'] ].concat(range(1, 10).map(function (x) { var ds = properDivisors(x);   return [x, ds.join(', '), ds.length]; })),   dctMostBelow20k = range(1, 20000).reduce(function (a, x) { var lng = properDivisors(x).length;   return lng > a.divisorCount ? { n: x, divisorCount: lng } : a; }, { n: 0, divisorCount: 0 });     // [[a]] -> bool -> s -> s function wikiTable(lstRows, blnHeaderRow, strStyle) { return '{| class="wikitable" ' + ( strStyle ? 'style="' + strStyle + '"' : '' ) + lstRows.map(function (lstRow, iRow) { var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');   return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) { return typeof v === 'undefined' ? ' ' : v; }).join(' ' + strDelim + strDelim + ' '); }).join('') + '\n|}'; }   return wikiTable( tblOneToTen, true ) + '\n\nMost proper divisors below 20,000:\n\n ' + JSON.stringify( dctMostBelow20k );   })();
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 involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#PL.2FI
PL/I
probch: Proc Options(main); Dcl prob(8) Dec Float(15) Init((1/5.0), /* aleph */ (1/6.0), /* beth */ (1/7.0), /* gimel */ (1/8.0), /* daleth */ (1/9.0), /* he */ (1/10.0), /* waw */ (1/11.0), /* zayin */ (1759/27720));/* heth */ Dcl what(8) Char(6) Init('aleph ','beth ','gimel ','daleth', 'he ','waw ','zayin ','heth '); Dcl ulim(0:8) Dec Float(15) Init((9)0); Dcl i Bin Fixed(31); Dcl ifloat Dec Float(15); Dcl one Dec Float(15) Init(1); Dcl num Dec Float(15) Init(1759); Dcl denom Dec Float(15) Init(27720); Dcl x Dec Float(15) Init(0); Dcl pr Dec Float(15) Init(0); Dcl (n,nn) Bin Fixed(31); Dcl cnt(8) Bin Fixed(31) Init((8)0); nn=1000000; Do i=1 To 8; ifloat=i+4; If i<8 Then prob(i)=one/ifloat; Else prob(i)=num/denom; Ulim(i)=ulim(i-1)+prob(i); /* Put Skip list(i,prob(i),ulim(i));*/ End; Do n=1 To nn; x=random(); Do i=1 To 8; If x<ulim(i) Then Leave; End; cnt(i)+=1; End; Put Edit('letter occurs frequency expected ')(Skip,a); Put Edit('------ ------ ---------- ----------')(Skip,a); Do i=1 To 8; pr=float(cnt(i))/float(nn); Put Edit(what(i),cnt(i),pr,prob(i))(Skip,a,f(10),x(2),2(f(11,8))); End; End;
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
push = Function[{queue, priority, item}, queue = SortBy[Append[queue, {priority, item}], First], HoldFirst]; pop = Function[queue, If[Length@queue == 0, Null, With[{item = queue[[-1, 2]]}, queue = Most@queue; item]], HoldFirst]; peek = Function[queue, If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst]; merge = Function[{queue1, queue2}, SortBy[Join[queue1, queue2], First], HoldAll];
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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#Tcl
Tcl
proc countPythagoreanTriples {limit} { lappend q 3 4 5 set idx [set count [set prim 0]] while {$idx < [llength $q]} { set a [lindex $q $idx] set b [lindex $q [incr idx]] set c [lindex $q [incr idx]] incr idx if {$a + $b + $c <= $limit} { incr prim for {set i 1} {$i*$a+$i*$b+$i*$c <= $limit} {incr i} { incr count } lappend q \ [expr {$a + 2*($c-$b)}] [expr {2*($a+$c) - $b}] [expr {2*($a-$b) + 3*$c}] \ [expr {$a + 2*($b+$c)}] [expr {2*($a+$c) + $b}] [expr {2*($a+$b) + 3*$c}] \ [expr {2*($b+$c) - $a}] [expr {2*($c-$a) + $b}] [expr {2*($b-$a) + 3*$c}] } } return [list $count $prim] } for {set i 10} {$i <= 10000000} {set i [expr {$i*10}]} { lassign [countPythagoreanTriples $i] count primitive puts "perimeter limit $i => $count triples, $primitive primitive" }
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#TI-83_BASIC
TI-83 BASIC
If 1 Stop
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#TI-89_BASIC
TI-89 BASIC
Prgm ... Stop ... EndPrgm
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Elixir
Elixir
defmodule Prime do def decomposition(n), do: decomposition(n, 2, [])   defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n]) defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc]) defp decomposition(n, k, acc), do: decomposition(n, k+1, acc) end   prime = Stream.iterate(2, &(&1+1)) |> Stream.filter(fn n-> length(Prime.decomposition(n)) == 1 end) |> Enum.take(17) mersenne = Enum.map(prime, fn n -> {n, round(:math.pow(2,n)) - 1} end) Enum.each(mersenne, fn {n,m} ->  :io.format "~3s :~20w = ~s~n", ["M#{n}", m, Prime.decomposition(m) |> Enum.join(" x ")] end)
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#Nim
Nim
type Foo = ref object x, y: float   var f: Foo new f
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#OCaml
OCaml
  let p = ref 1;; (* create a new "reference" data structure with initial value 1 *) let k = !p;; (* "dereference" the reference, returning the value inside *) p := k + 1;; (* set the value inside to a new 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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#F.23
F#
#r @"C:\Program Files\FlyingFrog\FSharpForVisualization.dll"   let x = Seq.map float [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9|] let y = [|2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0|]   open FlyingFrog.Graphics   Plot([Data(Seq.zip x y)], (0.0, 9.0))
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
#E
E
def makePoint(x, y) { def point implements pbc { to __printOn(out) { out.print(`<point $x,$y>`) } to __optUncall() { return [makePoint, "run", [x, y]] } to x() { return x } to y() { return y } to withX(new) { return makePoint(new, y) } to withY(new) { return makePoint(x, new) } } return point }   def makeCircle(x, y, r) { def circle extends makePoint(x, y) implements pbc { to __printOn(out) { out.print(`<circle $x,$y r $r>`) } to __optUncall() { return [makeCircle, "run", [x, y, r]] } to r() { return r } to withX(new) { return makeCircle(new, y, r) } to withY(new) { return makeCircle(x, new, r) } to withR(new) { return makeCircle(x, y, new) } } return circle }
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#J
J
parseHand=: <;._2@,&' '@u:~&7 NB. hand must be well formed Suits=: <"> 7 u: '♥♦♣♦' NB. or Suits=: 'hdcs' Faces=: <;._1 ' 2 3 4 5 6 7 8 9 10 j q k a'   suits=: {:&.> faces=: }:&.> flush=: 1 =&#&~. suits straight=: 1 = (i.#Faces) +/@E.~ Faces /:~@i. faces kinds=: #/.~ @:faces five=: 5 e. kinds NB. jokers or other cheat four=: 4 e. kinds three=: 3 e. kinds two=: 2 e. kinds twoPair=: 2 = 2 +/ .= kinds highcard=: 5 = 1 +/ .= kinds   IF=: 2 :'(,&(<m) ^: v)"1' Or=: 2 :'u ^:(5 e. $) @: v'   Deck=: ,Faces,&.>/Suits Joker=: <'joker' joke=: [: ,/^:(#@$ - 2:) (({. ,"1 Deck ,"0 1 }.@}.)^:(5>[)~ i.&Joker)"1^:2@,: punchLine=: {:@-.&a:@,@|: rateHand=: [:;:inv [: (, [: punchLine -1 :(0 :0-.LF)@joke) parseHand ('invalid' IF 1:) Or ('high-card' IF highcard) Or ('one-pair' IF two) Or ('two-pair' IF twoPair) Or ('three-of-a-kind' IF three) Or ('straight' IF straight) Or ('flush' IF flush) Or ('full-house' IF (two * three)) Or ('four-of-a-kind' IF four) Or ('straight-flush' IF (straight * flush)) Or ('five-of-a-kind' IF five) )
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#C.2B.2B
C++
#include <iostream> #include <bitset> #include <climits>   size_t popcount(unsigned long long n) { return std::bitset<CHAR_BIT * sizeof n>(n).count(); }   int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { std::cout << popcount(n) << " "; n *= 3; } std::cout << std::endl; }   int od[30]; int ne = 0, no = 0; std::cout << "evil  : "; for (int n = 0; ne+no < 60; n++) { if ((popcount(n) & 1) == 0) { if (ne < 30) { std::cout << n << " "; ne++; } } else { if (no < 30) { od[no++] = n; } } } std::cout << std::endl; std::cout << "odious: "; for (int i = 0; i < 30; i++) { std::cout << od[i] << " "; } std::cout << std::endl;   return 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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#GAP
GAP
x := Indeterminate(Rationals, "x"); p := x^11 + 3*x^8 + 7*x^2 + 3; q := x^7 + 5*x^3 + 1; QuotientRemainder(p, q); # [ x^4+3*x-5, -16*x^4+25*x^3+7*x^2-3*x+8 ]
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#Nim
Nim
type T = ref object of RootObj myValue: string S1 = ref object of T S2 = ref object of T   method speak(x: T) {.base.} = echo "T Hello ", x.myValue method speak(x: S1) = echo "S1 Meow ", x.myValue method speak(x: S2) = echo "S2 Woof ", x.myValue   echo "creating initial objects of types S1, S2, and T." var a = S1(myValue: "Green") a.speak var b = S2(myValue: "Blue") b.speak var u = T(myValue: "Blue") u.speak   echo "Making copy of a as u; colors and types should match." u.deepCopy(a) u.speak a.speak   echo "Assigning new color to u; A's color should be unchanged." u.myValue = "Orange" u.speak a.speak   echo "Assigning u to reference same object as b; colors and types should match." u = b u.speak b.speak   echo "Assigning new color to u. Since u,b reference the same object, b's color changes as well." u.myValue = "Yellow" u.speak b.speak
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#Objective-C
Objective-C
@interface T : NSObject - (void)identify; @end   @implementation T - (void)identify { NSLog(@"I am a genuine T"); } - (id)copyWithZone:(NSZone *)zone { T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here // then copy data into it as appropriate here // make sure to use "[[self class] alloc..." and // not "[T alloc..." to make it polymorphic return copy; } @end   @interface S : T @end   @implementation S - (void)identify { NSLog(@"I am an S"); } @end   int main() { @autoreleasepool {   T *original = [[S alloc] init]; T *another = [original copy]; [another identify]; // logs "I am an S"   } return 0; }
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#zkl
zkl
w,h:=640,640; bitmap:=PPM(w,h,0xFF|FF|FF); // White background angleIncrement:=(3.0).toRad(); while(True){ r,angle:=0.0, 0.0; ao,len,inc:=w/2, 2.5, angleIncrement+(130.0).toRad(); foreach c in (128){ s,a:=r + len, angle + inc; x,y:=r.toRectangular(angle); u,v:=r.toRectangular(a); c=c.shiftLeft(21) + c.shiftLeft(10) + c*8; // convert c to a RGB bitmap.line(ao+x,ao+y, ao+u,ao+v, c); r,angle=s,a; } bitmap.writeJPGFile("polyspiral.zkl.jpg"); bitmap.fill(0xFF|FF|FF); // White background angleIncrement=(angleIncrement + 0.05); Atomic.sleep(3); }
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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Hy
Hy
(import [numpy [polyfit]])   (setv x (range 11)) (setv y [1 6 17 34 57 86 121 162 209 262 321])   (print (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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
powerset s: local :out [ set{ } ] for value in keys s: for subset in copy out: local :subset+1 copy subset set-to subset+1 value true push-to out subset+1 out   !. powerset set{ 1 2 3 4 }
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#Delphi
Delphi
  program Power_set;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const n = 4;   var buf: TArray<Integer>;   procedure rec(ind, bg: Integer); begin for var i := bg to n - 1 do begin buf[ind] := i; for var j := 0 to ind do write(buf[j]: 2); writeln; rec(ind + 1, buf[ind] + 1); end; end;   begin SetLength(buf, n); rec(0,0); {$IFNDEF UNIX}readln;{$ENDIF} end.
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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Brainf.2A.2A.2A
Brainf***
>->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>> +]++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->------- --<]>--.[-]<<<->[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>> >]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--]<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--[>++++ ++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>]++++++++++[->+++++++++++<] >++.++.---------.++++.--------.>++++++++++.
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#FreeBASIC
FreeBASIC
' FB 1.050.0 Win64   Function rescale(price As Double) As Double If price < 0.00 OrElse price > 1.00 Then Return price Select Case price Case Is < 0.06 : Return 0.10 Case Is < 0.11 : Return 0.18 Case Is < 0.16 : Return 0.26 Case Is < 0.21 : Return 0.32 Case Is < 0.26 : Return 0.38 Case Is < 0.31 : Return 0.44 Case Is < 0.36 : Return 0.50 Case Is < 0.41 : Return 0.54 Case Is < 0.46 : Return 0.58 Case Is < 0.51 : Return 0.62 Case Is < 0.56 : Return 0.66 Case Is < 0.61 : Return 0.70 Case Is < 0.66 : Return 0.74 Case Is < 0.71 : Return 0.78 Case Is < 0.76 : Return 0.82 Case Is < 0.81 : Return 0.86 Case Is < 0.86 : Return 0.90 Case Is < 0.91 : Return 0.94 Case Is < 0.96 : Return 0.98 End Select Return 1.00 End Function   For i As Integer = 1 To 100 Dim d As Double = i/100.0 Print Using "#.##"; d; Print " -> "; Print Using "#.##"; rescale(d); Print " "; If i Mod 5 = 0 Then Print Next   Print Print "Press any key to quit" Sleep
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#jq
jq
def count(stream): reduce stream as $i (0; . + 1);   # unordered def proper_divisors: . as $n | if $n > 1 then 1, ( range(2; 1 + (sqrt|floor)) as $i | if ($n % $i) == 0 then $i, (($n / $i) | if . == $i then empty else . end) else empty end) else empty end;   # The first integer in 1 .. n inclusive # with the maximal number of proper divisors in that range: def most_proper_divisors(n): reduce range(1; n+1) as $i ( [null, 0]; count( $i | proper_divisors ) as $count | if $count > .[1] then [$i, $count] else . end);
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 involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#PowerShell
PowerShell
  $character = [PSCustomObject]@{ aleph = [PSCustomObject]@{Expected=1/5  ; Alpha="א"} beth = [PSCustomObject]@{Expected=1/6  ; Alpha="ב"} gimel = [PSCustomObject]@{Expected=1/7  ; Alpha="ג"} daleth = [PSCustomObject]@{Expected=1/8  ; Alpha="ד"} he = [PSCustomObject]@{Expected=1/9  ; Alpha="ה"} waw = [PSCustomObject]@{Expected=1/10  ; Alpha="ו"} zayin = [PSCustomObject]@{Expected=1/11  ; Alpha="ז"} heth = [PSCustomObject]@{Expected=1759/27720; Alpha="ח"} }   $sum = 0 $iterations = 1000000 $cumulative = [ordered]@{} $randomly = [ordered]@{}   foreach ($name in $character.PSObject.Properties.Name) { $sum += $character.$name.Expected $cumulative.$name = $sum $randomly.$name = 0 }   for ($i = 0; $i -lt $iterations; $i++) { $random = Get-Random -Minimum 0.0 -Maximum 1.0   foreach ($name in $cumulative.Keys) { if ($random -le $cumulative.$name) { $randomly.$name++ break } } }   foreach ($name in $character.PSObject.Properties.Name) { [PSCustomObject]@{ Name = $name Expected = $character.$name.Expected Actual = $randomly.$name / $iterations Character = $character.$name.Alpha } }  
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#Maxima
Maxima
/* Naive implementation using a sorted list of pairs [key, [item[1], ..., item[n]]]. The key may be any number (integer or not). Items are extracted in FIFO order. */   defstruct(pqueue(q = []))$   /* Binary search */   find_key(q, p) := block( [i: 1, j: length(q), k, c], if j = 0 then false elseif (c: q[i][1]) >= p then (if c = p then i else false) elseif (c: q[j][1]) <= p then (if c = p then j else false) else catch( while j >= i do ( k: quotient(i + j, 2), if (c: q[k][1]) = p then throw(k) elseif c < p then i: k + 1 else j: k - 1 ), false ) )$   pqueue_push(pq, x, p) := block( [q: pq@q, k], k: find_key(q, p), if integerp(k) then q[k][2]: endcons(x, q[k][2]) else pq@q: sort(cons([p, [x]], q)), 'done )$   pqueue_pop(pq) := block( [q: pq@q, v, x], if emptyp(q) then 'fail else ( p: q[1][1], v: q[1][2], x: v[1], if length(v) > 1 then q[1][2]: rest(v) else pq@q: rest(q), x ) )$   pqueue_print(pq) := block([t], while (t: pqueue_pop(pq)) # 'fail do disp(t))$     /* An example */   a: new(pqueue)$   pqueue_push(a, "take milk", 4)$ pqueue_push(a, "take eggs", 4)$ pqueue_push(a, "take wheat flour", 4)$ pqueue_push(a, "take salt", 4)$ pqueue_push(a, "take oil", 4)$ pqueue_push(a, "carry out crepe recipe", 5)$ pqueue_push(a, "savour !", 6)$ pqueue_push(a, "add strawberry jam", 5 + 1/2)$ pqueue_push(a, "call friends", 5 + 2/3)$ pqueue_push(a, "go to the supermarket and buy food", 3)$ pqueue_push(a, "take a shower", 2)$ pqueue_push(a, "get dressed", 2)$ pqueue_push(a, "wake up", 1)$ pqueue_push(a, "serve cider", 5 + 3/4)$ pqueue_push(a, "buy also cider", 3)$   pqueue_print(a); "wake up" "take a shower" "get dressed" "go to the supermarket and buy food" "buy also cider" "take milk" "take butter" "take flour" "take salt" "take oil" "carry out recipe" "add strawberry jam" "call friends" "serve cider" "savour !"
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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#VBA
VBA
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Tiny_BASIC
Tiny BASIC
LET I = 0 10 IF I = 10 THEN END LET I = I + 1 PRINT I GOTO 10
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#Transd
Transd
  (if errorCode (exit errorCode))  
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#True_BASIC
True BASIC
$$ MODE TUSCRIPT IF (condition==1) STOP -> execution stops and message: IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP "
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Erlang
Erlang
% no stack consuming version   factors(N) -> factors(N,2,[]).   factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N < K*K -> [N|Acc]; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc).
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#Oforth
Oforth
   ::class Foo  ::method init expose x x = 0  ::attribute x    ::routine somefunction a = .Foo~new -- assigns a to point to a new Foo object b = a -- b and a now point to the same object a~x = 5 -- modifies the X variable inside the object pointer to by a say b~x -- displays "5" because b points to the same object as a  
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#ooRexx
ooRexx
   ::class Foo  ::method init expose x x = 0  ::attribute x    ::routine somefunction a = .Foo~new -- assigns a to point to a new Foo object b = a -- b and a now point to the same object a~x = 5 -- modifies the X variable inside the object pointer to by a say b~x -- displays "5" because b points to the same object as a  
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Factor
Factor
USING: accessors assocs colors.constants kernel sequences ui ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;   chart new { { 0 9 } { 0 180 } } >>axes line new COLOR: blue >>color 9 <iota> { 2.7 2.8 31.4 38.1 58 76.2 100.5 130 149.3 180 } zip >>data add-gadget "Coordinate pairs" open-window
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim As Integer i, x(9), y(9) For i = 0 To 9 x(i) = i Next i   y(0) = 2.7 y(1) = 2.8 y(2) = 31.4 y(3) = 38.1 y(4) = 58.0 y(5) = 76.2 y(6) = 100.5 y(7) = 130.0 y(8) = 149.3 y(9) = 180.0   Locate 22, 4 For i = 0 To 9 Locate 22, ((i * 4) + 2) : Print i Next i   For i = 0 To 20 Step 2 Locate (21 - i), 0 : Print (i * 10) Next i   Color 14 For i = 0 To 9 Locate (21 - (y(i)/ 10)), (x(i) * 4) + 2 : Print "." Next i Sleep
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
#EchoLisp
EchoLisp
  (struct Point ((real:x 0) (real:y 0))) (struct Circle ((real:x 0) (real:y 0) (real:r 1)))   (define-method (print Point:p) (printf "📌 [%d %d]" p.x p.y)) (define-method (print Circle:c) (printf "⭕️ center:[%d %d] radius:%d" c.x c.y c.r))   (print (Point 5 6)) → 📌 [5 6] (print (Circle 2 3 4)) → ⭕️ center:[2 3] radius:4   ;; Accessors : ;; (Point-x p), (Point-y p) or p.x, p.y ;; (Circle-x c), c.x , etc. ;; Setters : ;; (set-Point-x! p value), (set-Circle-r! c value) etc.   ;; Constructors ;; (Point) (Point x) (Point x y) ;; (Circle) (circle x) (Circle x y) (Circle x y r)   ;;Copy (print (copy (Circle 3 3 ))) → ⭕️ center:[3 3] radius:1   ;;Assignment (to a variable) (define my-point (Point 7 8))   ;;Destructor : none. Points and Circles are garbage collected.   ;;Type checking (Point "here" "there") 💣 error: Real : type-check failure : here → 'Point:x'   ;;Initializer procedure (struct Circle ((x 0) (y 0) (r 1) d) #:initialize circle-init) (define (circle-init Circle:c) (set-Circle-d! c (* 2 PI c.r))) (define-method (print Circle:c) (printf "⭕️ center:[%d %d] radius:%d diameter:%d" c.x c.y c.r c.d))   (print (Circle 0 0 10)) → ⭕️ center:[0 0] radius:10 diameter:62.83185307179586  
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.HashSet;   public class PokerHandAnalyzer {   final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck();   public static void main(String[] args) { System.out.println("Regular hands:\n"); for (String input : new String[]{"2H 2D 2S KS QD", "2H 5H 7D 8S 9D", "AH 2D 3S 4S 5S", "2H 3H 2D 3S 3D", "2H 7H 2D 3S 3D", "2H 7H 7D 7S 7C", "TH JH QH KH AH", "4H 4C KC 5D TC", "QC TC 7C 6C 4C", "QC TC 7C 7C TD"}) { System.out.println(analyzeHand(input.split(" "))); }   System.out.println("\nHands with wildcards:\n"); for (String input : new String[]{"2H 2D 2S KS WW", "2H 5H 7D 8S WW", "AH 2D 3S 4S WW", "2H 3H 2D 3S WW", "2H 7H 2D 3S WW", "2H 7H 7D WW WW", "TH JH QH WW WW", "4H 4C KC WW WW", "QC TC 7C WW WW", "QC TC 7H WW WW"}) { System.out.println(analyzeHandWithWildcards(input.split(" "))); } }   private static Score analyzeHand(final String[] hand) { if (hand.length != 5) return new Score("invalid hand: wrong number of cards", -1, hand);   if (new HashSet<>(Arrays.asList(hand)).size() != hand.length) return new Score("invalid hand: duplicates", -1, hand);   int[] faceCount = new int[faces.length()]; long straight = 0, flush = 0; for (String card : hand) {   int face = faces.indexOf(card.charAt(0)); if (face == -1) return new Score("invalid hand: non existing face", -1, hand); straight |= (1 << face);   faceCount[face]++;   if (suits.indexOf(card.charAt(1)) == -1) return new Score("invalid hand: non-existing suit", -1, hand); flush |= (1 << card.charAt(1)); }   // shift the bit pattern to the right as far as possible while (straight % 2 == 0) straight >>= 1;   // straight is 00011111; A-2-3-4-5 is 1111000000001 boolean hasStraight = straight == 0b11111 || straight == 0b1111000000001;   // unsets right-most 1-bit, which may be the only one set boolean hasFlush = (flush & (flush - 1)) == 0;   if (hasStraight && hasFlush) return new Score("straight-flush", 9, hand);   int total = 0; for (int count : faceCount) { if (count == 4) return new Score("four-of-a-kind", 8, hand); if (count == 3) total += 3; else if (count == 2) total += 2; }   if (total == 5) return new Score("full-house", 7, hand);   if (hasFlush) return new Score("flush", 6, hand);   if (hasStraight) return new Score("straight", 5, hand);   if (total == 3) return new Score("three-of-a-kind", 4, hand);   if (total == 4) return new Score("two-pair", 3, hand);   if (total == 2) return new Score("one-pair", 2, hand);   return new Score("high-card", 1, hand); }   private static WildScore analyzeHandWithWildcards(String[] hand) { if (Collections.frequency(Arrays.asList(hand), "WW") > 2) throw new IllegalArgumentException("too many wildcards");   return new WildScore(analyzeHandWithWildcardsR(hand, null), hand.clone()); }   private static Score analyzeHandWithWildcardsR(String[] hand, Score best) {   for (int i = 0; i < hand.length; i++) { if (hand[i].equals("WW")) { for (String card : deck) { if (!Arrays.asList(hand).contains(card)) { hand[i] = card; best = analyzeHandWithWildcardsR(hand, best); } } hand[i] = "WW"; break; } } Score result = analyzeHand(hand); if (best == null || result.weight > best.weight) best = result; return best; }   private static String[] buildDeck() { String[] dck = new String[suits.length() * faces.length()]; int i = 0; for (char s : suits.toCharArray()) { for (char f : faces.toCharArray()) { dck[i] = "" + f + s; i++; } } return dck; }   private static class Score { final int weight; final String name; final String[] hand;   Score(String n, int w, String[] h) { weight = w; name = n; hand = h != null ? h.clone() : h; }   @Override public String toString() { return Arrays.toString(hand) + " " + name; } }   private static class WildScore { final String[] wild; final Score score;   WildScore(Score s, String[] w) { score = s; wild = w; }   @Override public String toString() { return String.format("%s%n%s%n", Arrays.toString(wild), score.toString()); } } }
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#Clojure
Clojure
  (defn population-count [n] (Long/bitCount n)) ; use Java inter-op   (defn exp [n pow] (reduce * (repeat pow n)))   (defn evil? [n] (even? (population-count n)))   (defn odious? [n] (odd? (population-count n)))   ;; ;; Clojure's support for generating "lazily-evaluated" infinite sequences can ;; be used to generate the requested output sets. We'll create some infinite ;; sequences, and only as many items will be computed as are "pulled" by 'take'. ;; (defn integers [] (iterate inc 0))   (defn powers-of-n [n] (map #(exp n %) (integers)))   (defn evil-numbers [] (filter evil? (integers)))   (defn odious-numbers [] (filter odious? (integers)))
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#Go
Go
package main   import "fmt"   func main() { n := []float64{-42, 0, -12, 1} d := []float64{-3, 1} fmt.Println("N:", n) fmt.Println("D:", d) q, r, ok := pld(n, d) if ok { fmt.Println("Q:", q) fmt.Println("R:", r) } else { fmt.Println("error") } }   func degree(p []float64) int { for d := len(p) - 1; d >= 0; d-- { if p[d] != 0 { return d } } return -1 }   func pld(nn, dd []float64) (q, r []float64, ok bool) { if degree(dd) < 0 { return } nn = append(r, nn...) if degree(nn) >= degree(dd) { q = make([]float64, degree(nn)-degree(dd)+1) for degree(nn) >= degree(dd) { d := make([]float64, degree(nn)+1) copy(d[degree(nn)-degree(dd):], dd) q[degree(nn)-degree(dd)] = nn[degree(nn)] / d[degree(d)] for i := range d { d[i] *= q[degree(nn)-degree(dd)] nn[i] -= d[i] } } } return q, nn, true }
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#OCaml
OCaml
let obj1 = object method name = "T" end   let obj2 = object method name = "S" end   let () = print_endline (Oo.copy obj1)#name; (* prints "T" *) print_endline (Oo.copy obj2)#name; (* prints "S" *)
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#ooRexx
ooRexx
  s = .s~new s2 = s~copy -- makes a copy of the first if s == s2 then say "copy didn't work!" if s2~name == "S" then say "polymorphic copy worked"   ::class t ::method name return "T"   ::class s subclass t ::method name return "S"  
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#OxygenBasic
OxygenBasic
  '====== class T '======   float vv   method constructor(float a=0) {vv=a} method destructor {} method copy as T {new T ob : ob<=vv : return ob} method mA() as float {return vv*2} method mB() as float {return vv*3}   end class     '====== class S '======   has T   method mB() as float {return vv*4} 'ovveride   end class   '==== 'TEST '====   new T objA(10.5)   let objB = cast S objA.copy   print objA.mb 'result 31.5 print objB.mb 'result 42   del objA : del objB  
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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#J
J
Y=:1 6 17 34 57 86 121 162 209 262 321 (%. ^/~@x:@i.@#) Y 1 2 3 0 0 0 0 0 0 0 0
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#Dyalect
Dyalect
let n = 4 let buf = Array.Empty(n)   func rec(idx, begin) { for i in begin..<n { buf[idx] = i for j in 0..idx { print("{0, 2}".Format(buf[j]), terminator: "") } print("") rec(idx + 1, buf[idx] + 1) } }   rec(0, 0)
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#E
E
pragma.enable("accumulator")   def powerset(s) { return accum [].asSet() for k in 0..!2**s.size() { _.with(accum [].asSet() for i ? ((2**i & k) > 0) => elem in s { _.with(elem) }) } }
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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Burlesque
Burlesque
fcL[2==
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#Gambas
Gambas
Public Sub Main() Dim byValue As Byte[] = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100] Dim byLimit As Byte[] = [6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96] Dim byCount, byCheck As Byte   For byCount = 0 To 100 For byCheck = 0 To byLimit.Max If byCount < byLimit[byCheck] Then Break Next Print Format(byCount / 100, "0.00") & " = " & Format(byValue[byCheck] / 100, "0.00") & gb.Tab; If byCount Mod 5 = 0 Then Print Next   End
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#Julia
Julia
  function properdivisors{T<:Integer}(n::T) 0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n")) 1 < n || return T[]  !isprime(n) || return T[one(T), n] f = factor(n) d = T[one(T)] for (k, v) in f c = T[k^i for i in 0:v] d = d*c' d = reshape(d, length(d)) end sort!(d) return d[1:end-1] end   lo = 1 hi = 10 println("List the proper divisors for ", lo, " through ", hi, ".") for i in lo:hi println(@sprintf("%4d", i), " ", properdivisors(i)) end   hi = 2*10^4 println("\nFind the numbers within [", lo, ",", hi, "] having the most divisors.")   maxdiv = 0 nlst = Int[]   for i in lo:hi ndiv = length(properdivisors(i)) if ndiv > maxdiv maxdiv = ndiv nlst = [i] elseif ndiv == maxdiv push!(nlst, i) end end   println(nlst, " have the maximum proper divisor count of ", maxdiv, ".")  
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 involved, this is subject to rounding errors). aleph 1/5.0 beth 1/6.0 gimel 1/7.0 daleth 1/8.0 he 1/9.0 waw 1/10.0 zayin 1/11.0 heth 1759/27720 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#PureBasic
PureBasic
#times=1000000   Structure Item name.s prob.d Amount.i EndStructure   If OpenConsole() Define i, j, d.d, e.d, txt.s Dim Mapps.Item(7) Mapps(0)\name="aleph": Mapps(0)\prob=1/5.0 Mapps(1)\name="beth": Mapps(1)\prob=1/6.0 Mapps(2)\name="gimel": Mapps(2)\prob=1/7.0 Mapps(3)\name="daleth":Mapps(3)\prob=1/8.0 Mapps(4)\name="he": Mapps(4)\prob=1/9.0 Mapps(5)\name="waw": Mapps(5)\prob=1/10.0 Mapps(6)\name="zayin": Mapps(6)\prob=1/11.0 Mapps(7)\name="heth": Mapps(7)\prob=1759/27720.0   For i=1 To #times d=Random(#MAXLONG)/#MAXLONG ; Get a random number e=0.0 For j=0 To ArraySize(Mapps()) e+Mapps(j)\prob ; Get span for current itme If d<=e ; Check if it is within this span? Mapps(j)\Amount+1 ; If so, count it. Break EndIf Next j Next i   PrintN("Sample times: "+Str(#times)+#CRLF$) For j=0 To ArraySize(Mapps()) d=Mapps(j)\Amount/#times txt=LSet(Mapps(j)\name,7)+" should be "+StrD(Mapps(j)\prob)+" is "+StrD(d) PrintN(txt+" | Deviatation "+RSet(StrD(100.0-100.0*Mapps(j)\prob/d,3),6)+"%") Next   Print(#CRLF$+"Press ENTER to exit"):Input() CloseConsole() EndIf
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#Mercury
Mercury
:- module test_pqueue.   :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module int. :- import_module list. :- import_module pqueue. :- import_module string.   :- pred build_pqueue(pqueue(int,string)::in, pqueue(int,string)::out) is det. build_pqueue(!PQ) :- pqueue.insert(3, "Clear drains",  !PQ), pqueue.insert(4, "Feed cat",  !PQ), pqueue.insert(5, "Make tea",  !PQ), pqueue.insert(1, "Solve RC tasks", !PQ), pqueue.insert(2, "Tax return",  !PQ).   :- pred display_pqueue(pqueue(int, string)::in, io::di, io::uo) is det. display_pqueue(PQ, !IO) :- ( pqueue.remove(K, V, PQ, PQO) -> io.format("Key = %d, Value = %s\n", [i(K), s(V)], !IO), display_pqueue(PQO, !IO)  ; true ).   main(!IO) :- build_pqueue(pqueue.init, PQO), display_pqueue(PQO, !IO).
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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#VBScript
VBScript
  For i=1 To 8 WScript.StdOut.WriteLine triples(10^i) Next   Function triples(pmax) prim=0 : count=0 : nmax=Sqr(pmax)/2 : n=1 Do While n <= nmax m=n+1 : p=2*m*(m+n) Do While p <= pmax If gcd(m,n)=1 Then prim=prim+1 count=count+Int(pmax/p) End If m=m+2 p=2*m*(m+n) Loop n=n+1 Loop triples = "Max Perimeter: " & pmax &_ ", Total: " & count &_ ", Primitive: " & prim End Function   Function gcd(a,b) c = a : d = b Do If c Mod d > 0 Then e = c Mod d c = d d = e Else gcd = d Exit Do End If Loop End Function  
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT IF (condition==1) STOP -> execution stops and message: IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP "
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#UNIX_Shell
UNIX Shell
#!/bin/sh   a='1' b='1' if [ "$a" -eq "$b" ]; then exit 239 # Unexpected error fi exit 0 # Program terminated normally
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#ERRE
ERRE
  PROGRAM DECOMPOSE     ! ! for rosettacode.org !   !VAR NUM,J   DIM PF[100]   PROCEDURE STORE_FACTOR PF[0]=PF[0]+1 PF[PF[0]]=CA I=I/CA END PROCEDURE   PROCEDURE DECOMP(I) PF[0]=0 CA=2 ! special case LOOP IF I=1 THEN EXIT PROCEDURE END IF EXIT IF INT(I/CA)*CA<>I STORE_FACTOR END LOOP FOR CA=3 TO INT(SQR(I)) STEP 2 DO LOOP IF I=1 THEN EXIT PROCEDURE END IF EXIT IF INT(I/CA)*CA<>I STORE_FACTOR END LOOP END FOR IF I>1 THEN CA=I STORE_FACTOR END IF END PROCEDURE   BEGIN  ! ----- function generate  ! in ... I ... number  ! out ... PF[] ... factors  ! PF[0] ... # of factors  ! mod ... CA ... pr.fact. candidate PRINT(CHR$(12);) !CLS INPUT("Numero ",NUM) DECOMP(NUM) PRINT(NUM;"=";) FOR J=1 TO PF[0] DO PRINT(PF[J];) END FOR PRINT END PROGRAM  
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#PARI.2FGP
PARI/GP
n=1; issquare(9,&n); print(n); \\ prints 3
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#Pascal
Pascal
program pointerDemo;   type { A new pointer data type is declared by `↑` followed by a data type name, the domain.   The domain data type may not have been declared yet, but must be declared within the current `type` section.   Most compilers do not support the reference token `↑` as specified in the ISO standards 7185 and 10206, but use the alternative `^` (caret). } integerReference = ^integer;   var integerLocation: integerReference;   begin { The procedure `new` taken one pointer variable and allocates memory for one new instance of the pointer domain’s data type (here an `integer`). The pointer variable will hold the address of the allocated instance. } new(integerLocation);   { Dereferencing a pointer is done via appending `↑` to the variable’s name. All operations on the domain type are now possible. } integerLocation^ := 42;   { The procedure `dispose` takes one pointer variable and releases the underlying memory. The supplied variable is otherwise not modified. } dispose(integerLocation); { In Pascal, `dispose` is not necessary. Any excess memory is automatically released after `program` termination. } end.
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#FreeBASIC
FreeBASIC
Dim As Integer i, x(9), y(9) For i = 0 To 9 x(i) = i Next i   y(0) = 2.7 y(1) = 2.8 y(2) = 31.4 y(3) = 38.1 y(4) = 58.0 y(5) = 76.2 y(6) = 100.5 y(7) = 130.0 y(8) = 149.3 y(9) = 180.0   Locate 22, 4 For i = 0 To 9 Locate 22, ((i * 4) + 2) : Print i Next i   For i = 0 To 20 Step 2 Locate (21 - i), 0 : Print (i * 10) Next i   Color 14 For i = 0 To 9 Locate (21 - (y(i)/ 10)), (x(i) * 4) + 2 : Print "." Next i Sleep
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
#Eiffel
Eiffel
class POINT inherit ANY redefine out end create make, make_origin   feature -- Initialization   make (a_x, a_y: INTEGER) -- Create with values `a_x' and `a_y' do set_x (a_x) set_y (a_y) ensure x_set: x = a_x y_set: y = a_y end   make_origin -- Create at origin do ensure x_set: x = 0 y_set: y = 0 end   feature -- Access   x: INTEGER assign set_x -- Horizontal axis coordinate   y: INTEGER assign set_y -- Vertical axis coordinate   feature -- Element change   set_x (a_x: INTEGER) -- Set `x' coordinate to `a_x' do x := a_x ensure x_set: x = a_x end   set_y (a_y: INTEGER) -- Set `y' coordinate to `a_y' do y := a_y ensure y_set: y = a_y end   feature -- Output   out: STRING -- Display as string do Result := "Point: x = " + x.out + " y = " + y.out end end
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#JavaScript
JavaScript
const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a']; const SUITS = ['♥', '♦', '♣', '♠'];   function analyzeHand(hand){ let cards = hand.split(' ').filter(x => x !== 'joker'); let jokers = hand.split(' ').length - cards.length;   let faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) ); let suits = cards.map( card => SUITS.indexOf(card.slice(-1)) );   if( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) return 'invalid';   let flush = suits.every(suit => suit === suits[0]); let groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x ); let shifted = faces.map(x => (x + 1) % 13); let distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted)); let straight = groups[0] === 1 && distance < 5; groups[0] += jokers;   if (groups[0] === 5) return 'five-of-a-kind' else if (straight && flush) return 'straight-flush' else if (groups[0] === 4) return 'four-of-a-kind' else if (groups[0] === 3 && groups[1] === 2) return 'full-house' else if (flush) return 'flush' else if (straight) return 'straight' else if (groups[0] === 3) return 'three-of-a-kind' else if (groups[0] === 2 && groups[1] === 2) return 'two-pair' else if (groups[0] === 2) return 'one-pair' else return 'high-card'; }
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#CLU
CLU
pop_count = proc (n: int) returns (int) p: int := 0 while n>0 do p := p + n//2 n := n/2 end return(p) end pop_count   evil = proc (n: int) returns (bool) return(pop_count(n)//2 = 0) end evil   odious = proc (n: int) returns (bool) return(~evil(n)) end odious   first = iter (n: int, p: proctype (int) returns (bool)) yields (int) i: int := 0 while n>0 do if p(i) then yield(i) n := n-1 end i := i+1 end end first   start_up = proc () po: stream := stream$primary_output()   for i: int in int$from_to(0,29) do stream$putright(po, int$unparse(pop_count(3**i)), 3) end stream$putl(po, "")   for i: int in first(30, evil) do stream$putright(po, int$unparse(i), 3) end stream$putl(po, "")   for i: int in first(30, odious) do stream$putright(po, int$unparse(i), 3) end stream$putl(po, "") end start_up
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#Haskell
Haskell
import Data.List   shift n l = l ++ replicate n 0   pad n l = replicate n 0 ++ l   norm :: Fractional a => [a] -> [a] norm = dropWhile (== 0)   deg l = length (norm l) - 1   zipWith' op p q = zipWith op (pad (-d) p) (pad d q) where d = (length p) - (length q)   polydiv f g = aux (norm f) (norm g) [] where aux f s q | ddif < 0 = (q, f) | otherwise = aux f' s q' where ddif = (deg f) - (deg s) k = (head f) / (head s) ks = map (* k) $ shift ddif s q' = zipWith' (+) q $ shift ddif [k] f' = norm $ tail $ zipWith' (-) f ks