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/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.
#REXX
REXX
/*REXX program plots X,Y coördinate pairs of numbers with plain (ASCII) characters.*/ 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 $= do j=1 for words(x) /*build a list suitable for $PLOT subr.*/ $=$ word(x, j)','word(y, j) /*add this X,Y coördinate to the $ list*/ end /*j*/ /*$≡ 0,2.7 1,2.8 2,31.4 3,38.1 ··· */ call '$PLOT' $ /*invoke the REXX program: $PLOT */ exit rc /*stick a fork in it, we're all done. */
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
#PicoLisp
PicoLisp
(class +Point) # x y   (dm T (X Y) (=: x (or X 0)) (=: y (or Y 0)) )   (dm print> () (prinl "Point " (: x) "," (: y)) )   (class +Circle +Point) # r   (dm T (X Y R) (super X Y) (=: r (or R 0)) )   (dm print> () (prinl "Circle " (: x) "," (: y) "," (: r)) )
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Pop11
Pop11
uses objectclass; define :class Point; slot x = 0; slot y = 0; enddefine;   define :class Circle; slot x = 0; slot y = 0; slot r = 1; enddefine;   define :method print(p : Point); printf('Point(' >< x(p) >< ', ' >< y(p) >< ')\n'); enddefine;   define :method print(p : Circle); printf('Circle(' >< x(p) >< ', ' >< y(p) >< ', ' >< r(p) >< ')\n'); enddefine;
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.
#Kotlin
Kotlin
// version 1.0.6   fun popCount(n: Long) = when { n < 0L -> throw IllegalArgumentException("n must be non-negative") else -> java.lang.Long.bitCount(n) }   fun main(args: Array<String>) { println("The population count of the first 30 powers of 3 are:") var pow3 = 1L for (i in 1..30) { print("${popCount(pow3)} ") pow3 *= 3L } println("\n") println("The first thirty evil numbers are:") var count = 0 var i = 0 while (true) { val pc = popCount(i.toLong()) if (pc % 2 == 0) { print("$i ") if (++count == 30) break } i++ } println("\n") println("The first thirty odious numbers are:") count = 0 i = 1 while (true) { val pc = popCount(i.toLong()) if (pc % 2 == 1) { print("$i ") if (++count == 30) break } i++ } println() }
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.
#Swift
Swift
    let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]   func average(_ input: [Int]) -> Int { return input.reduce(0, +) / input.count }   func polyRegression(x: [Int], y: [Int]) { let xm = average(x) let ym = average(y) let x2m = average(x.map { $0 * $0 }) let x3m = average(x.map { $0 * $0 * $0 }) let x4m = average(x.map { $0 * $0 * $0 * $0 }) let xym = average(zip(x,y).map { $0 * $1 }) let x2ym = average(zip(x,y).map { $0 * $0 * $1 })   let sxx = x2m - xm * xm let sxy = xym - xm * ym let sxx2 = x3m - xm * x2m let sx2x2 = x4m - x2m * x2m let sx2y = x2ym - x2m * ym   let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) let a = ym - b * xm - c * x2m   func abc(xx: Int) -> Int { return (a + b * xx) + (c * xx * xx) }   print("y = \(a) + \(b)x + \(c)x^2\n") print(" Input Approximation") print(" x y y1")   for i in 0 ..< x.count { let result = Double(abc(xx: i)) print(String(format: "%2d %3d  %5.1f", x[i], y[i], result)) } }   polyRegression(x: x, y: y)  
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.
#Maple
Maple
  combinat:-powerset({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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Subsets[{a, b, c}]
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
#Forth
Forth
: prime? ( n -- f ) dup 2 < if drop false else dup 2 = if drop true else dup 1 and 0= if drop false else 3 begin 2dup dup * >= while 2dup mod 0= if 2drop false exit then 2 + repeat 2drop true then then then ;
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( ( 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 ) )   def price_fix var p len for get 3 get swap 1 get swap 2 get nip p swap < swap p swap >= and if exitfor else drop endif endfor enddef   ( 0.00 1.01 0.01 ) for dup print 9 tochar print price_fix print nl endfor  
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
#Picat
Picat
go => _ = random2(), D = [ [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]],   Len = D.length, foreach(_ in 1..10) R = frand2(100), between(1,Len,Ix), R >= D[Ix,1], R < D[Ix,2], New = D[Ix,3], println(R=New) end, nl.   % Getting numbers of precision 2 frand2(N) = (random() mod N)/N.
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 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
#REXX
REXX
  /*REXX*/   Call time 'R' Do x=1 To 10 Say x '->' proper_divisors(x) End   hi=1 Do x=1 To 20000 /* If x//1000=0 Then Say x */ npd=count_proper_divisors(x) Select When npd>hi Then Do list.npd=x hi=npd End When npd=hi Then list.hi=list.hi x Otherwise Nop End End   Say hi '->' list.hi   Say ' 166320 ->' count_proper_divisors(166320) Say '1441440 ->' count_proper_divisors(1441440)   Say time('E') 'seconds elapsed' Exit   proper_divisors: Procedure Parse Arg n If n=1 Then Return '' pd='' /* Optimization reduces 37 seconds to 28 seconds */ If n//2=1 Then /* odd number */ delta=2 Else /* even number */ delta=1 Do d=1 To n%2 By delta If n//d=0 Then pd=pd d End Return space(pd)   count_proper_divisors: Procedure Parse Arg n Return words(proper_divisors(n))
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.
#Sidef
Sidef
class PriorityQueue { has tasks = []   method insert (Number priority { _ >= 0 }, task) { for n in range(tasks.len, priority) { tasks[n] = [] } tasks[priority].append(task) }   method get { tasks.first { !.is_empty } -> shift } method is_empty { tasks.all { .is_empty } } }   var pq = PriorityQueue()   [ [3, 'Clear drains'], [4, 'Feed cat'], [5, 'Make tea'], [9, 'Sleep'], [3, 'Check email'], [1, 'Solve RC tasks'], [9, 'Exercise'], [2, 'Do taxes'], ].each { |pair| pq.insert(pair...) }   say pq.get while !pq.is_empty
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
#Maple
Maple
> ifactor(1337); (7) (191)  
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.
#Ring
Ring
  # Project : Plot coordinate pairs   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Plot coordinate pairs") setgeometry(100,100,1024,900) label1 = new qlabel(win1) { setgeometry(10,10,1024,900) settext("") } new qpushbutton(win1) { setgeometry(50,50,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) setpen(pen)   old = 0 yold = 0 xnew = 0 ynew = 0 x2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y2 = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]   for x = 1 to 9 drawline(100*x,720,100*x,0) drawtext(100*x,750,string(x)) next   for y = 20 to 180 step 20 drawline(900,4*y,0,4*y) drawtext(0,720-4*y,string(y)) next   drawline(0,0,0,720) drawline(0,0,900,0)   for i = 1 to 10 if i=1 xold = 100*x2[i] yold = 720-4*y2[i] else xnew = 100*x2[i] ynew = 720-4*y2[i] drawline(xold,yold,xnew,ynew) xold = xnew yold = ynew ok next   endpaint() } label1 { setpicture(p1) show() } return  
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.
#Ruby
Ruby
require 'gnuplot'   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] Gnuplot.open do |gp| Gnuplot::Plot.new( gp ) do |plot| plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds| ds.with = "linespoints" ds.notitle end end end
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
#Prolog
Prolog
% Point point_construct(X, Y, point(X1,Y1)) :- default(X, X1), default(Y, Y1).   % Circle circle_construct(X, Y, R, circle(X1,Y1,R1)) :- default(X, X1), default(Y, Y1), default(R, R1).   % Accessors for general X,Y % individual getters/setters can be made but it is not required shape_x_y_set(point(_,_), X, Y, point(X,Y)). shape_x_y_set(circle(_,_,R), X, Y, circle(X,Y,R)).   % Accessors for R cicle_r_set(circle(X,Y,_), R, circle(X,Y,R)).   % Print print_shape(point(X,Y)) :- format('Point (~p,~p)', [X,Y]). print_shape(circle(X,Y,R)) :- format('Circle (~p,~p,~p)', [X,Y,R]).   % Default values for constructor (default to 0). default(N, 0) :- var(N). default(N, N) :- number(N).   % Tests test_point :- point_construct(2,3,P), test_poly(P).   test_circle :- circle_construct(3,4,_,C), cicle_r_set(C, 5, C1), test_poly(C1).   test_poly(T) :- shape_x_y_set(_, X, Y, T), X1 is X * 2, Y1 is Y * 2, shape_x_y_set(T, X1, Y1, T1), print_shape(T1).
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.
#Lua
Lua
-- Take decimal number, return binary string function dec2bin (n) local bin, bit = "" while n > 0 do bit = n % 2 n = math.floor(n / 2) bin = bit .. bin end return bin end   -- Take decimal number, return population count as number function popCount (n) local bin, count = dec2bin(n), 0 for pos = 1, bin:len() do if bin:sub(pos, pos) == "1" then count = count + 1 end end return count end   -- Implement task requirements function firstThirty (mode) local numStr, count, n, remainder = "", 0, 0 if mode == "Evil" then remainder = 0 else remainder = 1 end while count < 30 do if mode == "3^x" then numStr = numStr .. popCount(3 ^ count) .. " " count = count + 1 else if popCount(n) % 2 == remainder then numStr = numStr .. n .. " " count = count + 1 end n = n + 1 end end print(mode .. ":" , numStr) end   -- Main procedure firstThirty("3^x") firstThirty("Evil") firstThirty("Odious")
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.
#Tcl
Tcl
package require math::linearalgebra   proc build.matrix {xvec degree} { set sums [llength $xvec] for {set i 1} {$i <= 2*$degree} {incr i} { set sum 0 foreach x $xvec { set sum [expr {$sum + pow($x,$i)}] } lappend sums $sum }   set order [expr {$degree + 1}] set A [math::linearalgebra::mkMatrix $order $order 0] for {set i 0} {$i <= $degree} {incr i} { set A [math::linearalgebra::setrow A $i [lrange $sums $i $i+$degree]] } return $A }   proc build.vector {xvec yvec degree} { set sums [list] for {set i 0} {$i <= $degree} {incr i} { set sum 0 foreach x $xvec y $yvec { set sum [expr {$sum + $y * pow($x,$i)}] } lappend sums $sum }   set x [math::linearalgebra::mkVector [expr {$degree + 1}] 0] for {set i 0} {$i <= $degree} {incr i} { set x [math::linearalgebra::setelem x $i [lindex $sums $i]] } return $x }   # Now, to solve the example from the top of this page set x {0 1 2 3 4 5 6 7 8 9 10} set y {1 6 17 34 57 86 121 162 209 262 321}   # build the system A.x=b set degree 2 set A [build.matrix $x $degree] set b [build.vector $x $y $degree] # solve it set coeffs [math::linearalgebra::solveGauss $A $b] # show results puts $coeffs
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.
#MATLAB
MATLAB
function pset = powerset(theSet)   pset = cell(size(theSet)); %Preallocate memory   %Generate all numbers from 0 to 2^(num elements of the set)-1 for i = ( 0:(2^numel(theSet))-1 )   %Convert i into binary, convert each digit in binary to a boolean %and store that array of booleans indicies = logical(bitget( i,(1:numel(theSet)) ));   %Use the array of booleans to extract the members of the original %set, and store the set containing these members in the powerset pset(i+1) = {theSet(indicies)};   end   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
#Fortran
Fortran
FUNCTION isPrime(number) LOGICAL :: isPrime INTEGER, INTENT(IN) :: number INTEGER :: i   IF(number==2) THEN isPrime = .TRUE. ELSE IF(number < 2 .OR. MOD(number,2) == 0) THEN isPRIME = .FALSE. ELSE isPrime = .TRUE. DO i = 3, INT(SQRT(REAL(number))), 2 IF(MOD(number,i) == 0) THEN isPrime = .FALSE. EXIT END IF END DO END IF END FUNCTION
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
#PicoLisp
PicoLisp
(scl 2)   (de price (Pr) (format (cdr (rank Pr (quote (0.00 . 0.10) (0.06 . 0.18) (0.11 . 0.26) (0.16 . 0.32) (0.21 . 0.38) (0.26 . 0.44) (0.31 . 0.50) (0.36 . 0.54) (0.41 . 0.58) (0.46 . 0.62) (0.51 . 0.66) (0.56 . 0.70) (0.61 . 0.74) (0.66 . 0.78) (0.71 . 0.82) (0.76 . 0.86) (0.81 . 0.90) (0.86 . 0.94) (0.91 . 0.98) (0.96 . 1.00) ) ) ) *Scl ) )   (for N (0.3793 0.4425 0.0746 0.6918 0.2993 0.5486 0.7848 0.9383 0.2292) (prinl (price N)) )
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to 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
#PL.2FI
PL/I
declare t(20) fixed decimal (3,2) static initial ( .06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01); declare r(20) fixed decimal (3,2) static initial ( .10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1); declare x float, d fixed decimal (3,2); declare i fixed binary;   loop: do i = 1 to 20; if x < t(i) then do; d = r(i); leave loop; end; 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
#Ring
Ring
  # Project : Proper divisors   limit = 10 for n=1 to limit if n=1 see "" + 1 + " -> (None)" + nl loop ok see "" + n + " -> " for m=1 to n-1 if n%m = 0 see " " + m ok next see nl next  
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.
#Standard_ML
Standard ML
structure TaskPriority = struct type priority = int val compare = Int.compare type item = int * string val priority : item -> int = #1 end   structure PQ = LeftPriorityQFn (TaskPriority) ;   let val tasks = [ (3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")] val pq = foldl PQ.insert PQ.empty tasks (* or val pq = PQ.fromList tasks *) fun aux pq' = case PQ.next pq' of NONE => () | SOME ((prio, name), pq'') => ( print (Int.toString prio ^ ", " ^ name ^ "\n"); aux pq'' ) in aux pq end
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FactorInteger[2016] => {{2, 5}, {3, 2}, {7, 1}}
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Scala
Scala
import scala.swing.Swing.pair2Dimension import scala.swing.{ MainFrame, Panel, Rectangle } import java.awt.{ Color, Graphics2D, geom }   object PlotCoordPairs extends scala.swing.SimpleSwingApplication {   //min/max of display-x resp. y val (dx0, dy0) = (70, 30) val (dxm, dym) = (670, 430)   val (prefSizeX, prefSizeY) = (720, 480)   private def ui = new Panel {   import math._ val xmax = { val f1 = pow(10, log10(xs.max).toInt) val f2 = if (f1 < 10) 10 else round(xs.max / f1) * f1 if (f2 >= xs.max) f2 else (round(xs.max / f1) + 1) * f1 } val ymax = { val f1 = pow(10, log10(ys.max).toInt) val f2 = if (f1 < 10) 10 else round(ys.max / f1) * f1 if (f2 >= ys.max) f2 else (round(ys.max / f1) + 1) * f1 }   val (xinterv, yinterv) = (xmax / xs.size, ymax / xs.size)   case class Coord(x: Double, y: Double) { val (dx, dy) = ((x / xmax * (dxm - dx0) + dx0).toInt, (dym - y / ymax * (dym - dy0)).toInt) }   val pcentre = Coord(0, 0) val pxmax = Coord(xmax, 0) val pymax = Coord(0, ymax)   background = Color.white preferredSize = (prefSizeX, prefSizeY)   //axes: val a_path = new geom.GeneralPath a_path.moveTo(pxmax.dx, pxmax.dy) a_path.lineTo(pcentre.dx, pcentre.dy) //x-axis a_path.lineTo(pymax.dx, pymax.dy) //y-axis // interval ticks: xs.map(i => Coord(i * xinterv, 0)).map(p => { a_path.moveTo(p.dx, p.dy) a_path.lineTo(p.dx, p.dy + 5) }) xs.map(i => Coord(0, i * yinterv)).map(p => { a_path.moveTo(p.dx, p.dy) a_path.lineTo(p.dx - 5, p.dy) })   //grid: val g_path = new geom.GeneralPath (1 to xs.size). map(i => Coord(i * xinterv, 0)).map(p => { g_path.moveTo(p.dx, p.dy); g_path.lineTo(Coord(p.x, ymax).dx, Coord(p.x, ymax).dy) }) (1 to xs.size).map(i => Coord(0, i * yinterv)).map(p => { g_path.moveTo(p.dx, p.dy); g_path.lineTo(Coord(xmax, p.y).dx, Coord(xmax, p.y).dy) })   //labeling: val xlabels = (0 to xs.size).map(i => { val p = Coord(i * xinterv, 0) Triple(p.x.toInt.toString, p.dx - 3, p.dy + 20) }) val ylabels = (0 to xs.size).map(i => { val p = Coord(0, i * yinterv) Triple(p.y.toInt.toString, p.dx - 30, p.dy + 5) })   //curve: val path = new geom.GeneralPath val curve = xs.map(i => Coord(xs(i), ys(i))) path.moveTo(curve.head.dx, curve.head.dy) curve.map(p => path.lineTo(p.dx, p.dy)) //...flag all function values: val rects = curve.map(p => new Rectangle(p.dx - 3, p.dy - 3, 6, 6))   override def paintComponent(g: Graphics2D) = { super.paintComponent(g)   g.setColor(Color.lightGray) g.draw(g_path) g.setColor(Color.black) g.draw(a_path) xlabels.map(t => g.drawString(t._1, t._2, t._3)) ylabels.map(t => g.drawString(t._1, t._2, t._3)) g.draw(path) rects.map(g.draw(_)) } }   val xs = 0 to 9 val ys: List[Double] = List(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0)   def top = new MainFrame { title = "Rosetta Code >>> Task: Plot coordinate pairs | Language: Scala" contents = ui } }
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
#PureBasic
PureBasic
Class MyPoint   BeginProtect x.i y.i EndProtect   Public Method GetX() MethodReturn This\X EndMethod   Public Method GetY() MethodReturn This\Y EndMethod   Public Method SetX(n) This\X=n EndMethod   Public Method SetY(n) This\Y=n EndMethod   Public Method Print() PrintN("Point") EndMethod   Public Method Init(x=0,y=0) This\x=x This\y=y EndMethod EndClass   Class Circle Extends MyPoint   Protect Radie.i   Public Method Circel(x=0, y=0, r=0) This\X = x This\y = y This\Radie=r EndMethod   Public Method GetRadie() MethodReturn This\Radie EndMethod   Public Method SetRadie(n) This\Radie = n EndMethod   Public Method Print() PrintN("Circle: "+ _ " X= "+Str(This\X)+ _ " Y= "+Str(This\Y)+ _ " R= "+Str(This\Radie)) EndMethod   EndClass
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.
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2   R FUNCTION TO CALC POP COUNT INTERNAL FUNCTION(N) ENTRY TO POPCNT. RSLT = 0 PCTNUM = N LOOP PCTNXT = PCTNUM/2 RSLT = RSLT + PCTNUM-PCTNXT*2 PCTNUM = PCTNXT WHENEVER PCTNUM.NE.0, TRANSFER TO LOOP FUNCTION RETURN RSLT END OF FUNCTION   R POP COUNT OF 3^0 TO 3^29 POW3 = 1 THROUGH P3CNT, FOR I=0, 1, I.GE.30 PRINT FORMAT P3FMT, I, POPCNT.(POW3) P3CNT POW3 = POW3 * 3 VECTOR VALUES P3FMT = $15HPOP COUNT OF 3^,I2,2H: ,I3*$   R EVIL AND ODIOUS NUMBERS PRINT COMMENT$ $ PRINT COMMENT$ FIRST 30 EVIL NUMBERS ARE$ SEEN = 1 THROUGH EVIL, FOR I=0, 1, SEEN.GE.30 WHENEVER LOWBIT.(POPCNT.(I)).E.0 PRINT FORMAT NUMFMT,I SEEN = SEEN + 1 EVIL END OF CONDITIONAL   PRINT COMMENT$ $ PRINT COMMENT$ FIRST 30 ODIOUS NUMBERS ARE$ SEEN = 1 THROUGH ODIOUS, FOR I=0, 1, SEEN.GE.30 WHENEVER LOWBIT.(POPCNT.(I)).E.1 PRINT FORMAT NUMFMT,I SEEN = SEEN + 1 ODIOUS END OF CONDITIONAL   VECTOR VALUES NUMFMT = $I2*$ END OF PROGRAM
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.
#TI-83_BASIC
TI-83 BASIC
DelVar X seq(X,X,0,10) → L1 {1,6,17,34,57,86,121,162,209,262,321} → L2 QuadReg L1,L2
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.
#Maxima
Maxima
powerset({1, 2, 3, 4}); /* {{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 4}, {1, 3}, {1, 3, 4}, {1, 4}, {2}, {2, 3}, {2, 3, 4}, {2, 4}, {3}, {3, 4}, {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.
#Nim
Nim
import sets, hashes   proc hash(x: HashSet[int]): Hash = var h = 0 for i in x: h = h !& hash(i) result = !$h   proc powerset[T](inset: HashSet[T]): HashSet[HashSet[T]] = result.incl(initHashSet[T]()) # Initialized with empty set. for val in inset: let previous = result for aSet in previous: var newSet = aSet newSet.incl(val) result.incl(newSet)   echo powerset([1,2,3,4].toHashSet())
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPrime(n As Integer) As Boolean If n < 2 Then Return False If n = 2 Then Return True If n Mod 2 = 0 Then Return False Dim limit As Integer = Sqr(n) For i As Integer = 3 To limit Step 2 If n Mod i = 0 Then Return False Next Return True End Function   ' To test this works, print all primes under 100 For i As Integer = 1 To 99 If isPrime(i) Then Print Str(i); " "; End If Next   Print : Print Print "Press any key to quit" Sleep
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
#PowerShell
PowerShell
  function Convert-PriceFraction { [CmdletBinding()] [OutputType([double])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateScript({$_ -ge 0.0 -and $_ -le 1.0})] [double] $InputObject )   Process { foreach ($fraction in $InputObject) { switch ($fraction) { {$_ -lt 0.06} {0.10; break} {$_ -lt 0.11} {0.18; break} {$_ -lt 0.16} {0.26; break} {$_ -lt 0.21} {0.32; break} {$_ -lt 0.26} {0.38; break} {$_ -lt 0.31} {0.44; break} {$_ -lt 0.36} {0.50; break} {$_ -lt 0.41} {0.54; break} {$_ -lt 0.46} {0.58; break} {$_ -lt 0.51} {0.62; break} {$_ -lt 0.56} {0.66; break} {$_ -lt 0.61} {0.70; break} {$_ -lt 0.66} {0.74; break} {$_ -lt 0.71} {0.78; break} {$_ -lt 0.76} {0.82; break} {$_ -lt 0.81} {0.86; break} {$_ -lt 0.86} {0.90; break} {$_ -lt 0.91} {0.94; break} {$_ -lt 0.96} {0.98; break} Default {1.00} } } } }  
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 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
#Ruby
Ruby
require "prime"   class Integer def proper_divisors return [] if self == 1 primes = prime_division.flat_map{|prime, freq| [prime] * freq} (1...primes.size).each_with_object([1]) do |n, res| primes.combination(n).map{|combi| res << combi.inject(:*)} end.flatten.uniq end end   (1..10).map{|n| puts "#{n}: #{n.proper_divisors}"}   size, select = (1..20_000).group_by{|n| n.proper_divisors.size}.max select.each do |n| puts "#{n} has #{size} divisors" 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.
#Stata
Stata
mata struct Node { real scalar time transmorphic data } class Heap { public: struct Node rowvector nodes real scalar len real scalar size real scalar minHeap void new() void push() void siftup() void siftdown() struct Node scalar pop() real scalar empty() real scalar compare() } real scalar Heap::compare(a,b) { struct Node scalar left, right left = nodes[a] right = nodes[b] return(minHeap ? left.time<right.time : left.time>right.time) } void Heap::new() { len = 0 size = 4 nodes = Node(1,size) minHeap = 1 // defaults to min heap } real scalar Heap::empty() { return(len==0) } void Heap::siftdown(real scalar index) { parent = index while (parent*2 <= len) { child = parent*2 if (child+1 <= len ? compare(child+1,child) : 0) { child++ } if (compare(child,parent)) { nodes[(child,parent)] = nodes[(parent,child)] parent = child } else break } } void Heap::siftup(real scalar index) { child = index while(child>1) { parent = floor(child/2) if (compare(parent,child)) { break } nodes[(child,parent)] = nodes[(parent,child)] temp = child child = parent parent = temp } } void Heap::push (real scalar time, transmorphic data) { if (len + 1 >= size) { nodes = (nodes, nodes) size = size*2 } len++ nodes[len].time = time nodes[len].data = data siftup(len) } struct Node scalar Heap::pop () { if (len==0) { _error(3000,"empty heap") } len-- struct Node scalar newnode newnode.time = nodes[1].time newnode.data = nodes[1].data if (len>0) { nodes[1] = nodes[len+1] siftdown(1) } return(newnode) } void testHeap(real scalar minHeap) { class Heap scalar h struct Node scalar node h = Heap() h.minHeap = minHeap h.push(3, "Clear drains") h.push(4, "Feed cat") h.push(5, "Make tea") h.push(1, "Solve RC tasks") h.push(2, "Tax return") while (!h.empty()) { node = h.pop() printf("%f -> %s\n", node.time, node.data) } } testHeap(1) testHeap(0) end  
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
#MATLAB
MATLAB
function [outputPrimeDecomposition] = primedecomposition(inputValue) outputPrimeDecomposition = factor(inputValue);
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.
#Scilab
Scilab
--> 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]; --> plot2d(x,y)
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Sidef
Sidef
require('GD::Graph::points')   var data = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0], ]   var graph = %s'GD::Graph::points'.new(400, 300) var gd = graph.plot(data)   var format = 'png' File("qsort-range.#{format}").write(gd.(format), :raw)
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
#Python
Python
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)   class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
popcount[n_Integer] := IntegerDigits[n, 2] // Total Print["population count of powers of 3"] popcount[#] & /@ (3^Range[0, 30]) (*******) evilQ[n_Integer] := popcount[n] // EvenQ evilcount = 0; evillist = {}; i = 0; While[evilcount < 30, If[evilQ[i], AppendTo[evillist, i]; evilcount++]; i++ ] Print["first thirty evil numbers"] evillist (*******) odiousQ[n_Integer] := popcount[n] // OddQ odiouscount = 0; odiouslist = {}; i = 0; While[odiouscount < 30, If[odiousQ[i], AppendTo[odiouslist, i]; odiouscount++]; i++ ] Print["first thirty odious numbers"] odiouslist
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.
#TI-89_BASIC
TI-89 BASIC
DelVar x seq(x,x,0,10) → xs {1,6,17,34,57,86,121,162,209,262,321} → ys QuadReg xs,ys Disp regeq(x)
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.
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   + (NSArray *)powerSetForArray:(NSArray *)array { UInt32 subsetCount = 1 << array.count; NSMutableArray *subsets = [NSMutableArray arrayWithCapacity:subsetCount]; for(int subsetIndex = 0; subsetIndex < subsetCount; subsetIndex++) { NSMutableArray *subset = [[NSMutableArray alloc] init]; for (int itemIndex = 0; itemIndex < array.count; itemIndex++) { if((subsetIndex >> itemIndex) & 0x1) { [subset addObject:array[itemIndex]]; } } [subsets addObject:subset]; } return subsets; }
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
#Frink
Frink
isPrimeByTrialDivision[x] := { for p = primes[] { if p*p > x return true if x mod p == 0 return false }   return true }
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
#PureBasic
PureBasic
Procedure.f PriceFraction(price.f) ;returns price unchanged if value is invalid Protected fraction Select price * 100 Case 0 To 5 fraction = 10 Case 06 To 10 fraction = 18 Case 11 To 15 fraction = 26 Case 16 To 20 fraction = 32 Case 21 To 25 fraction = 38 Case 26 To 30 fraction = 44 Case 31 To 35 fraction = 5 Case 36 To 40 fraction = 54 Case 41 To 45 fraction = 58 Case 46 To 50 fraction = 62 Case 51 To 55 fraction = 66 Case 56 To 60 fraction = 7 Case 61 To 65 fraction = 74 Case 66 To 70 fraction = 78 Case 71 To 75 fraction = 82 Case 76 To 80 fraction = 86 Case 81 To 85 fraction = 9 Case 86 To 90 fraction = 94 Case 91 To 95 fraction = 98 Case 96 To 100 fraction = 100 Default ProcedureReturn price EndSelect   ProcedureReturn fraction / 100 EndProcedure   If OpenConsole() Define x.f, i   For i = 1 To 10 x = Random(10000)/10000 PrintN(StrF(x, 4) + " -> " + StrF(PriceFraction(x), 2)) Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
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
#Rust
Rust
trait ProperDivisors { fn proper_divisors(&self) -> Option<Vec<u64>>; }   impl ProperDivisors for u64 { fn proper_divisors(&self) -> Option<Vec<u64>> { if self.le(&1) { return None; } let mut divisors: Vec<u64> = Vec::new();   for i in 1..*self { if *self % i == 0 { divisors.push(i); } } Option::from(divisors) } }   fn main() { for i in 1..11 { println!("Proper divisors of {:2}: {:?}", i, i.proper_divisors().unwrap_or(vec![])); }   let mut most_idx: u64 = 0; let mut most_divisors: Vec<u64> = Vec::new(); for i in 1..20_001 { let divs = i.proper_divisors().unwrap_or(vec![]); if divs.len() > most_divisors.len() { most_divisors = divs; most_idx = i; } } println!("In 1 to 20000, {} has the most proper divisors at {}", most_idx, most_divisors.len()); }  
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.
#Swift
Swift
class Task : Comparable, CustomStringConvertible { var priority : Int var name: String init(priority: Int, name: String) { self.priority = priority self.name = name } var description: String { return "\(priority), \(name)" } } func ==(t1: Task, t2: Task) -> Bool { return t1.priority == t2.priority } func <(t1: Task, t2: Task) -> Bool { return t1.priority < t2.priority }   struct TaskPriorityQueue { let heap : CFBinaryHeapRef = { var callBacks = CFBinaryHeapCallBacks(version: 0, retain: { UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque()) }, release: { Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release() }, copyDescription: nil, compare: { (ptr1, ptr2, _) in let t1 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue() let t2 : Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue() return t1 == t2 ? CFComparisonResult.CompareEqualTo : t1 < t2 ? CFComparisonResult.CompareLessThan : CFComparisonResult.CompareGreaterThan }) return CFBinaryHeapCreate(nil, 0, &callBacks, nil) }() var count : Int { return CFBinaryHeapGetCount(heap) } mutating func push(t: Task) { CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque())) } func peek() -> Task { return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue() } mutating func pop() -> Task { let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue() CFBinaryHeapRemoveMinimumValue(heap) return result } }   var pq = TaskPriorityQueue()   pq.push(Task(priority: 3, name: "Clear drains")) pq.push(Task(priority: 4, name: "Feed cat")) pq.push(Task(priority: 5, name: "Make tea")) pq.push(Task(priority: 1, name: "Solve RC tasks")) pq.push(Task(priority: 2, name: "Tax return"))   while pq.count != 0 { print(pq.pop()) }
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
#Maxima
Maxima
(%i1) display2d: false$ /* disable rendering exponents as superscripts */ (%i2) factor(2016); (%o2) 2^5*3^2*7  
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Stata
Stata
clear input x y 0 2.7 1 2.8 2 31.4 3 38.1 4 58.0 5 76.2 6 100.5 7 130.0 8 149.3 9 180.0 end   lines y x graph export image.png
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.
#Tcl
Tcl
package require Tk   # The actual plotting engine proc plotxy {canvas xs ys} { global xfac yfac set maxx [tcl::mathfunc::max {*}$xs] set maxy [tcl::mathfunc::max {*}$ys] set xfac [expr {[winfo width $canvas] * 0.8/$maxx}] set yfac [expr {[winfo height $canvas] * 0.8/$maxy}] scale $canvas x 0 $maxx $xfac scale $canvas y 0 $maxy $yfac foreach x $xs y $ys { dot $canvas [expr {$x*$xfac}] [expr {$y*$yfac}] -fill red } } # Rescales the contents of the given canvas proc scale {canvas direction from to fac} { set f [expr {$from*$fac}] set t [expr {$to*$fac}] switch -- $direction { x { set f [expr {$from * $fac}] set t [expr {$to * $fac}] $canvas create line $f 0 $t 0 $canvas create text $f 0 -anchor nw -text $from $canvas create text $t 0 -anchor n -text $to   } y { set f [expr {$from * -$fac}] set t [expr {$to * -$fac}] $canvas create line 0 $f 0 $t $canvas create text 0 $f -anchor se -text $from $canvas create text 0 $t -anchor e -text $to } } } # Helper to make points, which are otherwise not a native item type proc dot {canvas x y args} { set id [$canvas create oval [expr {$x-3}] [expr {-$y-3}] \ [expr {$x+3}] [expr {-$y+3}]] $canvas itemconfigure $id {*}$args }   pack [canvas .c -background white] update set xs {0 1 2 3 4 5 6 7 8 9} set ys {2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0} plotxy .c $xs $ys .c config -scrollregion [.c bbox all] .c move all 20 20   # Save image (this is the only part that requires an external library) package require Img set im [image create photo -data .c] $im write plotxy.png -format 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
#R
R
setClass("point", representation( x="numeric", y="numeric"), prototype( x=0, y=0))   # Instantiate class with some arguments p1 <- new("point", x=3) # Access some values p1@x # 3 # Define a print method setMethod("print", signature("point"), function(x, ...) { cat("This is a point, with location, (", x@x, ",", x@y, ").\n") }) print(p1)   # Define a circle class setClass("circle", representation( centre="point", r="numeric"), prototype( centre=new("point"), r=1)) circS4 <- new("circle", r=5.5) # Access some values circS4@r # 5.5 circS4@centre@x # 0 # Define a print method setMethod("print", signature("circle"), function(x, ...) { cat("This is a circle, with radius", x@r, "and centre (", x@centre@x, ",", x@centre@y, ").\n") }) print(circS4)
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
#Racket
Racket
  #lang racket (define point% (class* object% (writable<%>) (super-new) (init-field [x 0] [y 0]) (define/public (copy) (new point% [x x] [y y])) (define/public (show) (format "<point% ~a ~a>" x y)) (define/public (custom-write out) (write (show) out)) (define/public (custom-display out) (display (show) out))))   (define circle% (class point% (super-new) (inherit-field x y) (init-field [r 0]) (define/override (copy) (new circle% [x x] [y y] [r r])) (define/override (show) (format "<circle% ~a ~a>" (super show) r)) (define/override (custom-write out) (write (show) out)) (define/override (custom-display out) (display (show) out))))  
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.
#min
min
(2 over over mod 'div dip) :divmod2   (  :n () =list (n 0 >) (n divmod2 list append #list @n) while list (1 ==) filter size ) :pop-count   (:n 0 () (over swap append 'succ dip) n times) :iota   "3^n: " print! 30 iota (3 swap pow int pop-count) map puts! 60 iota (pop-count odd?) partition "Evil: " print! puts! "Odious: " print! puts!
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.
#Ursala
Ursala
#import std #import nat #import flo   (fit "n") ("x","y") = ..dgelsd\"y" (gang \/*pow float*x iota successor "n")* "x"
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.
#OCaml
OCaml
module PowerSet(S: Set.S) = struct   include Set.Make (S)   let map f s = let work x r = add (f x) r in fold work s empty ;;   let powerset s = let base = singleton (S.empty) in let work x r = union r (map (S.add x) r) in S.fold work s base ;;   end;; (* PowerSet *)
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
#FunL
FunL
import math.sqrt   def isPrime( 2 ) = true isPrime( n ) | n < 3 or 2|n = false | otherwise = (3..int(sqrt(n)) by 2).forall( (/|n) )   (10^10..10^10+50).filter( isPrime ).foreach( println )
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
#Python
Python
>>> import bisect >>> _cin = [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01] >>> _cout = [.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00] >>> def pricerounder(pricein): return _cout[ bisect.bisect_right(_cin, pricein) ]
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
#S-BASIC
S-BASIC
  $lines   $constant false = 0 $constant true = FFFFH   rem - compute p mod q function mod(p, q = integer) = integer end = p - q * (p/q)   rem - count, and optionally display, proper divisors of n function divisors(n, display = integer) = integer var i, limit, count, start, delta = integer if mod(n, 2) = 0 then begin start = 2 delta = 1 end else begin start = 3 delta = 2 end if n < 2 then count = 0 else count = 1 if display and (count = 1) then print using "#####"; 1; i = start limit = n / start while i <= limit do begin if mod(n, i) = 0 then begin if display then print using "#####"; i; count = count + 1 end i = i + delta if count = 1 then limit = n / i end if display then print end = count   rem - main program begins here var i, ndiv, highdiv, highnum = integer   print "Proper divisors of first 10 numbers:" for i = 1 to 10 print using "### : "; i; ndiv = divisors(i, true) next i   print "Searching for number with most divisors ..." highdiv = 1 highnum = 1 for i = 1 to 20000 ndiv = divisors(i, false) if ndiv > highdiv then begin highdiv = ndiv highnum = i end next i print "Searched up to"; i print highnum; " has the most divisors: "; highdiv   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.
#Tcl
Tcl
package require struct::prioqueue   set pq [struct::prioqueue] foreach {priority task} { 3 "Clear drains" 4 "Feed cat" 5 "Make tea" 1 "Solve RC tasks" 2 "Tax return" } { # Insert into the priority queue $pq put $task $priority } # Drain the queue, in priority-sorted order while {[$pq size]} { # Remove the front-most item from the priority queue puts [$pq get] }
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
#MUMPS
MUMPS
ERATO1(HI) SET HI=HI\1 KILL ERATO1 ;Don't make it new - we want it to remain after the quit NEW I,J,P FOR I=2:1:(HI**.5)\1 DO .FOR J=I*I:I:HI DO ..SET P(J)=1 ;$SELECT($DATA(P(J))#10:P(J)+1,1:1)  ;WRITE !,"Prime numbers between 2 and ",HI,": " FOR I=2:1:HI DO .S:'$DATA(P(I)) ERATO1(I)=I ;WRITE $SELECT((I<3):"",1:", "),I KILL I,J,P QUIT PRIMDECO(N)  ;Returns its results in the string PRIMDECO  ;Kill that before the first call to this recursive function QUIT:N<=1 IF $D(PRIMDECO)=1 SET PRIMDECO="" D ERATO1(N) SET N=N\1,I=0 FOR SET I=$O(ERATO1(I)) Q:+I<1 Q:'(N#I) IF I>1 SET PRIMDECO=$S($L(PRIMDECO)>0:PRIMDECO_"^",1:"")_I D PRIMDECO(N/I)  ;that is, if I is a factor of N, add it to the string QUIT
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.
#TI-89_BASIC
TI-89 BASIC
FnOff PlotsOff NewPlot 1, 1, x, y ZoomData
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.
#Ursala
Ursala
#import std #import flo #import fit #import plo   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>   #output dot'tex' latex_document+ plot   main = visualization[curves: <curve[points: ~&p/x y]>]
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Raku
Raku
class Point { has Real $.x is rw = 0; has Real $.y is rw = 0; method Str { $ } }   class Circle { has Point $.p is rw = Point.new; has Real $.r is rw = 0; method Str { $ } }   my $c = Circle.new(p => Point.new(x => 1, y => 2), r => 3); say $c; $c.p.x = (-10..10).pick; $c.p.y = (-10..10).pick; $c.r = (0..10).pick; say $c;
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.
#Nim
Nim
import bitops import strformat   var n = 1 write(stdout, "3^x  :") for i in 0..<30: write(stdout, fmt"{popcount(n):2} ") n *= 3   var od: array[30, int] var ne, no = 0 n = 0 write(stdout, "\nevil  :") while ne + no < 60: if (popcount(n) and 1) == 0: if ne < 30: write(stdout, fmt"{n:2} ") inc ne else: if no < 30: od[no] = n inc no inc n   write(stdout, "\nodious:") for i in 0..<30: write(stdout, fmt"{od[i]:2} ") write(stdout, '\n')
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#VBA
VBA
Option Base 1 Private Function polynomial_regression(y As Variant, x As Variant, degree As Integer) As Variant Dim a() As Double ReDim a(UBound(x), 2) For i = 1 To UBound(x) For j = 1 To degree a(i, j) = x(i) ^ j Next j Next i polynomial_regression = WorksheetFunction.LinEst(WorksheetFunction.Transpose(y), a, True, True) End Function Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}] y = [{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}] result = polynomial_regression(y, x, 2) Debug.Print "coefficients  : "; For i = UBound(result, 2) To 1 Step -1 Debug.Print Format(result(1, i), "0.#####"), Next i Debug.Print Debug.Print "standard errors: "; For i = UBound(result, 2) To 1 Step -1 Debug.Print Format(result(2, i), "0.#####"), Next i Debug.Print vbCrLf Debug.Print "R^2 ="; result(3, 1) Debug.Print "F ="; result(4, 1) Debug.Print "Degrees of freedom:"; result(4, 2) Debug.Print "Standard error of y estimate:"; result(3, 2) End Sub
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.
#OPL
OPL
  {string} s={"A","B","C","D"}; range r=1.. ftoi(pow(2,card(s))); {string} s2 [k in r] = {i | i in s: ((k div (ftoi(pow(2,(ord(s,i))))) mod 2) == 1)};   execute { writeln(s2); }  
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
#FutureBasic
FutureBasic
window 1, @"Primality By Trial Division", (0,0,480,270)   local fn isPrime( n as long ) as Boolean long i Boolean result   if n < 2 then result = NO : exit fn if n = 2 then result = YES : exit fn if n mod 2 == 0 then result = NO : exit fn   result = YES for i = 3 to int( n^.5 ) step 2 if n mod i == 0 then result = NO : break next i end fn = result   long i, j = 0   print "Prime numbers between 0 and 1000:" for i = 0 to 1000 if ( fn isPrime(i) != _false ) printf @"%3d\t",i : j++ if j mod 10 == 0 then print end if next   HandleEvents
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
#Quackery
Quackery
[ $ 'bigrat.qky' loadfile ] now!   [ 2over 2over v< if 2swap 2drop ] is vmax ( n/d n/d --> n/d )   [ 100 1 v* 1 1 v- 0 1 vmax 5 1 v/ / [ table 10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100 ] 100 ] is scale ( n/d --> n/d )   [ swap echo sp echo ] is br ( n/d --> )   [ 2dup br say ' --> ' scale br cr ] is test ( n/d --> )   0 100 test 50 100 test 65 100 test 66 100 test 100 100 test 7368 10000 test   ( Show how to enter and display results as a decimal too. ) $ '0.7368' dup echo$ say ' --> ' $->v drop scale 2 point$ echo$
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
#Scala
Scala
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}"   println(f" n cnt PROPER DIVISORS") val (count, list) = (1 to 20000).foldLeft( (0, List[Int]()) ) { (max, i) => val divisors = properDivisors(i) if (i <= 10 || i == 100) println( format(i, divisors) ) if (max._1 < divisors.length) (divisors.length, List(i)) else if (max._1 == divisors.length) (divisors.length, max._2 ::: List(i)) else max }   list.foreach( number => println(f"$number%5d ${properDivisors(number).length}") )
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.
#VBA
VBA
Type Tuple Priority As Integer Data As String End Type Dim a() As Tuple Dim n As Integer 'number of elements in array, last element is n-1 Private Function Left(i As Integer) As Integer Left = 2 * i + 1 End Function Private Function Right(i As Integer) As Integer Right = 2 * i + 2 End Function Private Function Parent(i As Integer) As Integer Parent = (i - 1) \ 2 End Function Private Sub Add(fPriority As Integer, fData As String) n = n + 1 If n > UBound(a) Then ReDim Preserve a(2 * n) a(n - 1).Priority = fPriority a(n - 1).Data = fData bubbleUp (n - 1) End Sub Private Sub Swap(i As Integer, j As Integer) Dim t As Tuple t = a(i) a(i) = a(j) a(j) = t End Sub Private Sub bubbleUp(i As Integer) Dim p As Integer p = Parent(i) Do While i > 0 And a(i).Priority < a(p).Priority Swap i, p i = p p = Parent(i) Loop End Sub Private Function Remove() As Tuple Dim x As Tuple x = a(0) a(0) = a(n - 1) n = n - 1 trickleDown 0 If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2) Remove = x End Function Private Sub trickleDown(i As Integer) Dim j As Integer, l As Integer, r As Integer Do j = -1 r = Right(i) If r < n And a(r).Priority < a(i).Priority Then l = Left(i) If a(l).Priority < a(r).Priority Then j = l Else j = r End If Else l = Left(i) If l < n And a(l).Priority < a(i).Priority Then j = l End If If j >= 0 Then Swap i, j i = j Loop While i >= 0 End Sub Public Sub PQ() ReDim a(4) Add 3, "Clear drains" Add 4, "Feed cat" Add 5, "Make tea" Add 1, "Solve RC tasks" Add 2, "Tax return" Dim t As Tuple Do While n > 0 t = Remove Debug.Print t.Priority, t.Data Loop End Sub
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
#Nim
Nim
import math, sequtils, strformat, strutils, times   proc getStep(n: int64): int64 {.inline.} = result = 1 + n shl 2 - n shr 1 shl 1   proc primeFac(n: int64): seq[int64] = var maxq = int64(sqrt(float(n))) var d = 1 var q: int64 = 2 + (n and 1) # Start with 2 or 3 according to oddity. while q <= maxq and n %% q != 0: q = getStep(d) inc d if q <= maxq: let q1 = primeFac(n /% q) let q2 = primeFac(q) result = concat(q2, q1, result) else: result.add(n)   iterator primes(limit: int): int = var isPrime = newSeq[bool](limit + 1) for n in 2..limit: isPrime[n] = true for n in 2..limit: if isPrime[n]: yield n for i in countup(n *% n, limit, n): isPrime[i] = false   when isMainModule:   # Example: calculate factors of Mersenne numbers from M2 to M59. for m in primes(59): let p = 2i64^m - 1 let s = &"2^{m}-1" stdout.write &"{s:<6} = {p} with factors: " let start = cpuTime() stdout.write primeFac(p).join(", ") echo &" => {(1000 * (cpuTime() - start)).toInt} ms"
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.
#VBA
VBA
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
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.
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window import "math" for Point   class PlotCoordinates { construct new(width, height) { Window.title = "Plot coordinates" Window.resize(width, height) Canvas.resize(width, height) _width = width _height = height }   init() { var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] var y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] plotCoordinates(x, y) }   plotCoordinates(x, y) { var n = x.count // draw axes Canvas.line(40, _height - 40, _width - 40, _height - 40, Color.blue, 2) Canvas.line(40, _height - 40, 40, 40, Color.blue, 2) var length = 40 * n var div = length / 10 var j = 0 for (i in 0..9) { var p = Point.new(40 + j, _height - 40) Canvas.print(i.toString, p.x - 4, p.y + 4, Color.white) j = j + div } j = div for (i in 1..9) { var p = Point.new(10, _height - 40 - j) var s = (i * 20).toString if (s.count == 2) s = " " + s Canvas.print(s, p.x, p.y, Color.white) j = j + div } Canvas.print("X", _width - 44, _height - 36, Color.green) Canvas.print("Y", 20, 40, Color.green)   // plot points var xStart = 40 var xScale = 40 var yStart = 40 var yScale = 2 var points = List.filled(n, null) for (i in 0...n) { points[i] = Point.new(xStart + x[i]*xScale, _height - yStart - y[i]*yScale) } Canvas.circlefill(points[0].x, points[0].y, 3, Color.red) for (i in 1...n) { Canvas.line(points[i-1].x, points[i-1].y, points[i].x, points[i].y, Color.red) Canvas.circlefill(points[i].x, points[i].y, 3, Color.red) } }   update() {}   draw(alpha) {} }   var Game = PlotCoordinates.new(500, 500)
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
#Ruby
Ruby
class Point attr_accessor :x,:y def initialize(x=0, y=0) self.x = x self.y = y end def to_s "Point at #{x},#{y}" end end   # When defining Circle class as the sub-class of the Point class: class Circle < Point attr_accessor :r def initialize(x=0, y=0, r=0) self.x = x self.y = y self.r = r end def to_s "Circle at #{x},#{y} with radius #{r}" end end
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.
#Oforth
Oforth
: popcount(n) 0 while ( n ) [ n isOdd + n bitRight(1) ->n ] ;   : test | i count | 30 seq map(#[ 3 swap 1- pow ]) map(#popcount) println   0 ->count 0 while( count 30 <> ) [ dup popcount isEven ifTrue: [ dup . count 1+ ->count ] 1+ ] drop printcr   0 ->count 0 while( count 30 <> ) [ dup popcount isOdd ifTrue: [ dup . count 1+ ->count ] 1+ ] drop ;
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.
#Wren
Wren
import "/math" for Nums import "/seq" for Lst import "/fmt" for Fmt   var polynomialRegression = Fn.new { |x, y| var xm = Nums.mean(x) var ym = Nums.mean(y) var x2m = Nums.mean(x.map { |e| e * e }) var x3m = Nums.mean(x.map { |e| e * e * e }) var x4m = Nums.mean(x.map { |e| e * e * e * e }) var z = Lst.zip(x, y) var xym = Nums.mean(z.map { |p| p[0] * p[1] }) var x2ym = Nums.mean(z.map { |p| p[0] * p[0] * p[1] })   var sxx = x2m - xm * xm var sxy = xym - xm * ym var sxx2 = x3m - xm * x2m var sx2x2 = x4m - x2m * x2m var sx2y = x2ym - x2m * ym   var b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) var c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) var a = ym - b * xm - c * x2m   var abc = Fn.new { |xx| a + b * xx + c * xx * xx }   System.print("y = %(a) + %(b)x + %(c)x^2\n") System.print(" Input Approximation") System.print(" x y y1") for (p in z) Fmt.print("$2d $3d $5.1f", p[0], p[1], abc.call(p[0])) }   var x = List.filled(11, 0) for (i in 1..10) x[i] = i var y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] polynomialRegression.call(x, y)
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.
#Oz
Oz
declare %% Given a set as a list, returns its powerset (again as a list) fun {Powerset Set} proc {Describe Root} %% Describe sets by lower bound (nil) and upper bound (Set) Root = {FS.var.bounds nil Set} %% enumerate all possible sets {FS.distribute naive [Root]} end AllSets = {SearchAll Describe} in %% convert to list representation {Map AllSets FS.reflect.lowerBoundList} end in {Inspect {Powerset [1 2 3 4]}}
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks   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
#Gambas
Gambas
'Reworked from the BBC Basic example   Public Sub Main() Dim iNum As Integer   For iNum = 1 To 100 If FNisprime(iNum) Then Print iNum & " is prime" Next   End '___________________________________________________ Public Sub FNisprime(iNum As Integer) As Boolean Dim iLoop As Integer Dim bReturn As Boolean = True   If iNum <= 1 Then bReturn = False If iNum <= 3 Then bReturn = True If (iNum And 1) = 0 Then bReturn = False   For iLoop = 3 To Sqr(iNum) Step 2 If iNum Mod iLoop = 0 Then bReturn = False Next   Return bReturn   End
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
#R
R
  price_fraction <- function(x) { stopifnot(all(x >= 0 & x <= 1)) breaks <- seq(0.06, 1.01, 0.05) values <- c(.1, .18, .26, .32, .38, .44, .5, .54, .58, .62, .66, .7, .74, .78, .82, .86, .9, .94, .98, 1) indices <- sapply(x, function(x) which(x < breaks)[1]) values[indices] }   #Example usage: price_fraction(c(0, .01, 0.06, 0.25, 1)) # 0.10 0.10 0.18 0.38 1.00  
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
#Racket
Racket
  #lang racket   (define table '([0 #f] [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])    ;; returns #f for negatives or values >= 1.01 (define (convert x) (for/or ([c table]) (and (< x (car c)) (cadr c))))  
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: writeProperDivisors (in integer: n) is func local var integer: i is 0; begin for i range 1 to n div 2 do if n rem i = 0 then write(i <& " "); end if; end for; writeln; end func;   const func integer: countProperDivisors (in integer: n) is func result var integer: count is 0; local var integer: i is 0; begin for i range 1 to n div 2 step succ(n rem 2) do if n rem i = 0 then incr(count); end if; end for; end func;   const proc: main is func local var integer: i is 0; var integer: v is 0; var integer: max is 0; var integer: max_i is 1; begin for i range 1 to 10 do write(i <& ": "); writeProperDivisors(i); end for; for i range 1 to 20000 do v := countProperDivisors(i); if v > max then max := v; max_i := i; end if; end for; writeln(max_i <& " with " <& max <& " divisors"); end func;
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.
#VBScript
VBScript
  option explicit Class prio_queue private size private q   'adapt this function to your data private function out_of_order(f1,f2): out_of_order = f1(0)>f2(0):end function   function peek peek=q(1) end function   property get qty qty=size end property   property get isempty isempty=(size=0) end property   function remove dim x x=q(1) q(1)=q(size) size=size-1 sift_down remove=x end function   sub add (x) size=size+1 if size>ubound(q) then redim preserve q(ubound(q)*1.1) q(size)=x sift_up end sub   Private sub swap (i,j) dim x x=q(i):q(i)=q(j):q(j)=x end sub   private sub sift_up dim h,p h=size p=h\2 if p=0 then exit sub while out_of_order(q(p),q(h)) swap h,p h=p p=h\2 if p=0 then exit sub wend end sub   end sub   private sub sift_down dim p,h p=1 do if p>=size then exit do h =p*2 if h >size then exit do if h+1<=size then if out_of_order(q(h),q(h+1)) then h=h+1 if out_of_order(q(p),q(h)) then swap h,p p=h loop end sub   'Al instanciar objeto con New Private Sub Class_Initialize( ) redim q(100) size=0 End Sub   'When Object is Set to Nothing Private Sub Class_Terminate( ) erase q End Sub End Class '------------------------------------- 'test program '--------------------------------- dim tasks:tasks=array(_ array(3,"Clear drains"),_ array(4,"Feed cat"),_ array(5,"Make tea"),_ array(1,"Solve RC tasks"),_ array(2,"Tax return"))   dim queue,i,x set queue=new prio_queue for i=0 to ubound(tasks) queue.add(tasks(i)) next   wscript.echo "Done: " & queue.qty() &" items in queue. "& queue.peek()(1)& " is at the top." & vbcrlf   while not queue.isempty() x=queue.remove() wscript.echo x(0),x(1) wend   set queue= nothing    
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
#OCaml
OCaml
open Big_int;;   let prime_decomposition x = let rec inner c p = if lt_big_int p (square_big_int c) then [p] else if eq_big_int (mod_big_int p c) zero_big_int then c :: inner c (div_big_int p c) else inner (succ_big_int c) p in inner (succ_big_int (succ_big_int zero_big_int)) x;;
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   def ScrW=640, ScrH=480, VidMode=$101; def Sx = ScrW/10, \pixels per horz grid line Sy = ScrH/10, \pixels per vert grid line Ox = (3+1+1)*8+2, \offset for horz grid: allow room for "180.0" Oy = ScrH-20; \offset for vert grid: allow room for labels int X, DataX; real Y, DataY, Gain; def Brown=6, LCyan=11;   [DataX:= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; DataY:= [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0];   SetVid(VidMode); for X:= 0 to 9 do \draw grid [Move(X*Sx+Ox, Oy); Line(X*Sx+Ox, Oy-9*Sy, Brown); \vert lines Move(Ox, Oy-X*Sy); Line(9*Sx+Ox, Oy-X*Sy, Brown); \horz lines ]; Format(3,1); Attrib(LCyan); \label grid Y:= 0.0; for X:= 0 to 9 do [Move(X*Sx+Ox-3, Oy+6); IntOut(6, X); \X axis Move(0, Oy-X*Sy-7); RlOut(6, Y); \Y axis Y:= Y + 20.0; ]; Gain:= float(Sy)/20.0; Move(DataX(0)*Sx+Ox, Oy-Fix(DataY(0)*Gain)); \plot points for X:= 1 to 9 do Line(DataX(X)*Sx+Ox, Oy-Fix(DataY(X)*Gain), LCyan);   if ChIn(1) then []; \wait for key SetVid(3); \restore text ]
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.
#Yorick
Yorick
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]; window, 0; plmk, y, x; window, 1; plg, y, x, marks=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
#Scala
Scala
object PointCircle extends App {   class Point(x: Int = 0, y: Int = 0) {   def copy(x: Int = this.x, y: Int = this.y): Point = new Point(x, y)   override def toString = s"Point x: $x, y: $y" }   object Point { def apply(x: Int = 0, y: Int = 0): Point = new Point(x, y) }   case class Circle(x: Int = 0, y: Int = 0, r: Int = 0) extends Point(x, y) {   def copy(r: Int): Circle = Circle(x, y, r)   override def toString = s"Circle x: $x, y: $y, r: $r" }   val p = Point() val c = Circle() println("Instantiated ", p) println("Instantiated ", c)   val q = Point(5, 6) println("Instantiated ", q) val r = q.copy(y = 7) // change y coordinate println(r, " changed y coordinate")   val d = Circle(5, 6, 7) println("Instantiated ", d) val e = d.copy(r = 8) // change radius println(e, " changed radius")   }
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.
#PARI.2FGP
PARI/GP
vector(30,n,hammingweight(3^(n-1))) od=select(n->hammingweight(n)%2,[0..100]); ev=setminus([0..100],od); ev[1..30] od[1..30]
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.
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) xs:=GSL.VectorFromData(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ys:=GSL.VectorFromData(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321); v :=GSL.polyFit(xs,ys,2); v.format().println(); GSL.Helpers.polyString(v).println(); GSL.Helpers.polyEval(v,xs).format().println();
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.
#PARI.2FGP
PARI/GP
vector(1<<#S,i,vecextract(S,i-1))
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or 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.
#Perl
Perl
use Algorithm::Combinatorics "subsets"; my @S = ("a","b","c"); my @PS; my $iter = subsets(\@S); while (my $p = $iter->next) { push @PS, "[@$p]" } say join(" ",@PS);
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
#GAP
GAP
IsPrimeTrial := function(n) local k, m; if n < 5 then return (n = 2) or (n = 3); fi; if RemInt(n, 2) = 0 then return false; fi; m := RootInt(n); k := 3; while k <= m do if RemInt(n, k) = 0 then return false; fi; k := k + 2; od; return true; end;   Filtered([1 .. 100], IsPrimeTrial); # [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]
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
#Raku
Raku
sub price-fraction ($n where 0..1) { when $n < 0.06 { 0.10 } when $n < 0.11 { 0.18 } when $n < 0.16 { 0.26 } when $n < 0.21 { 0.32 } when $n < 0.26 { 0.38 } when $n < 0.31 { 0.44 } when $n < 0.36 { 0.50 } when $n < 0.41 { 0.54 } when $n < 0.46 { 0.58 } when $n < 0.51 { 0.62 } when $n < 0.56 { 0.66 } when $n < 0.61 { 0.70 } when $n < 0.66 { 0.74 } when $n < 0.71 { 0.78 } when $n < 0.76 { 0.82 } when $n < 0.81 { 0.86 } when $n < 0.86 { 0.90 } when $n < 0.91 { 0.94 } when $n < 0.96 { 0.98 } default { 1.00 } }   while prompt("value: ") -> $value { say price-fraction(+$value); }
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
#Sidef
Sidef
func propdiv (n) { n.divisors.slice(0, -2) }   {|i| printf("%2d: %s\n", i, propdiv(i)) } << 1..10   var max = 0 var candidates = []   for i in (1..20_000) { var divs = propdiv(i).len if (divs > max) { candidates = [] max = divs } candidates << i if (divs == max) }   say "max = #{max}, candidates = #{candidates}"
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.
#Wren
Wren
import "/queue" for PriorityQueue   var tasks = PriorityQueue.new() tasks.push("Clear drains", 3) tasks.push("Feed cat", 4) tasks.push("Make tea", 5) tasks.push("Solve RC tasks", 1) tasks.push("Tax return", 2) while (!tasks.isEmpty) { var t = tasks.pop() System.print(t) }
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
#Octave
Octave
r = factor(120202039393)
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.
#zkl
zkl
#<<< cmd:=0'| #set term wxt # X11 unset key # Only one data set, so the key is uninformative   plot '-' # '-' can be replaced with a filename, to read data from that file. 0 2.7 1 2.8 2 31.4 3 38.1 4 68.0 5 76.2 6 100.5 7 130.0 8 149.3 9 180.0 e |; #<<<   gnuplot:=System.popen("gnuplot","w"); gnuplot.write(cmd); gnuplot.flush(); ask("Hit return to finish"); gnuplot.close();
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: GraphicObj is new interface;   const proc: print (in GraphicObj: aGraphicObj) is DYNAMIC;     const type: Point is new struct var integer: x is 0; var integer: y is 0; end struct;   type_implements_interface(Point, GraphicObj);   const func Point: Point (in integer: x, in integer: y) is func result var Point: newPoint is Point.value; begin newPoint.x := x; newPoint.y := y; end func;   const proc: print (in Point: aPoint) is func begin writeln("Point(" <& aPoint.x <& ", " <& aPoint.y <& ")"); end func;     const type: Circle is sub Point struct var integer: r is 0; end struct;   type_implements_interface(Circle, GraphicObj);   const func Circle: Circle (in integer: x, in integer: y, in integer: r) is func result var Circle: newCircle is Circle.value; begin newCircle.x := x; newCircle.y := y; newCircle.r := r; end func;   const proc: print (in Circle: aCircle) is func begin writeln("Circle(" <& aCircle.x <& ", " <& aCircle.y <& ", " <& aCircle.r <& ")"); end func;     const proc: main is func local var Point: pnt is Point(1, 2); var Circle: circ is Circle(3, 4, 5); var GraphicObj: graph is Point.value; begin graph := pnt; print(graph); graph := circ; print(graph); end func;
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
#Self
Self
traits point = (| parent* = traits clonable. printString = ('Point(', x asString, ':', y asString, ')'). |)   point = (| parent* = traits point. x <- 0. y <- 0 |)   traits circle = (| parent* = traits clonable. printString = ('Circle(', center asString, ',', r asString, ')'). |)   circle = (| parent* = traits circle. center <- point copy. r <- 0 |)
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.
#Pascal
Pascal
unit popcount; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ASMCSE,CSE,PEEPHOLE} {$Smartlink OFF} {$ENDIF}   interface function popcnt(n:Uint64):integer;overload; function popcnt(n:Uint32):integer;overload; function popcnt(n:Uint16):integer;overload; function popcnt(n:Uint8):integer;overload;   implementation const //K1 = $0101010101010101; K33 = $3333333333333333; K55 = $5555555555555555; KF1 = $0F0F0F0F0F0F0F0F; KF2 = $00FF00FF00FF00FF; KF4 = $0000FFFF0000FFFF; KF8 = $00000000FFFFFFFF; { function popcnt64(n:Uint64):integer; begin n := n- (n shr 1) AND K55; n := (n AND K33)+ ((n shr 2) AND K33); n := (n + (n shr 4)) AND KF1; n := (n*k1) SHR 56; result := n; end; } function popcnt(n:Uint64):integer;overload; // on Intel Haswell 2x faster for fpc 32-Bit begin n := (n AND K55)+((n shr 1) AND K55); n := (n AND K33)+((n shr 2) AND K33); n := (n AND KF1)+((n shr 4) AND KF1); n := (n AND KF2)+((n shr 8) AND KF2); n := (n AND KF4)+((n shr 16) AND KF4); n := (n AND KF8)+ (n shr 32); result := n; end;   function popcnt(n:Uint32):integer;overload; var c,b : NativeUint; begin b := n; c := (b shr 1) AND NativeUint(K55); b := (b AND NativeUint(K55))+C; c := ((b shr 2) AND NativeUint(K33));b := (b AND NativeUint(K33))+C; c:= ((b shr 4) AND NativeUint(KF1)); b := (b AND NativeUint(KF1))+c; c := ((b shr 8) AND NativeUint(KF2));b := (b AND NativeUint(KF2))+c; c := b shr 16; b := (b AND NativeUint(KF4))+ C; result := b; end;   function popcnt(n:Uint16):integer;overload; var c,b : NativeUint; begin b := n; c := (b shr 1) AND NativeUint(K55); b := (b AND NativeUint(K55))+C; c :=((b shr 2) AND NativeUint(K33)); b := (b AND NativeUint(K33))+C; c:= ((b shr 4) AND NativeUint(KF1)); b := (b AND NativeUint(KF1))+c; c := b shr 8; b := (b AND NativeUint(KF2))+c; result := b; end;   function popcnt(n:Uint8):integer;overload; var c,b : NativeUint; begin b := n; c := (b shr 1) AND NativeUint(K55); b := (b AND NativeUint(K55))+C; c :=((b shr 2) AND NativeUint(K33));b := (b AND NativeUint(K33))+C; c:= b shr 4; result := (b AND NativeUint(KF1))+c; end;   Begin 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.
#Phix
Phix
sequence powerset integer step = 1 function pst(object key, object /*data*/, object /*user_data*/) integer k = 1 while k<length(powerset) do k += step for j=1 to step do powerset[k] = append(powerset[k],key) k += 1 end for end while step *= 2 return 1 end function function power_set(integer d) powerset = repeat({},power(2,dict_size(d))) step = 1 traverse_dict(routine_id("pst"),0,d) return powerset end function integer d1234 = new_dict({{1,0},{2,0},{3,0},{4,0}}) ?power_set(d1234) integer d0 = new_dict() ?power_set(d0) setd({},0,d0) ?power_set(d0)
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
#Go
Go
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false   default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }