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....
#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 lis...
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...
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 ...
#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) { prin...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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 }...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 pow...
#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 ...
#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 ...
#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 ...
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 ...
#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,...
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...
#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 ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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 {...
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 ...
#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....
#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(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....
#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, poi...
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 ...
#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 = dec2...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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}] ...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 in...
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 ...
#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) ...
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 ...
#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) ...
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 ...
#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); decl...
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...
#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 insert...
#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,...
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 ...
#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....
#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, pre...
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...
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 ...
#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 ...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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 pow...
#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 pow...
#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...
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 ...
#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,...
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 ...
#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....
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...
#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| pu...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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 ...
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 ...
#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....
#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....
#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.ra...
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 ...
#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...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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 pow...
#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]...
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 ...
#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 ...
#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 Cas...
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...
#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 ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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.prio...
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 ...
#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....
#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....
#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 $ma...
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 i...
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...
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 ...
#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!...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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 pow...
#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 ...
#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 ...
#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, pr...
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...
#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 ...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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]} ...
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 ...
#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...
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....
#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....
#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...
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 ...
#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 ...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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.Lin...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 ...
#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 =...
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 ...
#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 ...
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...
#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(...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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 F...
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 ...
#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 %...
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....
#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 .SeriesCollecti...
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....
#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...
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 sel...
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 ...
#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...
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#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 }) ...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 A...
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 ...
#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 i...
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#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(...
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 ...
#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...
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...
#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...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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=...
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 ...
#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....
#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...
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....
#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...
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 ...
#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 i...
#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...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 pow...
#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 ...
#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;   Fil...
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 ...
#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 } ...
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...
#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}...
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#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 ...
#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....
#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",...
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, ...
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 = (| ...
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 ...
#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;   implem...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#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 ...
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 ...
#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 }