task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #D | D | import std.stdio: writeln;
class Point {
private int x, y;
this(int x_=0, int y_=0) { x = x_; y = y_; }
this(Point p_) { x = p_.getX(); y = p_.getY(); }
int getX() { return x; }
void setX(int x_) { this.x = x_; }
int getY() { return y; }
void setY(int y_) { this.y = y_; }
}
class Circle ... |
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,... | #Go | Go | package main
import (
"fmt"
"sort"
"strings"
)
type card struct {
face byte
suit byte
}
const faces = "23456789tjqka"
const suits = "shdc"
func isStraight(cards []card) bool {
sorted := make([]card, 5)
copy(sorted, cards)
sort.Slice(sorted, func(i, j int) bool {
return so... |
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
... | #C | C | #include <stdio.h>
int main() {
{
unsigned long long n = 1;
for (int i = 0; i < 30; i++) {
// __builtin_popcount() for unsigned int
// __builtin_popcountl() for unsigned long
// __builtin_popcountll() for unsigned long long
printf("%d ", __builtin_popcountll(n));
n *= 3;
}
... |
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... | #Fortran | Fortran | module Polynom
implicit none
contains
subroutine poly_long_div(n, d, q, r)
real, dimension(:), intent(in) :: n, d
real, dimension(:), intent(out), allocatable :: q
real, dimension(:), intent(out), allocatable, optional :: r
real, dimension(:), allocatable :: nt, dt, rt
integer :: gn, gt, g... |
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... | #Kotlin | Kotlin | // version 1.1.2
open class Animal(val name: String, var age: Int) {
open fun copy() = Animal(name, age)
override fun toString() = "Name: $name, Age: $age"
}
class Dog(name: String, age: Int, val breed: String) : Animal(name, age) {
override fun copy() = Dog(name, age, breed)
override f... |
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... | #Lua | Lua | T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }
function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T) S1.name=function(s) return "S1" end
function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=fu... |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
var Radians = Fn.new { |d| d * Num.pi / 180 }
class Polyspiral {
construct new(width, height) {
Window.title = "Polyspiral"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
... |
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... | #Haskell | Haskell | import Data.List
import Data.Array
import Control.Monad
import Control.Arrow
import Matrix.LU
ppoly p x = map (x**) p
polyfit d ry = elems $ solve mat vec where
mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d]
vec = listArray (1,d) $ take d ry |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Common_Lisp | Common Lisp | (defun powerset (s)
(if s (mapcan (lambda (x) (list (cons (car s) x) x))
(powerset (cdr s)))
'(()))) |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Befunge | Befunge | &>:48*:** \1`!#^_2v
v_v#`\*:%*:*84\/*:*84::+<
v >::48*:*/\48*:*%%!#v_1^
>0"seY" >:#,_@#: "No">#0< |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #Factor | Factor | CONSTANT: dispensary-data {
{ 0.06 0.10 }
{ 0.11 0.18 }
{ 0.16 0.26 }
{ 0.21 0.32 }
{ 0.26 0.38 }
{ 0.31 0.44 }
{ 0.36 0.50 }
{ 0.41 0.54 }
{ 0.46 0.58 }
{ 0.51 0.62 }
{ 0.56 0.66 }
{ 0.61 0.70 }
{ 0.66 0.74 }
{ 0.71 0.78 }
{ 0.76 0.82 }
{ 0.81 0.86 }
{ 0.86 0.90 }
{ 0.91 0.94 }
{ 0.96 0.98 }
{ 1.01 1.00 } }
: price-... |
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 ... | #Fantom | Fantom |
class Defn // to hold the three numbers from a 'row' in the table
{
Float low
Float high
Float value
new make (Float low, Float high, Float value)
{
this.low = low
this.high = high
this.value = value
}
}
class PriceConverter
{
Defn[] defns := [,]
new make (Str table) // process given tab... |
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... | #Java | Java | import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Proper{
public static List<Integer> properDivs(int n){
List<Integer> divs = new LinkedList<Integer>();
if(n == 1) return divs;
divs.add(1);
for(int x = 2; x < n; x++){
if(n % ... |
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... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Probabilistic_choice
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
( ( "aleph" 0.200000 0 ) ( "beth" 0.166667 0 ) ( "gimel" 0.142857 0 ) ( "daleth" 0.125000 0 )
( "he" 0.111111 0 ) ( "waw" 0.100000 0 ) ( "zayin" 0.090909 0 ) ( "heth" 0.063456 0 ) )
len 1 swap ... |
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... | #PicoLisp | PicoLisp | (let (Count 1000000 Denom 27720 N Denom)
(let Probs
(mapcar
'((I S)
(prog1 (cons N (*/ Count I) 0 S)
(dec 'N (/ Denom I)) ) )
(range 5 12)
'(aleph beth gimel daleth he waw zayin heth) )
(do Count
(inc (cddr (rank (rand 1 Denom) Probs T))) )... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module UnOrderedArray {
Class PriorityQueue {
Private:
Dim Item()
many=0, level=0, first
cmp = lambda->0
Module Reduce {
if .many<.first*2 then exit
If .level<.many/2 then .many/=2 : Dim .Item(.many)
}
Pu... |
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,... | #Swift | Swift | var total = 0
var prim = 0
var maxPeri = 100
func newTri(s0:Int, _ s1:Int, _ s2: Int) -> () {
let p = s0 + s1 + s2
if p <= maxPeri {
prim += 1
total += maxPeri / p
newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2)
newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+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... | #SSEM | SSEM | 00000000000000110000000000000000 Test
00000000000001110000000000000000 Stop |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Standard_ML | Standard ML | if problem then
OS.Process.exit OS.Process.failure
(* valid status codes include OS.Process.success and OS.Process.failure *)
else
() |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Tcl | Tcl | if {$problem} {
# Print a “friendly” message...
puts stderr "some problem occurred"
# Indicate to the caller of the program that there was a problem
exit 1
} |
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem | Primality by Wilson's theorem | Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
| #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn isWilsonPrime(p){
if(p<=1 or (p%2==0 and p!=2)) return(False);
BI(p-1).factorial().add(1).mod(p) == 0
}
fcn wPrimesW{ [2..].tweak(fcn(n){ isWilsonPrime(n) and n or Void.Skip }) } |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #zkl | zkl | const CNT =0d1_000_000;
sieve :=Import("sieve.zkl",False,False,False).postponed_sieve;
conspiracy:=Dictionary();
Utils.Generator(sieve).reduce(CNT,'wrap(digit,p){
d:=p%10;
conspiracy.incV("%d → %d count:".fmt(digit,d));
d
});
foreach key in (conspiracy.keys.sort()){ v:=conspiracy[key].toFloat();
print... |
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 ... | #Ela | Ela | open integer //arbitrary sized integers
decompose_prime n = loop n 2I
where
loop c p | c < (p * p) = [c]
| c % p == 0I = p :: (loop (c / p) p)
| else = loop c (p + 1I)
decompose_prime 600851475143I |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Lua | Lua | local table1 = {1,2,3}
local table2 = table1
table2[3] = 4
print(unpack(table1)) |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #M2000_Interpreter | M2000 Interpreter |
A=10
Module Beta {
Read &X
X++
}
Beta &A
Print A=11
|
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Modula-3 | Modula-3 | TYPE IntRef = REF INTEGER;
VAR intref := NEW(IntRef);
intref^ := 10 |
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.... | #Erlang | Erlang |
-module( plot_coordinate_pairs ).
-export( [task/0, to_png_file/3] ).
task() ->
Xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Ys = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0],
File = "plot_coordinate_pairs",
to_png_file( File, Xs, Ys ).
to_png_file( File, Xs, Ys ) ->
PNG = egd_chart:graph( [{File... |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Delphi | Delphi | type
{ TPoint }
TMyPoint = class
private
FX: Integer;
FY: Integer;
public
constructor Create; overload;
constructor Create(X0: Integer; Y0: Integer); overload;
constructor Create(MyPoint: TMyPoint); overload;
destructor Destroy; override;
procedure Print; virtual;
property ... |
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,... | #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight ... |
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
... | #C.23 | C# |
using System;
using System.Linq;
namespace PopulationCount
{
class Program
{
private static int PopulationCount(long n)
{
string binaryn = Convert.ToString(n, 2);
return binaryn.ToCharArray().Where(t => t == '1').Count();
}
static void Main(string[] ... |
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... | #FreeBASIC | FreeBASIC | #define EPS 1.0e-20
type polyterm
degree as uinteger
coeff as double
end type
sub poly_print( P() as double )
dim as string outstr = "", sri
for i as integer = ubound(P) to 0 step -1
if outstr<>"" then
if P(i)>0 then outstr = outstr + " + "
if P(i)<0 then outstr = out... |
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... | #MiniScript | MiniScript | T = {}
T.foo = function()
return "This is an instance of T"
end function
S = new T
S.foo = function()
return "This is an S for sure"
end function
instance = new S
print "instance.foo: " + instance.foo
copy = {}
copy = copy + instance // copies all elements
print "copy.foo: " + copy.foo
// And to prove ... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
-- -----------------------------------------------------------------------------
class RCPolymorphicCopy public
method copier(x = T) public static returns T
return x.copy
method main(args = String[]) public constant
obj1 = T()
... |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #XPL0 | XPL0 |
def Width=640., Height=480.;
def Deg2Rad = 3.141592654/180.;
real Incr, Angle, Length, X, Y, X1, Y1;
int N;
[SetVid($101); \VESA 640x480x8 graphics
Incr:= 0.;
repeat Incr:= Incr+1.;
X:= Width/2.; Y:= Height/2.;
Move(fix(X), fix(Y));
Length:= 5.;
Angle:= Incr;
for N:= 1 to... |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #Yabasic | Yabasic | w = 1024 : h = 600
open window w, h
color 255,0,0
incr = 0 : twopi = 2 * pi
while true
incr = mod(incr + 0.05, twopi)
x1 = w / 2
y1 = h / 2
length = 5
angle = incr
clear window
for i = 1 to 151
x2 = x1 + cos(angle) * length
y2 = y1 + sin(angle) * length
line x... |
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... | #HicEst | HicEst | REAL :: n=10, x(n), y(n), m=3, p(m)
x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y = (1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
p = 2 ! initial guess for the polynom's coefficients
SOLVE(NUL=Theory()-y(nr), Unknown=p, DataIdx=nr, Iters=iterations)
WRITE(ClipBoard, Name) p, iteratio... |
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... | #D | D | import std.algorithm;
import std.range;
auto powerSet(R)(R r)
{
return
(1L<<r.length)
.iota
.map!(i =>
r.enumerate
.filter!(t => (1<<t[0]) & i)
.map!(t => t[1])
);
}
unittest
{
int[] emptyArr;
assert(emptyArr.powerSet.equal!equal([emptyArr]));
assert(emptyArr.powerSet.powerSet.equal!(equal!equa... |
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
... | #Bracmat | Bracmat | ( prime
= incs n I inc
. 4 2 4 2 4 6 2 6:?incs
& 2:?n
& 1 2 2 !incs:?I
& whl
' ( !n*!n:~>!arg
& div$(!arg.!n)*!n:~!arg
& (!I:%?inc ?I|!incs:%?inc ?I)
& !n+!inc:?n
)
& !n*!n:>!arg
)
& 100000000000:?p
& whl
' ( !p+1:<100000000100:... |
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 ... | #Forth | Forth | : as begin parse-word dup while evaluate , repeat 2drop ;
create bounds as 96 91 86 81 76 71 66 61 56 51 46 41 36 31 26 21 16 11 6 0
create official as 100 98 94 90 86 82 78 74 70 66 62 58 54 50 44 38 32 26 18 10
: official@ ( a-bounds -- +n )
\ (a+n) - a + b = (a+n) + (b - a) = (b+n)
[ official bounds - ]... |
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 ... | #Fortran | Fortran | program price_fraction
implicit none
integer, parameter :: i_max = 10
integer :: i
real, dimension (20), parameter :: in = &
& (/0.00, 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, &
& 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96/)
real, dimension (2... |
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... | #JavaScript | JavaScript | (function () {
// Proper divisors
function properDivisors(n) {
if (n < 2) return [];
else {
var rRoot = Math.sqrt(n),
intRoot = Math.floor(rRoot),
lows = range(1, intRoot).filter(function (x) {
return (n % x) === 0;
... |
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... | #PL.2FI | PL/I | probch: Proc Options(main);
Dcl prob(8) Dec Float(15) Init((1/5.0), /* aleph */
(1/6.0), /* beth */
(1/7.0), /* gimel */
(1/8.0), /* daleth */
(1/9.0), /* he ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | push = Function[{queue, priority, item},
queue = SortBy[Append[queue, {priority, item}], First], HoldFirst];
pop = Function[queue,
If[Length@queue == 0, Null,
With[{item = queue[[-1, 2]]}, queue = Most@queue; item]],
HoldFirst];
peek = Function[queue,
If[Length@queue == 0, Null, Max[queue[[All, 1]]... |
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,... | #Tcl | Tcl | proc countPythagoreanTriples {limit} {
lappend q 3 4 5
set idx [set count [set prim 0]]
while {$idx < [llength $q]} {
set a [lindex $q $idx]
set b [lindex $q [incr idx]]
set c [lindex $q [incr idx]]
incr idx
if {$a + $b + $c <= $limit} {
incr prim
for {set i 1} {$i*$a+$i*... |
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... | #TI-83_BASIC | TI-83 BASIC | If 1
Stop
|
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #TI-89_BASIC | TI-89 BASIC | Prgm
...
Stop
...
EndPrgm |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #Elixir | Elixir | defmodule Prime do
def decomposition(n), do: decomposition(n, 2, [])
defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end
prime = ... |
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 |... | #Nim | Nim | type Foo = ref object
x, y: float
var f: Foo
new f |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #OCaml | OCaml |
let p = ref 1;; (* create a new "reference" data structure with initial value 1 *)
let k = !p;; (* "dereference" the reference, returning the value inside *)
p := k + 1;; (* set the value inside to a new value *)
|
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.... | #F.23 | F# | #r @"C:\Program Files\FlyingFrog\FSharpForVisualization.dll"
let x = Seq.map float [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9|]
let y = [|2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0|]
open FlyingFrog.Graphics
Plot([Data(Seq.zip x y)], (0.0, 9.0)) |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #E | E | def makePoint(x, y) {
def point implements pbc {
to __printOn(out) { out.print(`<point $x,$y>`) }
to __optUncall() { return [makePoint, "run", [x, y]] }
to x() { return x }
to y() { return y }
to withX(new) { return makePoint(new, y) }
to withY(new) { return makePoint(x, new) }
}
return po... |
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,... | #J | J | parseHand=: <;._2@,&' '@u:~&7 NB. hand must be well formed
Suits=: <"> 7 u: '♥♦♣♦' NB. or Suits=: 'hdcs'
Faces=: <;._1 ' 2 3 4 5 6 7 8 9 10 j q k a'
suits=: {:&.>
faces=: }:&.>
flush=: 1 =&#&~. suits
straight=: 1 = (i.#Faces) +/@E.~ Faces /:~@i. faces
kinds=: #/.~ @:faces
five=: 5 e. kinds NB. jokers or other c... |
http://rosettacode.org/wiki/Population_count | Population count | Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
... | #C.2B.2B | C++ | #include <iostream>
#include <bitset>
#include <climits>
size_t popcount(unsigned long long n) {
return std::bitset<CHAR_BIT * sizeof n>(n).count();
}
int main() {
{
unsigned long long n = 1;
for (int i = 0; i < 30; i++) {
std::cout << popcount(n) << " ";
n *= 3;
}
std::cout << std::... |
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... | #GAP | GAP | x := Indeterminate(Rationals, "x");
p := x^11 + 3*x^8 + 7*x^2 + 3;
q := x^7 + 5*x^3 + 1;
QuotientRemainder(p, q);
# [ x^4+3*x-5, -16*x^4+25*x^3+7*x^2-3*x+8 ] |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #Nim | Nim | type
T = ref object of RootObj
myValue: string
S1 = ref object of T
S2 = ref object of T
method speak(x: T) {.base.} = echo "T Hello ", x.myValue
method speak(x: S1) = echo "S1 Meow ", x.myValue
method speak(x: S2) = echo "S2 Woof ", x.myValue
echo "creating initial objects of types S1, S2, and T."
var a ... |
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... | #Objective-C | Objective-C | @interface T : NSObject
- (void)identify;
@end
@implementation T
- (void)identify {
NSLog(@"I am a genuine T");
}
- (id)copyWithZone:(NSZone *)zone {
T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here
// then copy... |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #zkl | zkl | w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF); // White background
angleIncrement:=(3.0).toRad();
while(True){
r,angle:=0.0, 0.0;
ao,len,inc:=w/2, 2.5, angleIncrement+(130.0).toRad();
foreach c in (128){
s,a:=r + len, angle + inc;
x,y:=r.toRectangular(angle);
u,v:=r.toRectangular(a);
c=c.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... | #Hy | Hy | (import [numpy [polyfit]])
(setv x (range 11))
(setv y [1 6 17 34 57 86 121 162 209 262 321])
(print (polyfit x y 2)) |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | powerset s:
local :out [ set{ } ]
for value in keys s:
for subset in copy out:
local :subset+1 copy subset
set-to subset+1 value true
push-to out subset+1
out
!. powerset set{ 1 2 3 4 } |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Delphi | Delphi |
program Power_set;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
n = 4;
var
buf: TArray<Integer>;
procedure rec(ind, bg: Integer);
begin
for var i := bg to n - 1 do
begin
buf[ind] := i;
for var j := 0 to ind do
write(buf[j]: 2);
writeln;
rec(ind + 1, buf[ind] + 1);
end;
en... |
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
... | #Brainf.2A.2A.2A | Brainf*** | >->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>
+]++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->-------
--<]>--.[-]<<<->[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>>
>]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--]<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--[>+... |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #FreeBASIC | FreeBASIC | ' FB 1.050.0 Win64
Function rescale(price As Double) As Double
If price < 0.00 OrElse price > 1.00 Then Return price
Select Case price
Case Is < 0.06 : Return 0.10
Case Is < 0.11 : Return 0.18
Case Is < 0.16 : Return 0.26
Case Is < 0.21 : Return 0.32
Case Is < 0.26 : Return 0.38
Case Is < ... |
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... | #jq | jq | def count(stream): reduce stream as $i (0; . + 1);
# unordered
def proper_divisors:
. as $n
| if $n > 1 then 1,
( range(2; 1 + (sqrt|floor)) as $i
| if ($n % $i) == 0 then $i,
(($n / $i) | if . == $i then empty else . end)
else empty
end)
else empty
end;
# The first ... |
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... | #PowerShell | PowerShell |
$character = [PSCustomObject]@{
aleph = [PSCustomObject]@{Expected=1/5 ; Alpha="א"}
beth = [PSCustomObject]@{Expected=1/6 ; Alpha="ב"}
gimel = [PSCustomObject]@{Expected=1/7 ; Alpha="ג"}
daleth = [PSCustomObject]@{Expected=1/8 ; Alpha="ד"}
he = [PSCustomObject]@{Exp... |
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... | #Maxima | Maxima | /* Naive implementation using a sorted list of pairs [key, [item[1], ..., item[n]]].
The key may be any number (integer or not). Items are extracted in FIFO order. */
defstruct(pqueue(q = []))$
/* Binary search */
find_key(q, p) := block(
[i: 1, j: length(q), k, c],
if j = 0 then false
elseif (c: q[i][1]... |
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,... | #VBA | VBA | Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - 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... | #Tiny_BASIC | Tiny BASIC | LET I = 0
10 IF I = 10 THEN END
LET I = I + 1
PRINT I
GOTO 10 |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #Transd | Transd |
(if errorCode
(exit errorCode))
|
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #True_BASIC | True BASIC | $$ MODE TUSCRIPT
IF (condition==1) STOP
-> execution stops and message:
IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP " |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #Erlang | Erlang | % no stack consuming version
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N < K*K -> [N|Acc];
factors(N,K,Acc) when N rem K == 0 ->
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc). |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Oforth | Oforth |
::class Foo
::method init
expose x
x = 0
::attribute x
::routine somefunction
a = .Foo~new -- assigns a to point to a new Foo object
b = a -- b and a now point to the same object
a~x = 5 -- modifies the X variable inside the object pointer to by a
say b~x ... |
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 |... | #ooRexx | ooRexx |
::class Foo
::method init
expose x
x = 0
::attribute x
::routine somefunction
a = .Foo~new -- assigns a to point to a new Foo object
b = a -- b and a now point to the same object
a~x = 5 -- modifies the X variable inside the object pointer to by a
say b~x ... |
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.... | #Factor | Factor | USING: accessors assocs colors.constants kernel sequences ui
ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;
chart new { { 0 9 } { 0 180 } } >>axes
line new COLOR: blue >>color
9 <iota> { 2.7 2.8 31.4 38.1 58 76.2 100.5 130 149.3 180 } zip
>>data add-gadget "Coordinate pairs" open-window |
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | Dim As Integer i, x(9), y(9)
For i = 0 To 9
x(i) = i
Next i
y(0) = 2.7
y(1) = 2.8
y(2) = 31.4
y(3) = 38.1
y(4) = 58.0
y(5) = 76.2
y(6) = 100.5
y(7) = 130.0
y(8) = 149.3
y(9) = 180.0
Locate 22, 4
For i = 0 To 9
Locate 22, ((i * 4) + 2) : Print i
Next i
For i = 0 To 20 Step 2
Locate (21 - i), 0 : Print ... |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #EchoLisp | EchoLisp |
(struct Point ((real:x 0) (real:y 0)))
(struct Circle ((real:x 0) (real:y 0) (real:r 1)))
(define-method (print Point:p) (printf "📌 [%d %d]" p.x p.y))
(define-method (print Circle:c) (printf "⭕️ center:[%d %d] radius:%d" c.x c.y c.r))
(print (Point 5 6))
→ 📌 [5 6]
(print (Circle 2 3 4))
→ ⭕️ center:[2 3... |
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,... | #Java | Java | import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class PokerHandAnalyzer {
final static String faces = "AKQJT98765432";
final static String suits = "HDSC";
final static String[] deck = buildDeck();
public static void main(String[] args) {
System.out.p... |
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
... | #Clojure | Clojure |
(defn population-count [n]
(Long/bitCount n)) ; use Java inter-op
(defn exp [n pow]
(reduce * (repeat pow n)))
(defn evil? [n]
(even? (population-count n)))
(defn odious? [n]
(odd? (population-count n)))
;;
;; Clojure's support for generating "lazily-evaluated" infinite sequences can
;; be use... |
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... | #Go | Go | package main
import "fmt"
func main() {
n := []float64{-42, 0, -12, 1}
d := []float64{-3, 1}
fmt.Println("N:", n)
fmt.Println("D:", d)
q, r, ok := pld(n, d)
if ok {
fmt.Println("Q:", q)
fmt.Println("R:", r)
} else {
fmt.Println("error")
}
}
func degree(p []f... |
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... | #OCaml | OCaml | let obj1 =
object
method name = "T"
end
let obj2 =
object
method name = "S"
end
let () =
print_endline (Oo.copy obj1)#name; (* prints "T" *)
print_endline (Oo.copy obj2)#name; (* prints "S" *) |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #ooRexx | ooRexx |
s = .s~new
s2 = s~copy -- makes a copy of the first
if s == s2 then say "copy didn't work!"
if s2~name == "S" then say "polymorphic copy worked"
::class t
::method name
return "T"
::class s subclass t
::method name
return "S"
|
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #OxygenBasic | OxygenBasic |
'======
class T
'======
float vv
method constructor(float a=0) {vv=a}
method destructor {}
method copy as T {new T ob : ob<=vv : return ob}
method mA() as float {return vv*2}
method mB() as float {return vv*3}
end class
'======
class S
'======
has T
method mB() as float {return vv*4} 'ovveride
... |
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... | #J | J | Y=:1 6 17 34 57 86 121 162 209 262 321
(%. ^/~@x:@i.@#) Y
1 2 3 0 0 0 0 0 0 0 0 |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Dyalect | Dyalect | let n = 4
let buf = Array.Empty(n)
func rec(idx, begin) {
for i in begin..<n {
buf[idx] = i
for j in 0..idx {
print("{0, 2}".Format(buf[j]), terminator: "")
}
print("")
rec(idx + 1, buf[idx] + 1)
}
}
rec(0, 0) |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #E | E | pragma.enable("accumulator")
def powerset(s) {
return accum [].asSet() for k in 0..!2**s.size() {
_.with(accum [].asSet() for i ? ((2**i & k) > 0) => elem in s {
_.with(elem)
})
}
} |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Burlesque | Burlesque | fcL[2== |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #Gambas | Gambas | Public Sub Main()
Dim byValue As Byte[] = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]
Dim byLimit As Byte[] = [6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]
Dim byCount, byCheck As Byte
For byCount = 0 To 100
For byCheck = 0 To byLimit.Max
If by... |
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... | #Julia | Julia |
function properdivisors{T<:Integer}(n::T)
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
1 < n || return T[]
!isprime(n) || return T[one(T), n]
f = factor(n)
d = T[one(T)]
for (k, v) in f
c = T[k^i for i in 0:v]
d = d*c'
d = reshape(d, length... |
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... | #PureBasic | PureBasic | #times=1000000
Structure Item
name.s
prob.d
Amount.i
EndStructure
If OpenConsole()
Define i, j, d.d, e.d, txt.s
Dim Mapps.Item(7)
Mapps(0)\name="aleph": Mapps(0)\prob=1/5.0
Mapps(1)\name="beth": Mapps(1)\prob=1/6.0
Mapps(2)\name="gimel": Mapps(2)\prob=1/7.0
Mapps(3)\name="daleth":Mapps(3)\prob=... |
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... | #Mercury | Mercury | :- module test_pqueue.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int.
:- import_module list.
:- import_module pqueue.
:- import_module string.
:- pred build_pqueue(pqueue(int,string)::in, pqueue(int,string)::out) is det.
build_pqueue(!PQ) :-
... |
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,... | #VBScript | VBScript |
For i=1 To 8
WScript.StdOut.WriteLine triples(10^i)
Next
Function triples(pmax)
prim=0 : count=0 : nmax=Sqr(pmax)/2 : n=1
Do While n <= nmax
m=n+1 : p=2*m*(m+n)
Do While p <= pmax
If gcd(m,n)=1 Then
prim=prim+1
count=count+Int(pmax/p)
End If
m=m+2
p=2*m*(m+n)
Loop
n=n+1
Loop
triple... |
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... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
IF (condition==1) STOP
-> execution stops and message:
IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP " |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks... | #UNIX_Shell | UNIX Shell | #!/bin/sh
a='1'
b='1'
if [ "$a" -eq "$b" ]; then
exit 239 # Unexpected error
fi
exit 0 # Program terminated normally |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #ERRE | ERRE |
PROGRAM DECOMPOSE
!
! for rosettacode.org
!
!VAR NUM,J
DIM PF[100]
PROCEDURE STORE_FACTOR
PF[0]=PF[0]+1
PF[PF[0]]=CA
I=I/CA
END PROCEDURE
PROCEDURE DECOMP(I)
PF[0]=0 CA=2 ! special case
LOOP
IF I=1 THEN EXIT PROCEDURE END IF
EXIT IF INT(I/CA)*CA<>I
STORE_FACTOR
END LOOP
FO... |
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 |... | #PARI.2FGP | PARI/GP | n=1;
issquare(9,&n);
print(n); \\ prints 3 |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Pascal | Pascal | program pointerDemo;
type
{
A new pointer data type is declared by `↑` followed by a data type name,
the domain.
The domain data type may not have been declared yet, but must be
declared within the current `type` section.
Most compilers do not support the reference token `↑` as specified in
the ISO s... |
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.... | #FreeBASIC | FreeBASIC | Dim As Integer i, x(9), y(9)
For i = 0 To 9
x(i) = i
Next i
y(0) = 2.7
y(1) = 2.8
y(2) = 31.4
y(3) = 38.1
y(4) = 58.0
y(5) = 76.2
y(6) = 100.5
y(7) = 130.0
y(8) = 149.3
y(9) = 180.0
Locate 22, 4
For i = 0 To 9
Locate 22, ((i * 4) + 2) : Print i
Next i
For i = 0 To 20 Step 2
Locate (21 - i), 0 : Print ... |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Eiffel | Eiffel | class
POINT
inherit
ANY
redefine
out
end
create
make, make_origin
feature -- Initialization
make (a_x, a_y: INTEGER)
-- Create with values `a_x' and `a_y'
do
set_x (a_x)
set_y (a_y)
ensure
x_set: x = a_x
... |
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,... | #JavaScript | JavaScript | const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];
const SUITS = ['♥', '♦', '♣', '♠'];
function analyzeHand(hand){
let cards = hand.split(' ').filter(x => x !== 'joker');
let jokers = hand.split(' ').length - cards.length;
let faces = cards.map( card => FACES.indexOf(card.slice(0,... |
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
... | #CLU | CLU | pop_count = proc (n: int) returns (int)
p: int := 0
while n>0 do
p := p + n//2
n := n/2
end
return(p)
end pop_count
evil = proc (n: int) returns (bool)
return(pop_count(n)//2 = 0)
end evil
odious = proc (n: int) returns (bool)
return(~evil(n))
end odious
first = iter (n: in... |
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... | #Haskell | Haskell | import Data.List
shift n l = l ++ replicate n 0
pad n l = replicate n 0 ++ l
norm :: Fractional a => [a] -> [a]
norm = dropWhile (== 0)
deg l = length (norm l) - 1
zipWith' op p q = zipWith op (pad (-d) p) (pad d q)
where d = (length p) - (length q)
polydiv f g = aux (norm f) (norm g) []
where aux f s q... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.