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/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...
#Oz
Oz
declare class T from ObjectSupport.reflect meth init skip end   meth name($) 'T' end end   class S from T attr a feat f   meth name($) 'S' end   meth getA($) @a end meth setA(V) a := V end end   Obj = {New S init} Copy = {Obj clone($)...
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...
#Perl
Perl
package T; sub new { my $cls = shift; bless [ @_ ], $cls }   sub set_data { my $self = shift; @$self = @_; }   sub copy { my $self = shift; bless [ @$self ], ref $self; }   sub manifest { my $self = shift; print "type T, content: @$self\n\n"; }   package S...
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...
#Java
Java
import java.util.Arrays; import java.util.function.IntToDoubleFunction; import java.util.stream.IntStream;   public class PolynomialRegression { private static void polyRegression(int[] x, int[] y) { int n = x.length; int[] r = IntStream.range(0, n).toArray(); double xm = Arrays.stream(x).av...
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...
#EchoLisp
EchoLisp
  (define (set-cons a A) (make-set (cons a A)))   (define (power-set e) (cond ((null? e) (make-set (list ∅))) (else (let [(ps (power-set (cdr e)))] (make-set (append ps (map set-cons (circular-list (car e)) ps)))))))   (define B (make-set ' ( 🍎 🍇 🎂 🎄 ))) (power-set B) → { ∅ { �...
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 ...
#C
C
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2;   /* comparing p*p <= n can overflow */ for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
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 ...
#Go
Go
package main   import "fmt"   func pf(v float64) float64 { switch { case v < .06: return .10 case v < .11: return .18 case v < .16: return .26 case v < .21: return .32 case v < .26: return .38 case v < .31: return .44 case v < .36: ...
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...
#Kotlin
Kotlin
// version 1.0.5-2   fun listProperDivisors(limit: Int) { if (limit < 1) return for(i in 1..limit) { print(i.toString().padStart(2) + " -> ") if (i == 1) { println("(None)") continue } (1..i/2).filter{ i % it == 0 }.forEach { print(" $it") } printl...
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...
#Python
Python
import random, bisect   def probchoice(items, probs): '''\ Splits the interval 0.0-1.0 in proportion to probs then finds where each random.random() choice lies '''   prob_accumulator = 0 accumulator = [] for p in probs: prob_accumulator += p accumulator.append(prob_accumulator)   while True: ...
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...
#Nim
Nim
type PriElem[T] = tuple data: T pri: int   PriQueue[T] = object buf: seq[PriElem[T]] count: int   # first element not used to simplify indices proc initPriQueue[T](initialSize = 4): PriQueue[T] = result.buf.newSeq(initialSize) result.buf.setLen(1) result.count = 0   proc add[T](q: var PriQueue...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Visual_Basic
Visual Basic
Option Explicit   Dim total As Long, prim As Long, maxPeri As Long   Public Sub NewTri(ByVal s0 As Long, ByVal s1 As Long, ByVal s2 As Long) Dim p As Long, x1 As Long, x2 As Long p = s0 + s1 + s2 If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p x1 = s0 + s2 x2 = s...
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...
#Unlambda
Unlambda
`ei
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...
#Ursa
Ursa
stop
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Ezhil
Ezhil
  ## இந்த நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும்   நிரல்பாகம் பகாஎண்ணா(எண்1)   ## இந்த நிரல்பாகம் தரப்பட்ட எண் பகு எண்ணா அல்லது பகா எண்ணா என்று கண்டறிந்து சொல்லும் ## பகுஎண் என்றால் 0 திரும்பத் தரப்படும் ## பகாஎண் என்றால் 1 திரும்பத் தரப்படும்   @(எண்1 < 0) ஆனால்   ## எதிர்மறை எண்களை நேராக்குதல் ...
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 |...
#Perl
Perl
# start with some var definitions my $scalar = 'aa'; my @array = ('bb', 'cc'); my %hash = ( dd => 'DD', ee => 'EE' );   # make references my $scalarref = \$scalar; my $arrayref = \@array; my $hashref = \%hash;
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 |...
#Phix
Phix
atom addr = allocate(8) -- (assumes 32 bit) poke4(addr,{NULL,SOME_CONSTANT}) c_proc(xSome_External_Routine,{addr,addr+4}) ?peek4s({addr,2}) -- prints {x,y} free(addr)
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....
#gnuplot
gnuplot
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
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....
#Go
Go
package main   import ( "fmt" "log" "os/exec" )   var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} )   func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err =...
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
#Ela
Ela
type Point = Point x y   instance Show Point where show (Point x y) = "Point " ++ (show x) ++ " " ++ (show y)   instance Name Point where getField nm (Point x y) | nm == "x" = x | nm == "y" = y | else = fail "Undefined name." isField nm _ = nm == "x" || nm == "y"   pointX = flip Point 0   pointY = Poi...
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
#Elena
Elena
import extensions;   class Point { prop int X; prop int Y;   constructor new(int x, int y) { X := x; Y := y }   constructor new() <= new(0,0);   print() { console.printLine("Point") } }   class Circle : Point { prop int R;   constructor new() <...
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,...
#Julia
Julia
sorteddeck = [string(r) * s for s in "♣♦♥♠", r in "23456789TJQKA"]   cardlessthan(card1, card2) = indexin(x, sorteddeck)[1] < indexin(y, sorteddeck)[1]   decksort(d) = sort(d, lt=cardlessthan)   highestrank(d) = string(highestcard(d)[1])   function hasduplicate(d) s = sort(d) for i in 1:length(s)-1 if s...
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 ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. HAMMING.   DATA DIVISION. WORKING-STORAGE SECTION. 01 POPCOUNT-VARIABLES. 03 POPCOUNT-IN PIC 9(15)V9. 03 FILLER REDEFINES POPCOUNT-IN. 05 POPCOUNT-REST PIC 9(15). 05 FILLER PI...
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...
#J
J
divmod=:[: (}: ; {:) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)&.|.~
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...
#Phix
Phix
with javascript_semantics enum NAME, METHOD procedure me_t() puts(1,"I is a T\n") end procedure procedure me_s() puts(1,"I is an S\n") end procedure type T(object o) -- as o[METHOD] can be overidden, don't verify it (as in test for me_t)! return sequence(o) and length(o)=2 and string(o[NAME]) and int...
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...
#PHP
PHP
<?php class T { function name() { return "T"; } }   class S { function name() { return "S"; } }   $obj1 = new T(); $obj2 = new S(); $obj3 = clone $obj1; $obj4 = clone $obj2; echo $obj3->name(), "\n"; // prints "T" echo $obj4->name(), "\n"; // prints "S" ?>
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...
#Julia
Julia
polyfit(x::Vector, y::Vector, deg::Int) = collect(v ^ p for v in x, p in 0:deg) \ y   x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] @show polyfit(x, y, 2)
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Elixir
Elixir
defmodule RC do use Bitwise def powerset1(list) do n = length(list) max = round(:math.pow(2,n)) for i <- 0..max-1, do: (for pos <- 0..n-1, band(i, bsl(1, pos)) != 0, do: Enum.at(list, pos) ) end   def powerset2([]), do: [[]] def powerset2([h|t]) do pt = powerset2(t) (for x <- pt, do: [h|x]...
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 ...
#C.23
C#
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 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 ...
#Groovy
Groovy
def priceFraction(value) { assert value >= 0.0 && value <= 1.0   def priceMappings = [(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...
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...
#Lua
Lua
-- Return a table of the proper divisors of n function propDivs (n) if n < 2 then return {} end local divs, sqr = {1}, math.sqrt(n) for d = 2, sqr do if n % d == 0 then table.insert(divs, d) if d ~= sqr then table.insert(divs, n/d) end end end table.sort(divs)...
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...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   ( --------------- zen object orientation -------------- )   [ immovable ]this[ swap do ]done[ ] is object ( [ --> )   [ ]'[ ] is method ( --> [ )   [ method [ dup share swap put ] ] is localise ( --> )   ...
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...
#R
R
prob = c(aleph=1/5, beth=1/6, gimel=1/7, daleth=1/8, he=1/9, waw=1/10, zayin=1/11, heth=1759/27720) # Note that R doesn't actually require the weights # vector for rmultinom to sum to 1. hebrew = c(rmultinom(1, 1e6, prob)) d = data.frame( Requested = prob, Obtained = hebrew/sum(hebrew)) print(d)
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   const void *PQRetain(CFAllocatorRef allocator, const void *ptr) { return (__bridge_retained const void *)(__bridge id)ptr; } void PQRelease(CFAllocatorRef allocator, const void *ptr) { (void)(__bridge_transfer id)ptr; } CFComparisonResult PQCompare(const void *ptr1, const void *p...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Wren
Wren
var sc = System.clock var total = 0 var prim = 0 var maxPeri = 0   var newTri // recursive function so needs to be declared before it can be called newTri = Fn.new { |s0, s1, s2| var p = s0 + s1 + s2 if (p <= maxPeri) { prim = prim + 1 total = total + (maxPeri/p).floor newTri.call( 1*s0-...
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...
#VBA
VBA
'In case of problem this will terminate the program (without cleanup): If problem then End 'As VBA is run within an application, such as Excel, a more rigorous way would be: If problem then Application.Quit 'This will stop the application, but will prompt you to save work.
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...
#VBScript
VBScript
dim i, j j = 0 do for i = 1 to 100 while j < i if i = 3 then wscript.quit end if wend next loop
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 ...
#F.23
F#
let decompose_prime n = let rec loop c p = if c < (p * p) then [c] elif c % p = 0I then p :: (loop (c/p) p) else loop c (p + 1I)   loop n 2I   printfn "%A" (decompose_prime 600851475143I)
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PHP
PHP
<?php /* Assignment of scalar variables */ $a = 1; $b =& $a; // $b and $a are now linked together $b = 2; //both $b and $a now equal 2 $c = $b; $c = 7; //$c is not a reference; no change to $a or $b unset($a); //won't unset $b, just $a.   /* Passing by Reference in and out of functions */ function &pass_out() { glo...
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 |...
#PicoLisp
PicoLisp
: (setq L (1 a 2 b 3 c)) # Create a list of 6 items in 'L' -> (1 a 2 b 3 c)   : (nth L 4) # Get a pointer to the 4th item -> (b 3 c)   : (set (nth L 4) "Hello") # Store "Hello" in that location -> "Hello"   : L # Look at the modified list in 'L' -> (1 a 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....
#Groovy
Groovy
import groovy.swing.SwingBuilder import javax.swing.JFrame 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   def chart = { x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2.7, ...
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
#F.23
F#
type Printable = abstract member Print : unit -> unit   type Point(?x, ?y) = member t.x = defaultArg x 0.0 member t.y = defaultArg y 0.0 interface Printable with member t.Print() = printfn "Point(x:%f, y:%f)" t.x t.y   type Circle(?center, ?radius) = member t.center = defaultArg center (new Point()) me...
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,...
#Kotlin
Kotlin
// version 1.1.2   class Card(val face: Int, val suit: Char)   const val FACES = "23456789tjqka" const val SUITS = "shdc"   fun isStraight(cards: List<Card>): Boolean { val sorted = cards.sortedBy { it.face } if (sorted[0].face + 4 == sorted[4].face) return true if (sorted[4].face == 14 && sorted[0].face ==...
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Common_Lisp
Common Lisp
(format T "3^x: ~{~a ~}~%" (loop for i below 30 collect (logcount (expt 3 i))))   (multiple-value-bind (evil odious) (loop for i below 60 if (evenp (logcount i)) collect i into evil else collect i into odious finally (return (values evil odious))) (format T "evil: ...
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...
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;   public class PolynomialLongDivision {   public static void main(String[] args) { RunDivideTest(new Polynomial(1, 3, -12, 2, -42, 0), new Polynomial(1, 1, -3, 0)); ...
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...
#PicoLisp
PicoLisp
: (setq A (new '(+Cls1 +Cls2) 'attr1 123 'attr2 "def" 'attr3 (4 2 0) 'attr4 T)) -> $385603635   : (show A) $385603635 (+Cls1 +Cls2) attr4 attr3 (4 2 0) attr2 "def" attr1 123 -> $385603635
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...
#Python
Python
import copy   class T: def classname(self): return self.__class__.__name__   def __init__(self): self.myValue = "I'm a T."   def speak(self): print self.classname(), 'Hello', self.myValue   def clone(self): return copy.copy(self)   class S1(T): def speak(self): print self.c...
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...
#Kotlin
Kotlin
// version 1.1.51   fun polyRegression(x: IntArray, y: IntArray) { val xm = x.average() val ym = y.average() val x2m = x.map { it * it }.average() val x3m = x.map { it * it * it }.average() val x4m = x.map { it * it * it * it }.average() val xym = x.zip(y).map { it.first * it.second }.averag...
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...
#Erlang
Erlang
For [1 2 3]: [ ] | 0 0 0 | 0 [ 3] | 0 0 1 | 1 [ 2 ] | 0 1 0 | 2 [ 2 3] | 0 1 1 | 3 [1 ] | 1 0 0 | 4 [1 3] | 1 0 1 | 5 [1 2 ] | 1 1 0 | 6 [1 2 3] | 1 1 1 | 7 ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
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.23
F#
  let subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]  
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 ...
#C.2B.2B
C++
#include <cmath>   bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 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 ...
#Haskell
Haskell
price_fraction n | n < 0 || n > 1 = error "Values must be between 0 and 1." | n < 0.06 = 0.10 | n < 0.11 = 0.18 | n < 0.16 = 0.26 | n < 0.21 = 0.32 | n < 0.26 = 0.38 | n < 0.31 = 0.44 | n < 0.36 = 0.50 | n < 0.41 = 0.54 | n < 0.46 = 0.58 | n < 0.51 = 0.62 | n < 0.56 = 0.66 | n < 0.61 = 0.70 ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ProperDivisors[n_Integer /; n > 0] := Most@Divisors@n;
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...
#Racket
Racket
#lang racket ;;; returns a probabalistic choice from the sequence choices ;;; choices generates two values -- the chosen value and a ;;; probability (weight) of the choice. ;;; ;;; Note that a hash where keys are choices and values are probabilities ;;; is such a sequence. ;;; ;;; if the total probability < 1 then choi...
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...
#Raku
Raku
constant TRIALS = 1e6;   constant @event = <aleph beth gimel daleth he waw zayin heth>;   constant @P = flat (1 X/ 5 .. 11), 1759/27720; constant @cP = [\+] @P;   my atomicint @results[+@event]; (^TRIALS).race.map: { @results[ @cP.first: { $_ > once rand }, :k ]⚛++; }   say 'Event Occurred Expected Difference'; fo...
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...
#OCaml
OCaml
module PQ = Base.PriorityQueue   let () = let tasks = [ 3, "Clear drains"; 4, "Feed cat"; 5, "Make tea"; 1, "Solve RC tasks"; 2, "Tax return"; ] in let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in List.iter (PQ.add pq) tasks; while not (PQ.is_empty pq) do let _, task = ...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#XPL0
XPL0
func GCD(N, D); \Return the greatest common divisor of N and D int N, D, R; \numerator and denominator [if D > N then [R:=D; D:=N; N:=R]; while D > 0 do [R:= rem(N/D); N:= D; D:= R; ]; return N; ];   int Max, PrimCnt, TripCnt, M, N, A, B, C, K, Prim; [Max:= 10; repeat PrimCnt:= 0; TripCnt:= 0...
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...
#Vedit_macro_language
Vedit macro language
if (#99 == 1) { Return } // Exit current macro. Return to calling macro. if (#99 == 2) { Break_Out() } // Stop all macro execution and return to command mode. if (#99 == 3) { Exit } // Exit Vedit. Prompt for saving any changed files. if (#99 == 4) { Exit(4) } // As above, but return specified va...
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 ...
#Factor
Factor
USING: io kernel math math.parser math.primes.factors sequences ;   27720 factors [ number>string ] map " " join print ;
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 |...
#PL.2FI
PL/I
  dcl i fixed bin(31); dcl p pointer; dcl j fixed bin(31) based; i=5; p=addr(i); p->j=p->j+1; /an other way to say i=i+1 */ put skip edit(i)(F(5)); /* -> 6 */   /* second form */ dcl i fixed bin(31); dcl j fixed bin(31) based(p); i=5; p=addr(i); j=j+1; /* an other way to say i=i+1 */ put skip edit(i)(F(5)); /*...
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 |...
#Pop11
Pop11
vars vec1, vec2; ;;; Create a vector and assign (reference to) it to vec1 consvector("a", "b", "c", 3) -> vec1; ;;; Copy (reference to) vector vec1 -> vec2; ;;; Print value of vec1 vec1 => ;;; Change first element of vec2 "d" -> vec2(1); ;;; Print value of vec1 -- the value changes because vec1 and ;;; vec2 reference t...
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....
#Haskell
Haskell
import Graphics.Gnuplot.Simple   pnts = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]   doPlot = plotPathStyle [ ( Title "plotting dots" )] (PlotStyle Points (CustomStyle [])) (zip [0..] pnts)
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....
#HicEst
HicEst
REAL :: n=10, x(n), y(n)   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(WINdowhandle=wh, Width=-300, Height=-300, X=1, TItle='Rosetta') AXIS(WINdowhandle=wh, Title='x values', Yaxis, Title='y values') LINE(X=x, Y=y, SymbolDiameter=2)
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
#Factor
Factor
QUALIFIED: io  ! there already is print in io   GENERIC: print ( shape -- )   TUPLE: point x y ; C: <point> point  ! shorthand constructor definition   M: point print drop "Point" io:print ;   TUPLE: circle radius x y ; C: <circle> circle   M: circle print drop "Circle" io:print ;
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
#Forth
Forth
include lib/memcell.4th include 4pp/lib/foos.4pp   :: Point ( xn n a--) class field: x \ x coordinate field: y \ y coordinate method: print \ print routine method: setx \ set x...
http://rosettacode.org/wiki/Poker_hand_analyser
Poker hand analyser
Task Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. Example 2d       (two of diamonds). Faces are:    a, 2, 3, 4,...
#Lua
Lua
-- Check whether t is a valid poker hand function valid (t) if #t ~= 5 then return false end for k, v in pairs(t) do for key, card in pairs(t) do if v.value == card.value and v.suit == card.suit and k ~= key then return false ...
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 ...
#Crystal
Crystal
struct Int def evil? self >= 0 && popcount.even? end end   puts "Powers of 3:", (0...30).map{|n| (3u64 ** n).popcount}.join(' ') # can also use &** (to prevent arithmetic overflow) puts "Evil:" , 0.step.select(&.evil?).first(30).join(' ') puts "Odious:", 0.step.reject(&.evil?).first(30).join(' ')
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...
#Julia
Julia
  using Polynomials   p = Poly([-42,0,-12,1]) q = Poly([-3,1])   d, r = divrem(p,q)   println(p, " divided by ", q, " is ", d, " with remainder ", r, ".")  
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...
#Racket
Racket
#lang racket/base   (define (copy-prefab-struct str) (apply make-prefab-struct (vector->list (struct->vector str))))   (struct point (x y) #:prefab) (struct point/color point (color) #:prefab)     (let* ([original (point 0 0)] [copied (copy-prefab-struct original)]) (displayln copied) (displayln (eq? origi...
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...
#Raku
Raku
my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }} my Cool $y = $x.clone; $y.brag;
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...
#REXX
REXX
/*REXX program to copy (polymorphically) one variable's value into another variable. */ b= 'old value.' a= 123.45 b= a /*copy a variable's value into another.*/ if a==b then say "copy did work." else say "copy didn't work." /*didn't work, maybe ran out...
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...
#Lua
Lua
function eval(a,b,c,x) return a + (b + c * x) * x end   function regression(xa,ya) local n = #xa   local xm = 0.0 local ym = 0.0 local x2m = 0.0 local x3m = 0.0 local x4m = 0.0 local xym = 0.0 local x2ym = 0.0   for i=1,n do xm = xm + xa[i] ym = ym + ya[i] ...
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Factor
Factor
USING: kernel prettyprint sequences arrays sets hash-sets ; IN: powerset   : add ( set elt -- newset ) 1array <hash-set> union ; : powerset ( set -- newset ) members { HS{ } } [ dupd [ add ] curry map append ] reduce <hash-set> ;
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Chapel
Chapel
proc is_prime(n) { if n == 2 then return true; if n <= 1 || n % 2 == 0 then return false; for i in 3..floor(sqrt(n)):int by 2 do if n % i == 0 then 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 ...
#HicEst
HicEst
DIMENSION upperbound(20), rescaleTo(20), temp(20) upperbound = (.06,.11,.16,.21,.26,.31,.36,.41,.46,.51,.56,.61,.66,.71,.76,.81,.86,.91,.96,1.01) rescaleTo = (.10,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.90,.94,.98,1.00)   DO test = 1, 10 value = RAN(0.5, 0.5) temp = value > upperbound PriceF...
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...
#MATLAB
MATLAB
function D=pd(N) K=1:ceil(N/2); D=K(~(rem(N, K)));
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...
#ReScript
ReScript
let p = [ ("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), ("Zayin", 1.0 /. 11.0), ("Heth", 1759.0 /. 27720.0), ]   let prob_take = (arr, k) => { let rec aux = (i, k) => { let ...
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...
#REXX
REXX
/*REXX program displays results of probabilistic choices, gen random #s per probability.*/ parse arg trials digs seed . /*obtain the optional arguments from CL*/ if trials=='' | trials=="," then trials= +1e6 /*Not specified? Then use the default.*/ if digs=='' | digs=="," then digs= 15 ...
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...
#OxygenBasic
OxygenBasic
  'PRIORITY QUEUE WITH 16 LEVELS   uses console   % pl 16 'priority levels   =================== Class PriorityQueue ===================   indexbase 1 bstring buf[pl] 'buffers to hold priority queues content int bg[pl] 'buffers base offset int i[pl] 'indexers int le[pl] 'length of buffer   method constr...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#zkl
zkl
fcn tri(lim,a=3,b=4,c=5){ p:=a + b + c; if(p>lim) return(0,0); T(1,lim/p).zipWith('+, tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c), tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c), tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) ); }
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...
#Visual_Basic
Visual Basic
Sub Main() '... If problem Then For n& = Forms.Count To 0 Step -1 Unload Forms(n&) Next Exit Sub End If '... End Sub
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Wren
Wren
import "io" for Stdin, Stdout   System.write("Do you want to terminate the program y/n ? ") Stdout.flush() var yn = Stdin.readLine() if (yn == "y" || yn == "Y") { System.print("OK, shutting down") Fiber.suspend() // return to OS } System.print("OK, carrying on")
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 ...
#FALSE
FALSE
[2[\$@$$*@>~][\$@$@$@$@\/*=$[%$." "$@\/\0~]?~[1+1|]?]#%.]d: 27720d;! {2 2 2 3 3 5 7 11}
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PureBasic
PureBasic
Define varA.i = 5, varB.i = 0, *myInteger.Integer   *myInteger = @varA ;set pointer to address of an integer variable varB = *myInteger\i + 3 ;set variable to the 3 + value of dereferenced pointer, i.e varB = 8
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 |...
#Python
Python
# Bind a literal string object to a name: a = "foo" # Bind an empty list to another name: b = [] # Classes are "factories" for creating new objects: invoke class name as a function: class Foo(object): pass c = Foo() # Again, but with optional initialization: class Bar(object): def __init__(self, init...
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....
#Icon_and_Unicon
Icon and Unicon
link printf,numbers   procedure main() x := [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.] y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] Plot(x,y,600,400) end   $define POINTR 2 # Point Radius $define POINTC "red" # Point Colour $define GRIDC "grey" ...
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
#Fortran
Fortran
  module geom   type point real(8), private :: x = 0 real(8), private :: y = 0 contains procedure, public :: get_x procedure, public :: get_y procedure, public :: set_x procedure, public :: set_y procedure, public :: print => print_point procedure, pass :: copy_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,...
#Nim
Nim
import algorithm, sequtils, strutils, tables, unicode   type   Suit* = enum ♠, ♥, ♦, ♣ Face* {.pure.} = enum Ace = (1, "a") Two = (2, "2") Three = (3, "3") Four = (4, "4") Five = (5, "5") Six = (6, "6") Seven = (7, "7") Eight = (8, "8") Nine = (9, "9") Ten = (10, "10") Ja...
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 ...
#D
D
void main() { import std.stdio, std.algorithm, std.range, core.bitop;   enum pCount = (ulong n) => popcnt(n & uint.max) + popcnt(n >> 32); writefln("%s\nEvil: %s\nOdious: %s", uint.max.iota.map!(i => pCount(3L ^^ i)).take(30), uint.max.iota.filter!(i => pCount(i) % 2 == 0).take(30)...
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...
#Kotlin
Kotlin
// version 1.1.51   typealias IAE = IllegalArgumentException   data class Solution(val quotient: DoubleArray, val remainder: DoubleArray)   fun polyDegree(p: DoubleArray): Int { for (i in p.size - 1 downTo 0) { if (p[i] != 0.0) return i } return Int.MIN_VALUE }   fun polyShiftRight(p: DoubleArray, 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...
#Ruby
Ruby
class T def name "T" end end   class S def name "S" end end   obj1 = T.new obj2 = S.new puts obj1.dup.name # prints "T" puts obj2.dup.name # prints "S"
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Scala
Scala
object PolymorphicCopy {   def main(args: Array[String]) { val a: Animal = Dog("Rover", 3, "Terrier") val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog println(s"Dog 'a' = $a") // implicitly calls Dog.toString() println(s"Dog 'b' = $b") // ditto println(s"Dog 'a' is $...
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...
#Maple
Maple
with(CurveFitting); PolynomialInterpolation([[0, 1], [1, 6], [2, 17], [3, 34], [4, 57], [5, 86], [6, 121], [7, 162], [8, 209], [9, 262], [10, 321]], '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...
#Forth
Forth
: ?print dup 1 and if over args type space then ; : .set begin dup while ?print >r 1+ r> 1 rshift repeat drop drop ; : .powerset 0 do ." ( " 1 i .set ." )" cr loop ; : check-none dup 2 < abort" Usage: powerset [val] .. [val]" ; : check-size dup /cell 8 [*] >= abort" Set too large" ; : powerset 1 argn check-none check-s...
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Clojure
Clojure
(defn divides? [k n] (zero? (mod k n)))
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Icon_and_Unicon
Icon and Unicon
  record Bounds(low,high,new)   # rescale given value according to a list of bounds procedure rescale (i, bounds) every bound := !bounds do if bound.low <= i < bound.high then return bound.new return fail # could not find i in bounds end   procedure main () bounds := [ Bounds(0.00, 0.06, 0.10), ...
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...
#Modula-2
Modula-2
MODULE ProperDivisors; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE proper_divisors(n : INTEGER; print_flag : BOOLEAN) : IN...
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Ring
Ring
  # Project : Probabilistic choice   cnt = list(8) item = ["aleph","beth","gimel","daleth","he","waw","zayin","heth"] prob = [1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720]   for trial = 1 to 1000000 r = random(10)/10 p = 0 for i = 1 to len(prob) p = p + prob[i] if r < p ...
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...
#Ruby
Ruby
probabilities = { "aleph" => 1/5.0, "beth" => 1/6.0, "gimel" => 1/7.0, "daleth" => 1/8.0, "he" => 1/9.0, "waw" => 1/10.0, "zayin" => 1/11.0, } probabilities["heth"] = 1.0 - probabilities.each_value.inject(:+) ordered_keys = probabilities.keys   sum, sums = 0.0, {} ordered_keys.each do |key| ...
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...
#Pascal
Pascal
  program PriorityQueueTest;   uses Classes;   Type TItem = record Priority:Integer; Value:string; end;   PItem = ^TItem;   TPriorityQueue = class(Tlist) procedure Push(Priority:Integer;Value:string); procedure SortPriority(); function Pop():String; function Empty:Boolean; end;   { TPriorityQueue }   pro...
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#ZX_Spectrum_Basic
ZX Spectrum Basic
1 LET Y=0: LET X=0: LET Z=0: LET V=0: LET U=0: LET L=10: LET T=0: LET P=0: LET N=4: LET M=0: PRINT "limit trip. prim." 2 FOR U=2 TO INT (SQR (L/2)): LET Y=U-INT (U/2)*2: LET N=N+4: LET M=U*U*2: IF Y=0 THEN LET M=M-U-U 3 FOR V=1+Y TO U-1 STEP 2: LET M=M+N: LET X=U: LET Y=V 4 LET Z=Y: LET Y=X-INT (X/Y)*Y:...
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...
#XPL0
XPL0
if Problem then exit 1;