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/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Yabasic
Yabasic
;assumes this runs inline org &1000 ;program start main: call GetInput ;unimplemented input get routine, returns key press in accumulator cp 'Y' ;compare to ascii capital Y ret z ;return to BASIC if equal jp main ;loop back to main
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 ...
#Forth
Forth
: decomp ( n -- ) 2 begin 2dup dup * >= while 2dup /mod swap if drop 1+ 1 or \ next odd number else -rot nip dup . then repeat drop . ;
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Racket
Racket
  #lang racket   (define (inc! b) (set-box! b (add1 (unbox b))))   (define b (box 0)) (inc! b) (inc! b) (inc! b) (unbox b) ; => 3  
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Raku
Raku
my $foo = 42; # place a reference to 42 in $foo's item container $foo++; # deref $foo name, then increment the container's contents to 43 $foo.say; # deref $foo name, then $foo's container, and call a method on 43.   $foo := 42; # bind a direct ref to 42 $foo++; # ERROR, cannot modify i...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#REXX
REXX
/* Using ADDR to get memory address, and PEEKC / POKE. There is also PEEK for numeric values. */ data _null_; length a b c $4; adr_a=addr(a); adr_b=addr(b); adr_c=addr(c); a="ABCD"; b="EFGH"; c="IJKL"; b=peekc(adr_a,1); call poke(b,adr_c,1); put a b c; run;
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....
#J
J
require 'plot' X=: i.10 Y=: 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 'dot; pensize 2.4' plot X;Y
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Java
Java
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static dou...
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
#Go
Go
package main   import "fmt"   type point struct { x, y float64 }   type circle struct { x, y, r float64 }   type printer interface { print() }   func (p *point) print() { fmt.Println(p.x, p.y) }   func (c *circle) print() { fmt.Println(c.x, c.y, c.r) }   func main() { var i printer //...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Perl
Perl
  use strict; use warnings; use utf8; use feature 'say'; use open qw<:encoding(utf-8) :std>;   package Hand { sub describe { my $str = pop; my $hand = init($str); return "$str: INVALID" if !$hand; return analyze($hand); }   sub init { (my $str = lc shift) =~ tr/234567...
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 ...
#Delphi
Delphi
  program Population_count;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, Math;   function PopulationCount(AInt: UInt64): Integer; begin Result := 0; repeat inc(Result, (AInt and 1)); AInt := AInt div 2; until (AInt = 0); end;   var i, count: Integer; n: Double; popCount: Integer;   ...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Maple
Maple
  > p := randpoly( x ); # pick a random polynomial in x 5 4 3 2 p := -56 - 7 x + 22 x - 55 x - 94 x + 87 x   > rem( p, x^2 + 2, x, 'q' ); # remainder 220 + 169 x   > q; # quotient 3 2 ...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PolynomialQuotientRemainder[x^3-12 x^2-42,x-3,x]
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Sidef
Sidef
class T(value) { method display { say value; } }   class S(value) < T { method display { say value; } }   var obj1 = T("T"); var obj2 = S("S"); var obj3 = obj2.dclone; # make a deep clone of obj2   obj1.value = "foo"; # change the value of obj1 obj2.value = "bar"; ...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Slate
Slate
define: #T &parents: {Cloneable}.   define: #S &parents: {Cloneable}.   define: #obj1 -> T clone. define: #obj2 -> S clone.   obj1 printName. obj2 printName.
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Swift
Swift
class T { required init() { } // constructor used in polymorphic initialization must be "required" func identify() { println("I am a genuine T") } func copy() -> T { let newObj : T = self.dynamicType() // call an appropriate constructor here // then copy data into newObj as appropriate here // m...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data = Transpose@{Range[0, 10], {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}}; Fit[data, {1, x, x^2}, 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...
#FreeBASIC
FreeBASIC
Function ConjuntoPotencia(set() As String) As String If Ubound(set,1) > 31 Then Print "Set demasiado grande para representarlo como un entero" : Exit Function If Ubound(set,1) < 0 Then Print "{}": Exit Function ' Set vacío Dim As Integer i, j Dim As String s = "{" For i = Lbound(set) To (2 Shl Uboun...
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 ...
#CLU
CLU
isqrt = proc (s: int) returns (int) x0: int := s/2 if x0=0 then return(s) end x1: int := (x0 + s/x0)/2 while x1 < x0 do x0 := x1 x1 := (x0 + s/x0)/2 end return(x0) end isqrt   prime = proc (n: int) returns (bool) if n<=2 then return(n=2) end if n//2=0 then return(false) e...
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 ...
#Inform_7
Inform 7
Home is a room.   Price is a kind of value. 0.99 specifies a price.   Table of Price Standardization upper bound replacement 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....
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 ...
#J
J
le =: -0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0 out =: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1   priceFraction =: out {~ le I. -
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...
#Nim
Nim
import strformat   proc properDivisors(n: int) = var count = 0 for i in 1..<n: if n mod i == 0: inc count write(stdout, fmt"{i} ") write(stdout, "\n")   proc countProperDivisors(n: int): int = var nn = n var prod = 1 var count = 0 while nn mod 2 == 0: inc count nn = nn div 2 prod...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Rust
Rust
extern crate rand;   use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice}; use rand::{weak_rng, Rng};   const DATA: [(&str, f64); 8] = [ ("aleph", 1.0 / 5.0), ("beth", 1.0 / 6.0), ("gimel", 1.0 / 7.0), ("daleth", 1.0 / 8.0), ("he", 1.0 / 9.0), ("waw", 1.0 / 10.0), (...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Scala
Scala
object ProbabilisticChoice extends App { import scala.collection.mutable.LinkedHashMap   def weightedProb[A](prob: LinkedHashMap[A,Double]): A = { require(prob.forall{case (_, p) => p > 0 && p < 1}) assume(prob.values.sum == 1) def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A...
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...
#Perl
Perl
use 5.10.0; use strict; use Heap::Priority;   my $h = new Heap::Priority;   $h->highest_first(); # higher or lower number is more important $h->add(@$_) for ["Clear drains", 3], ["Feed cat", 4], ["Make tea", 5], ["Solve RC tasks", 1], ["Tax return", 2];   say while ($_ = $h->pop);
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Z80_Assembly
Z80 Assembly
;assumes this runs inline org &1000 ;program start main: call GetInput ;unimplemented input get routine, returns key press in accumulator cp 'Y' ;compare to ascii capital Y ret z ;return to BASIC if equal jp main ;loop back to main
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#zkl
zkl
if (die) System.exit(); if (die) System.exit(1); if (die) System.exit("dumping core");
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 ...
#Fortran
Fortran
module PrimeDecompose implicit none   integer, parameter :: huge = selected_int_kind(18) ! => integer(8) ... more fails on my 32 bit machine with gfortran(gcc) 4.3.2   contains   subroutine find_factors(n, d) integer(huge), intent(in) :: n integer, dimension(:), intent(out) :: d   integer(huge) :: d...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SAS
SAS
/* Using ADDR to get memory address, and PEEKC / POKE. There is also PEEK for numeric values. */ data _null_; length a b c $4; adr_a=addr(a); adr_b=addr(b); adr_c=addr(c); a="ABCD"; b="EFGH"; c="IJKL"; b=peekc(adr_a,1); call poke(b,adr_c,1); put a b c; run;
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Scala
Scala
#!/usr/local/bin/shale   aVariable var // Create aVariable aVariable 0 = // Regular assignment. aVariable "aVariable = %d\n" printf // Print aVariable   aPointer var // Create aPointer aPointer aVariable &= // Pointer a...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Shale
Shale
#!/usr/local/bin/shale   aVariable var // Create aVariable aVariable 0 = // Regular assignment. aVariable "aVariable = %d\n" printf // Print aVariable   aPointer var // Create aPointer aPointer aVariable &= // Pointer a...
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#jq
jq
jq -n -M -r -f plot.jq | R CMD BATCH plot.R
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....
#Julia
Julia
using Plots plotlyjs()   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]   p = scatter(x, y) savefig(p, "/tmp/testplot.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
#Golo
Golo
#!/usr/bin/env golosh ---- This module demonstrates Golo's version of polymorphism. ---- module Polymorphism   # Each struct automatically gets a constructor and also accessor and assignment methods for each field. # For example, the constructor for Point is Point(1, 2) # and the accessor methods are x() and y() # and ...
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
#Groovy
Groovy
@Canonical @TupleConstructor(force = true) @ToString(includeNames = true) class Point { Point(Point p) { x = p.x; y = p.y } void print() { println toString() } Number x Number y }   @Canonical @TupleConstructor(force = true) @ToString(includeNames = true, includeSuper = true) class Circle extends Point ...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Phix
Phix
with javascript_semantics function poker(string hand) hand = substitute(hand,"10","t") sequence cards = split(hand) if length(cards)!=5 then return "invalid hand" end if sequence ranks = repeat(0,13), suits = repeat(0,4) integer jokers = 0 for i=1 to length(cards) do sequenc...
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 ...
#Elixir
Elixir
defmodule Population do   def count(n), do: count(<<n :: integer>>, 0)   defp count(<<>>, acc), do: acc   defp count(<<bit :: integer-1, rest :: bitstring>>, sum), do: count(rest, sum + bit)   def evil?(n), do: n >= 0 and rem(count(n),2) == 0   def odious?(n), do: n >= 0 and rem(count(n),2) == 1   end   IO.pu...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Nim
Nim
const MinusInfinity = -1   type Polynomial = seq[int] Term = tuple[coeff, exp: int]   func degree(p: Polynomial): int = ## Return the degree of a polynomial. ## "p" is supposed to be normalized. result = if p.len > 0: p.len - 1 else: MinusInfinity   func normalize(p: var Polynomial) = ## Normalize a polynom...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#OCaml
OCaml
let rec shift n l = if n <= 0 then l else shift (pred n) (l @ [0.0]) let rec pad n l = if n <= 0 then l else pad (pred n) (0.0 :: l) let rec norm = function | 0.0 :: tl -> norm tl | x -> x let deg l = List.length (norm l) - 1   let zip op p q = let d = (List.length p) - (List.length q) in List.map2 op (pad (-d) p) ...
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Tcl
Tcl
set varCopy $varOriginal
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Wren
Wren
class Animal { construct new(name, age) { _name = name _age = age }   name { _name } age { _age }   copy() { Animal.new(name, age) }   toString { "Name: %(_name), Age: %(_age)" } }   class Dog is Animal { construct new(name, age, breed) { super(name, age) // call Ani...
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...
#MATLAB
MATLAB
>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; >> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; >> polyfit(x,y,2)   ans =   2.999999999999998 2.000000000000019 0.999999999999956
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...
#Frink
Frink
  a = new set[1,2,3,4] a.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 ...
#CMake
CMake
# Prime predicate: does n be a prime number? Sets var to true or false. function(primep var n) if(n GREATER 2) math(EXPR odd "${n} % 2") if(odd) # n > 2 and n is odd. set(factor 3) # Loop for odd factors from 3, while factor <= n / factor. math(EXPR quot "${n} / ${factor}") while...
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 ...
#Java
Java
import java.util.Random;   public class Main { private static float priceFraction(float f) { if (0.00f <= f && f < 0.06f) return 0.10f; else if (f < 0.11f) return 0.18f; else if (f < 0.16f) return 0.26f; else if (f < 0.21f) return 0.32f; else if (f < 0.26f) return 0.38f; else if (f < 0.31f) return 0.44f; ...
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...
#Oberon-2
Oberon-2
  MODULE ProperDivisors; IMPORT Out;   CONST initialSize = 128; TYPE Result* = POINTER TO ResultDesc; ResultDesc = RECORD found-: LONGINT; (* number of slots in pd *) pd-: POINTER TO ARRAY OF LONGINT; cap: LONGINT; (* Capacity *) END;   VAR i,found,max,idxMx: LONGINT; mx: ARRAY 32 OF LON...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Scheme
Scheme
(use-modules (ice-9 format))   (define (random-choice probs) (define choice (random 1.0)) (define (helper val prob-lis) (let ((nval (- val (cadar prob-lis)))) (if (< nval 0) (caar prob-lis) (helper nval (cdr prob-lis))))) (helper choice probs))   (define (add-result result delta tab...
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...
#Phix
Phix
with javascript_semantics constant tasklist = new_dict() procedure add_task(integer priority, string desc) integer k = getd_index(priority,tasklist) if k=0 then putd(priority,{desc},tasklist) else sequence descs = getd_by_index(k,tasklist) putd(priority,append(descs,desc),tasklist)...
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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPrime(n As Integer) As Boolean If n Mod 2 = 0 Then Return n = 2 If n Mod 3 = 0 Then Return n = 3 Dim d As Integer = 5 While d * d <= n If n Mod d = 0 Then Return False d += 2 If n Mod d = 0 Then Return False d += 4 Wend Return True End Function   Sub getPrimeFa...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Sidef
Sidef
func assign2ref(ref, value) { *ref = value; }   var x = 10; assign2ref(\x, 20); say x; # x is now 20
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Standard_ML
Standard ML
  val p = ref 1; (* create a new "reference" data structure with initial value 1 *) val k = !p; (* "dereference" the reference, returning the value inside *) p := k + 1; (* set the value inside to a new value *)  
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Tcl
Tcl
set var 3 set pointer var; # assign name "var" not value 3 set pointer; # returns "var" set $pointer; # returns 3 set $pointer 42; # variable var now has value 42
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....
#Kotlin
Kotlin
// Version 1.2.31   import org.jfree.chart.ChartFactory import org.jfree.chart.ChartPanel import org.jfree.data.xy.XYSeries import org.jfree.data.xy.XYSeriesCollection import org.jfree.chart.plot.PlotOrientation import javax.swing.JFrame import javax.swing.SwingUtilities import java.awt.BorderLayout   fun main(args: Ar...
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
#Haskell
Haskell
data Point = Point Integer Integer instance Show Point where show (Point x y) = "Point at "++(show x)++","++(show y)   -- Constructor that sets y to 0 ponXAxis = flip Point 0   -- Constructor that sets x to 0 ponYAxis = Point 0   -- Constructor that sets x and y to 0 porigin = Point 0 0   data Circle = Circle Integ...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Picat
Picat
go => Hands = [ [[2,h], [7,h], [2,d], [3,c], [3,d]],  % two-pair [[2,h], [5,h], [7,d], [8,c], [9,s]],  % high-card [[a,h], [2,d], [3,c], [4,c], [5,d]],  % straight [[2,h], [3,h], [2,d], [3,c], [3,d]],  % full-house [[2,h], [7,h], [2,d], [3,c], [3,d]],  % two...
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 ...
#Erlang
Erlang
-module(population_count). -export([popcount/1]).   -export([task/0]).   popcount(N) -> popcount(N,0).   popcount(0,Acc) -> Acc; popcount(N,Acc) -> popcount(N div 2, Acc + N rem 2).   threes(_,0,Acc) -> lists:reverse(Acc); threes(Threes,N,Acc) -> threes(Threes * 3, N-1, [popcount(Threes)|Acc]).   th...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Octave
Octave
function [q, r] = poly_long_div(n, d) gd = length(d); pv = zeros(1, length(n)); pv(1:gd) = d; if ( length(n) >= gd ) q = []; while ( length(n) >= gd ) q = [q, n(1)/pv(1)]; n = n - pv .* (n(1)/pv(1)); n = shift(n, -1); % tn = n(1:length(n)-1); % eat the higher powe...
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ПC С/П ПD ИП9 + П9 ИПC ИП5 + П5 ИПC x^2 П2 ИП6 + П6 ИП2 ИПC * ИП7 + П7 ИП2 x^2 ИП8 + П8 ИПC ИПD * ИПA + ПA ИП2 ИПD * ИПB + ПB ИПD КИП4 С/П БП 00
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...
#FunL
FunL
def powerset( s ) = s.subsets().toSet()
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 ...
#COBOL
COBOL
Identification Division. Program-Id. Primality-By-Subdiv.   Data Division. Working-Storage Section. 78 True-Val Value 0. 78 False-Val Value 1.   Local-Storage Section. 01 lim Pic 9(10). 01 i Pic 9(10).   Linkage Section. 01 num Pic ...
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 ...
#JavaScript
JavaScript
function getScaleFactor(v) {   var values = ['0.10','0.18','0.26','0.32','0.38','0.44','0.50','0.54', '0.58','0.62','0.66','0.70','0.74','0.78','0.82','0.86', '0.90','0.94','0.98','1.00'];   return values[(v * 100 - 1) / 5 | 0]; }
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...
#Objeck
Objeck
use Collection;   class Proper{ function : Main(args : String[]) ~ Nil { for(x := 1; x <= 10; x++;) { Print(x, ProperDivs(x)); };   x := 0; count := 0;   for(n := 1; n <= 20000; n++;) { if(ProperDivs(n)->Size() > count) { x := n; count := ProperDivs(n)->Size(); };...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: letter is new enum aleph, beth, gimel, daleth, he, waw, zayin, heth end enum;   const func string: str (in letter: aLetter) is return [] ("aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth") [succ(ord(aLetter))];   enable_output(lette...
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...
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Priority_queue by Galileo, 05/2022 #/   include ..\Utilitys.pmt   ( ) ( 3 "Clear drains" ) 0 put ( 4 "Feed cat" ) 0 put ( 5 "Make tea" ) 0 put ( 1 "Solve RC tasks" ) 0 put ( 2 "Tax return" ) 0 put sort pop swap print pstack  
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 ...
#Frink
Frink
println[factor[2^508-1]]
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Toka
Toka
variable myvar #! stores 1 cell
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#VBA
VBA
Dim samplevariable as New Object Dim anothervariable as Object Set anothervariable = sameplevariable
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Wren
Wren
// This function takes a string (behaves like a value type) and a list (reference type). // The value and the reference are copied to their respective parameters. var f = Fn.new { |s, l| if (s.type != String) Fiber.abort("First parameter must be a string.") if (l.type != List) Fiber.abort("Second parameter mu...
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....
#Lambdatalk
Lambdatalk
  1) define X & Y:   {def X 0 1 2 3 4 5 7 8 9} -> X {def Y 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0} -> Y   2) define a function returning a sequence of SVG points   {def curve {lambda {:curve :kx :ky} {S.map {{lambda {:curve :kx :ky :i} {* :kx {S.get :i {{car :curve}}}} ...
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
#Icon_and_Unicon
Icon and Unicon
class Circle (x, y, r) # make a new copy of this instance method copy () return Circle (x, y, r) end   # print a representation of this instance method print () write ("Circle (" || x || ", " || y || ", " || r || ")") end   # called during instance construction, to pass in field values initially...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#PicoLisp
PicoLisp
(setq *Rank '(("2" . 0) ("3" . 1) ("4" . 2) ("5" . 3) ("6" . 4) ("7" . 5) ("8" . 6) ("9" . 7) ("t" . 8) ("j" . 9) ("q" . 10) ("k" . 11) ("a" . 12) ) ) (de poker (Str) (let (S NIL R NIL Seq NIL) (for (L (chop Str) (cdr L) (cdddr L)) (accu 'R (cdr (assoc (car L) *Rank)) 1) ...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#F.23
F#
  // Population count. Nigel Galloway: February 18th., 2021 let pC n=Seq.unfold(fun n->match n/2L,n%2L with (0L,0L)->None |(n,g)->Some(g,n))n|>Seq.sum printf "pow3  :"; [0..29]|>List.iter((pown 3L)>>pC>>(printf "%3d")); printfn "" printf "evil  :"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=0L)|>Seq.take ...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#PARI.2FGP
PARI/GP
poldiv(a,b)={ my(rem=a%b); [(a - rem)/b, rem] }; poldiv(x^9+1, x^3+x-3)
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Modula-2
Modula-2
MODULE PolynomialRegression; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE Eval(a,b,c,x : REAL) : REAL; BEGIN RETURN a + b*x + c*x*x; END Eval;   PROCEDURE Regression(x,y : ARRAY OF INTEGER); VAR n,i : INTEGER; xm,x2m,x3m...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
# Built-in Combinations([1, 2, 3]); # [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]   # Note that it handles duplicates Combinations([1, 2, 3, 1]); # [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], ...
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 ...
#CoffeeScript
CoffeeScript
is_prime = (n) -> # simple prime detection using trial division, works # for all integers return false if n <= 1 # by definition p = 2 while p * p <= n return false if n % p == 0 p += 1 true   for i in [-1..100] console.log i if is_prime 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 ...
#jq
jq
def getScaleFactor: ["0.10","0.18","0.26","0.32","0.38","0.44","0.50","0.54", "0.58","0.62","0.66","0.70","0.74","0.78","0.82","0.86", "0.90","0.94","0.98","1.00"] as $values | $values[ (. * 100 - 1) / 5 | floor ] ;
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...
#Oforth
Oforth
Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) }   10 seq apply(#[ dup print " : " print properDivs println ]) 20000 seq map(#[ dup properDivs size Pair new ]) reduce(#maxKey) println
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Sidef
Sidef
define TRIALS = 1e4;   func prob_choice_picker(options) { var n = 0; var a = []; options.each { |k,v| n += v; a << [n, k]; } func { var r = 1.rand; a.first{|e| r <= e[0] }[1]; } }   var ps = Hash( aleph => 1/5, beth => 1/6, gimel => 1/7, daleth => ...
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...
#PHP
PHP
<?php $pq = new SplPriorityQueue;   $pq->insert('Clear drains', 3); $pq->insert('Feed cat', 4); $pq->insert('Make tea', 5); $pq->insert('Solve RC tasks', 1); $pq->insert('Tax return', 2);   // This line causes extract() to return both the data and priority (in an associative array), // Otherwise it would just return th...
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 ...
#GAP
GAP
FactorsInt(2^67-1); # [ 193707721, 761838257287 ]
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XPL0
XPL0
\Paraphrasing the C example: \This creates a pointer to an integer variable: int Var, Ptr, V; Ptr:= @Var;   \Access the integer variable through the pointer: Var:= 3; V:= Ptr(0); \set V to the value of Var, i.e. 3 Ptr(0):= 42; \set Var to 42   \Change the pointer to refer to another integer variable: int OtherV...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Z80_Assembly
Z80 Assembly
ld a,(&C000) ;load the accumulator with the value from the memory address &C000.   ld hl,&D000 ld e,(hl) ;load the E register with the byte at memory address &D000.   ld bc,(&E000) ;load the register pair BC from memory address &E000. ; This is the same as: ; ld a,(&E000) ; ld c,a ; ld a,(&E001) ; ld b,a   ld ...
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....
#Liberty_BASIC
Liberty BASIC
  'Plotting coordinate pairs MainWin - Style For i = 0 To 9 x(i) = i Next i   y(0) = 2.7 y(1) = 2.8 y(2) = 31.4 y(3) = 38.1 y(4) = 58.0 y(5) = 76.2 y(6) = 100.5 y(7) = 130.0 y(8) = 149.3 y(9) = 180.0   Locate 4, 22 For i = 0 To 9 Locate ((i * 4) + 2), 22 Print i Next i   For i = 0 To 20 Step 2 Locate 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
#Inform_7
Inform 7
Space is a room.   A point is a kind of thing. A point has a number called X position. A point has a number called Y position.   A circle is a kind of point. A circle has a number called radius.   To print (P - point): say "Point: [X position of P], [Y position of P]." To print (C - circle): say "Circle: [X position of...
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
#J
J
coclass 'Point' create=: monad define 'X Y'=:2{.y ) getX=: monad def 'X' getY=: monad def 'Y' setX=: monad def 'X=:y' setY=: monad def 'Y=:y' print=: monad define smoutput 'Point ',":X,Y ) destroy=: codestroy
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Prolog
Prolog
:- initialization(main).     faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).   face(F) :- faces(Fs), member(F,Fs). suit(S) :- member(S, ['♥','♦','♣','♠']).     best_hand(Cards,H) :- straight_flush(Cards,C) -> H = straight-flush(C) ; many_kind(Cards,F,4) -> H = four-of-a-kind(F) ; full_house(Cards,F1,F2) -> H = full-hou...
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 ...
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.bitwise math.functions namespaces prettyprint.config sequences ;   : 3^n ( obj -- obj' ) [ 3 swap ^ bit-count ] lmap-lazy ; : evil ( obj -- obj' ) [ bit-count even? ] lfilter ; : odious ( obj -- obj' ) [ bit-count odd? ] lfilter ;   100 margin set 0 lfrom [ 3^n ] [ ev...
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Perl
Perl
use strict; use List::Util qw(min);   sub poly_long_div { my ($rn, $rd) = @_;   my @n = @$rn; my $gd = scalar(@$rd); if ( scalar(@n) >= $gd ) { my @q = (); while ( scalar(@n) >= $gd ) { my $piv = $n[0]/$rd->[0]; push @q, $piv; $n[$_] -= $rd->[$_] * $piv foreach ( 0 .. min(scalar(@n), $g...
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...
#Nim
Nim
import lenientops, sequtils, stats, strformat   proc polyRegression(x, y: openArray[int]) =   let xm = mean(x) let ym = mean(y) let x2m = mean(x.mapIt(it * it)) let x3m = mean(x.mapIt(it * it * it)) let x4m = mean(x.mapIt(it * it * it * it)) let xym = mean(zip(x, y).mapIt(it[0] * it[1])) let x2ym = mean(z...
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...
#GAP
GAP
# Built-in Combinations([1, 2, 3]); # [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]   # Note that it handles duplicates Combinations([1, 2, 3, 1]); # [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], ...
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 ...
#Common_Lisp
Common Lisp
(defun primep (n) "Is N prime?" (and (> n 1) (or (= n 2) (oddp n)) (loop for i from 3 to (isqrt n) by 2 never (zerop (rem n 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 ...
#Julia
Julia
  const PFCUT = [6:5:101]//100 const PFVAL = [10:8:26, 32:6:50, 54:4:98, 100]//100   function pricefraction{T<:FloatingPoint}(a::T) zero(T) <= a || error("a = ", a, ", but it must be >= 0.") a <= one(T) || error("a = ", a, ", but it must be <= 1.") convert(T, PFVAL[findfirst(a .< PFCUT)]) end   test = [0.:0...
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...
#PARI.2FGP
PARI/GP
proper(n)=if(n==1, [], my(d=divisors(n)); d[2..#d]); apply(proper, [1..10]) r=at=0; for(n=1,20000, t=numdiv(n); if(t>r, r=t; at=n)); [at, numdiv(t)-1]
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Stata
Stata
clear mata letters="aleph","beth","gimel","daleth","he","waw","zayin","heth" a=letters[rdiscrete(10000,1,(1/5,1/6,1/7,1/8,1/9,1/10,1/11,1759/27720))]' st_addobs(10000) st_addvar("str10","a") st_sstore(.,.,a) end
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Tcl
Tcl
package require Tcl 8.5   set map [dict create] set sum 0.0   foreach name {aleph beth gimel daleth he waw zayin} \ prob {1/5.0 1/6.0 1/7.0 1/8.0 1/9.0 1/10.0 1/11.0} \ { set prob [expr $prob] set sum [expr {$sum + $prob}] dict set map $name [dict create probability $prob limit $sum count 0] } dict ...
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...
#Picat
Picat
main => Tasks = [[3,"Clear drains"], [4,"Feed cat"], [5,"Make tea"], [1,"Solve RC tasks"], [2,"Tax return"]], Heap = new_min_heap([]), foreach(Task in Tasks) Heap.heap_push(Task), println(top=Heap.heap_top()) end, nl, println(Heap), println(size=Heap.h...
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 ...
#Go
Go
package main   import ( "fmt" "math/big" )   var ( ZERO = big.NewInt(0) ONE = big.NewInt(1) )   func Primes(n *big.Int) []*big.Int { res := []*big.Int{} mod, div := new(big.Int), new(big.Int) for i := big.NewInt(2); i.Cmp(n) != 1; { div.DivMod(n, i, mod) for mod.Cmp(ZERO) ==...
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#zkl
zkl
fcn f(r){r.inc()} r:= Ref(1); f(r); r.value; //-->2
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....
#LiveCode
LiveCode
  on plotGraphic local tCoordinates local x = "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" local y = "2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0" if there is a graphic "graph" then delete graphic "graph" repeat with i = 1 to the number of items of x put ite...
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....
#Lua
Lua
  w_width = love.graphics.getWidth() w_height = love.graphics.getHeight()   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} origin = {24,24} points = {} x_unit = w_width/x[10]/2 y_unit = w_height/10   --add points to an array properly formatted for the line function for i=1,...