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/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... | #AutoHotkey | AutoHotkey | a = 1,a,-- ; elements separated by commas
StringSplit a, a, `, ; a0 = #elements, a1,a2,... = elements of the set
t = {
Loop % (1<<a0) { ; generate all 0-1 sequences
x := A_Index-1
Loop % a0
t .= (x>>A_Index-1) & 1 ? a%A_Index% "," : ""
t .= "}`n{" ; new subsets in new lines
... |
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
... | #AppleScript | AppleScript | on isPrime(n)
if (n < 3) then return (n is 2)
if (n mod 2 is 0) then return false
repeat with i from 3 to (n ^ 0.5) div 1 by 2
if (n mod i is 0) then return false
end repeat
return true
end isPrime
-- Test code:
set output to {}
repeat with n from -7 to 100
if (isPrime(n)) then set e... |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #C.23 | C# | namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int x = 0; x < 10; x++)
{
Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", ((double)x) / 10, SpecialRound(((double)x) / 10));
}
Console.WriteLi... |
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... | #Factor | Factor | USING: formatting io kernel math math.functions
math.primes.factors math.ranges prettyprint sequences ;
: #divisors ( m -- n )
dup sqrt >integer 1 + [1,b] [ divisor? ] with count dup +
1 - ;
10 [1,b] [ dup pprint bl divisors but-last . ] each
20000 [1,b] [ #divisors ] supremum-by dup #divisors
"%d with %d d... |
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... | #J | J |
main=: verb define
hdr=. ' target actual '
lbls=. ; ,:&.> ;:'aleph beth gimel daleth he waw zayin heth'
prtn=. +/\ pt=. (, 1-+/)1r1%5+i.7
da=. prtn I. ?y # 0
pa=. y%~ +/ da =/ i.8
hdr, lbls,. 9j6 ": |: pt,:pa
)
Note 'named abbreviations'
hdr (header)
lbls (labels)
pt (tar... |
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... | #Go | Go | package main
import (
"fmt"
"container/heap"
)
type Task struct {
priority int
name string
}
type TaskPQ []Task
func (self TaskPQ) Len() int { return len(self) }
func (self TaskPQ) Less(i, j int) bool {
return self[i].priority < self[j].priority
}
func (self TaskPQ) Swap(i, j int) { self... |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #Python | Python |
from collections import namedtuple
import math
Circle = namedtuple('Circle', 'x, y, r')
def solveApollonius(c1, c2, c3, s1, s2, s3):
'''
>>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), 1,1,1)
Circle(x=2.0, y=2.1, r=3.9)
>>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), -1,-1,-1)
Circle... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Scala | Scala | object ScriptName extends App {
println(s"Program of instantiated object: ${this.getClass.getName}")
// Not recommended, due various implementations
println(s"Program via enviroment: ${System.getProperty("sun.java.command")}")
} |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Scheme | Scheme | #!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
(use posix)
(require-extension srfi-1) ; lists
(require-extension srfi-13) ; strings
(define (main args)
(let ((prog (cdr (program))))
(display (format "Program: ~a\n" prog))
(exit)))
(define (program)
(if (string=? (car (argv)) "csi")
(let ((s-index (list-in... |
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,... | #Racket | Racket | #lang racket
#| Euclid's enumeration formula and counting is fast enough for extra credit.
For maximum perimeter P₀, the primitive triples are enumerated by n,m with:
1 ≤ n < m
perimeter P(n, m) ≤ P₀ where P(n, m) = (m² - n²) + 2mn + (m² + n²) = 2m(m+n)
m and n of different parity and coprime.
Since ... |
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... | #PowerShell | PowerShell | if (somecondition) {
exit
} |
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... | #Prolog | Prolog | halt. |
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
| #Nim | Nim | import strutils, sugar
proc facmod(n, m: int): int =
## Compute (n - 1)! mod m.
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prim... |
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
| #PARI.2FGP | PARI/GP | Wilson(n) = prod(i=1,n-1,Mod(i,n))==-1
|
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 ... | #Prolog | Prolog |
% table of nth prime values (up to 100,000)
nthprime( 10, 29).
nthprime( 100, 541).
nthprime( 1000, 7919).
nthprime( 10000, 104729).
nthprime(100000, 1299709).
conspiracy(M) :-
N is 10**M,
nthprime(N, P),
sieve(P, Ps),
tally(Ps, Counts),
sort(Counts, Sorted),
show(Sorted).
show(Re... |
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 ... | #C | C | #include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef uint32_t pint;
typedef uint64_t xint;
typedef unsigned int uint;
#define PRIuPINT PRIu32 /* printf macro for pint */
#define PRIuXINT PRIu64 /* printf macro for xint */
#define MAX_FACTORS 63 /* b... |
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 |... | #ALGOL_68 | ALGOL 68 | INT var := 3;
REF INT pointer := var; |
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 |... | #ARM_Assembly | ARM Assembly | ;this example uses VASM syntax, your assembler may not use the # before constants or the semicolon for comments
MOV R1,#0x04000000
MOV R0,#0x403
STR R0,[R1] ;store 0x403 into memory address 0x04000000. |
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
| #Ada | Ada | package Shapes is
type Point is tagged private;
procedure Print(Item : in Point);
function Setx(Item : in Point; Val : Integer) return Point;
function Sety(Item : in Point; Val : Integer) return Point;
function Getx(Item : in Point) return Integer;
function Gety(Item : in Point) return Integer;
fun... |
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
| #Aikido | Aikido |
class Point (protected x=0.0, protected y=0.0) {
public function print {
println ("Point")
}
public function getX { return x }
public function getY { return y }
public function setX(nx) { x = nx }
public function setY(ny) { y = ny }
}
class Circle (x=0.0, y=0.0, r=0.0) extends 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,... | #11l | 11l | F analyzeHandHelper(faceCount, suitCount)
V
p1 = 0B
p2 = 0B
t = 0B
f = 0B
fl = 0B
st = 0B
L(fc) faceCount
S fc
2 {I p1 {p2 = 1B} E p1 = 1B}
3 {t = 1B}
4 {f = 1B}
L(sc) suitCount
I sc == 5
fl = 1B
I !p1 & !p2 & !t & !... |
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
... | #ALGOL_68 | ALGOL 68 | # returns the population count (number of bits on) of the non-negative #
# integer n #
PROC population count = ( LONG INT n )INT:
BEGIN
LONG INT number := n;
INT result := 0;
WHILE number > 0 DO
IF ODD n... |
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... | #C.23 | C# | using System;
namespace PolynomialLongDivision {
class Solution {
public Solution(double[] q, double[] r) {
Quotient = q;
Remainder = r;
}
public double[] Quotient { get; }
public double[] Remainder { get; }
}
class Program {
static int 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... | #Common_Lisp | Common Lisp | (defstruct super foo)
(defstruct (sub (:include super)) bar)
(defgeneric frob (thing))
(defmethod frob ((super super))
(format t "~&Super has foo = ~w." (super-foo super)))
(defmethod frob ((sub sub))
(format t "~&Sub has foo = ~w, bar = ~w."
(sub-foo sub) (sub-bar sub))) |
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... | #D | D | class T {
override string toString() { return "I'm the instance of T"; }
T duplicate() { return new T; }
}
class S : T {
override string toString() { return "I'm the instance of S"; }
override T duplicate() { return new S; }
}
void main () {
import std.stdio;
T orig = new S;
T copy = o... |
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... | #JavaScript | JavaScript |
<!-- Polyspiral.html -->
<html>
<head><title>Polyspiral Generator</title></head>
<script>
// Basic function for family of Polyspirals
// Where: rng - range (prime parameter), w2 - half of canvas width,
// d - direction (1 - clockwise, -1 - counter clockwise).
function ppsp(ctx, rng, w2, d) {
// Note: coeffic... |
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... | #Julia | Julia | using Gtk, Graphics, Colors
const can = @GtkCanvas()
const win = GtkWindow(can, "Polyspiral", 360, 360)
const drawiters = 72
const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"]
const angleiters = [0, 0, 0]
const angles = [75, 100, 135, 160]
Base.length(v::Vec2) = sqr... |
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... | #C.23 | C# | public static double[] Polyfit(double[] x, double[] y, int degree)
{
// Vandermonde matrix
var v = new DenseMatrix(x.Length, degree + 1);
for (int i = 0; i < v.RowCount; i++)
for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
va... |
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... | #AWK | AWK | cat power_set.awk
#!/usr/local/bin/gawk -f
# User defined function
function tochar(l,n, r) {
while (l) { n--; if (l%2 != 0) r = r sprintf(" %c ",49+n); l = int(l/2) }; return r
}
# For each input
{ for (i=0;i<=2^NF-1;i++) if (i == 0) printf("empty\n"); else printf("(%s)\n",tochar(i,NF)) }
|
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
... | #Arturo | Arturo | isPrime?: function [n][
if n=2 -> return true
if n=3 -> return true
if or? n=<1 0=n%2 -> return false
high: to :integer sqrt n
loop high..2 .step: 3 'i [
if 0=n%i -> return false
]
return true
]
loop 1..20 'i [
print ["isPrime?" i "=" isPrime? i ]
] |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
int main( ) {
double froms[ ] = { 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 } ;
double tos[ ] = { 0.06 , 0.11 , 0.16 , 0.21 , 0.26 , 0.31 ,
0.36 , 0.41 , 0.46... |
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... | #Fermat | Fermat | Func Divisors(n) =
[d]:=[(1)]; {start divisor list with just 1, which is a divisor of everything}
for i = 2 to n\2 do {loop through possible divisors of n}
if Divides(i, n) then [d]:=[d]_[(i)] fi
od;
.;
fo... |
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... | #Java | Java | public class Prob{
static long TRIALS= 1000000;
private static class Expv{
public String name;
public int probcount;
public double expect;
public double mapping;
public Expv(String name, int probcount, double expect, double mapping){
this.name= name;
this.probcount= probcount;
this.expect= expe... |
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... | #Groovy | Groovy | import groovy.transform.Canonical
@Canonical
class Task implements Comparable<Task> {
int priority
String name
int compareTo(Task o) { priority <=> o?.priority }
}
new PriorityQueue<Task>().with {
add new Task(priority: 3, name: 'Clear drains')
add new Task(priority: 4, name: 'Feed cat')
add... |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #Racket | Racket |
#lang slideshow
(struct circle (x y r) #:prefab)
(define (apollonius c1 c2 c3 s1 s2 s3)
(define x1 (circle-x c1))
(define y1 (circle-y c1))
(define r1 (circle-r c1))
(define x2 (circle-x c2))
(define y2 (circle-y c2))
(define r2 (circle-r c2))
(define x3 (circle-x c3))
(define y3 (circle-y c3))
... |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #Raku | Raku | class Circle {
has $.x;
has $.y;
has $.r;
method gist { sprintf "%s =%7.3f " xx 3, (:$!x,:$!y,:$!r)».kv }
}
sub circle($x,$y,$r) { Circle.new: :$x, :$y, :$r }
sub solve-Apollonius([\c1, \c2, \c3], [\s1, \s2, \s3]) {
my \𝑣11 = 2 * c2.x - 2 * c1.x;
my \𝑣12 = 2 * c2.y - 2 * c1.y;
my \𝑣13 = c... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
begin
writeln("Program path: " <& path(PROGRAM));
writeln("Program directory: " <& dir(PROGRAM));
writeln("Program file: " <& file(PROGRAM));
end func; |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Sidef | Sidef | say __MAIN__;
if (__MAIN__ != __FILE__) {
say "This file has been included!";
} |
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,... | #Raku | Raku | constant limit = 100;
for [X] [^limit] xx 3 -> (\a, \b, \c) {
say [a, b, c] if a < b < c and a**2 + b**2 == c**2
} |
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... | #PureBasic | PureBasic | If problem = 1
End
EndIf |
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... | #Python | Python | import sys
if problem:
sys.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
| #Pascal | Pascal |
program PrimesByWilson;
uses SysUtils;
(* Function to return whether 32-bit unsigned n is prime.
Applies Wilson's theorem with full calculation of (n - 1)! modulo n. *)
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1... |
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 ... | #Python | Python | def isPrime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
if n % 3 == 0:
return n == 3
d = 5
while d * d <= n:
if n % d == 0:
return False
d += 2
if n % d == 0:
return False
d += 4
return True
def gen... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace PrimeDecomposition
{
class Program
{
static void Main(string[] args)
{
GetPrimes(12);
}
static List<int> GetPrimes(decimal n)
{
List<int> storage = new List<int>();
while (n ... |
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 |... | #AutoHotkey | AutoHotkey | VarSetCapacity(var, 100) ; allocate memory
NumPut(87, var, 0, "Char") ; store 87 at offset 0
MsgBox % NumGet(var, 0, "Char") ; get character at offset 0 (87)
MsgBox % &var ; address of contents pointed to by var structure
MsgBox % *&var ; integer at address of var contents (87) |
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 |... | #BBC_BASIC | BBC BASIC | REM Pointer to integer variable:
pointer_to_varA = ^varA%
!pointer_to_varA = 123456
PRINT !pointer_to_varA
REM Pointer to variant variable:
pointer_to_varB = ^varB
|pointer_to_varB = PI
PRINT |pointer_to_varB
REM Pointer to procedure:
PROCmyproc : REM conv... |
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.... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program areaPlot64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM... |
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
| #ALGOL_68 | ALGOL 68 | # Algol 68 provides for polymorphic operators but not procedures #
# define the CIRCLE and POINT modes #
MODE POINT = STRUCT( REAL x, y );
MODE CIRCLE = STRUCT( REAL x, y, r );
# PRINT operator #
O... |
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,... | #AutoHotkey | AutoHotkey | PokerHand(hand){
StringUpper, hand, hand
Sort, hand, FCardSort D%A_Space%
cardSeq := RegExReplace(hand, "[^2-9TJQKA]")
Straight:= InStr("23456789TJQKA", cardSeq) || (cardSeq = "2345A") ? true : false
hand := cardSeq = "2345A" ? RegExReplace(hand, "(.*)\h(A.)", "$2 $1") : hand
Royal := InStr(hand, "A") ? "Royal... |
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
... | #ALGOL_W | ALGOL W | begin
% returns the population count (number of bits on) of the non-negative integer n %
integer procedure populationCount( integer value n ) ;
begin
integer v, count;
v := n;
count := 0;
while v > 0 do begin
if ... |
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... | #C.2B.2B | C++ |
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
typedef vector<double> Poly;
// does: prints all members of vector
// input: c - ASCII char with the name of the vector
// A - reference to polynomial (vector)
void Print(char name, const Poly &A) {
cout << name << "(" << A.si... |
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... | #Delphi | Delphi | program PolymorphicCopy;
type
T = class
function Name:String; virtual;
function Clone:T; virtual;
end;
S = class(T)
function Name:String; override;
function Clone:T; override;
end;
function T.Name :String; begin Exit('T') end;
function T.Clone:T; begin Exit(T.Create)end;
functio... |
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... | #Kotlin | Kotlin | // version 1.1.0
import java.awt.*
import java.awt.event.ActionEvent
import javax.swing.*
class PolySpiral() : JPanel() {
private var inc = 0.0
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(40) {
inc = (inc + 0.05) % 360.0
repaint... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
void polyRegression(const std::vector<int>& x, const std::vector<int>& y) {
int n = x.size();
std::vector<int> r(n);
std::iota(r.begin(), r.end(), 0);
double xm = std::accumulate(x.begin(), x.end(), 0.0) / x.size();
doub... |
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... | #BBC_BASIC | BBC BASIC | DIM list$(3) : list$() = "1", "2", "3", "4"
PRINT FNpowerset(list$())
END
DEF FNpowerset(list$())
IF DIM(list$(),1) > 31 ERROR 100, "Set too large to represent as integer"
LOCAL i%, j%, s$
s$ = "{"
FOR i% = 0 TO (2 << DIM(list$(),1)) - 1
s$ += "{"
FOR j%... |
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
... | #AutoHotkey | AutoHotkey | MsgBox % IsPrime(1995937)
Loop
MsgBox % A_Index-3 . " is " . (IsPrime(A_Index-3) ? "" : "not ") . "prime."
IsPrime(n,k=2) { ; testing primality with trial divisors not multiple of 2,3,5, up to sqrt(n)
d := k+(k<7 ? 1+(k>2) : SubStr("6-----4---2-4---2-4---6-----2",Mod(k,30),1))
Return n < 3 ? n>1 : Mod(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 ... | #Clipper | Clipper | FUNCTION PriceFraction( npQuantDispensed )
LOCAL aPriceFraction := { {0,.06,.1},;
{.06,.11,.18}, ;
{.11,.16,.26}, ;
{.16,.21,.32}, ;
{.21,.26,.38}, ;
{.26,.31,.44}, ;
... |
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 ... | #Clojure | Clojure | (def values [10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100])
(defn price [v]
(format "%.2f" (double (/ (values (int (/ (- (* v 100) 1) 5))) 100)))) |
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... | #Forth | Forth | : .proper-divisors
dup 1 ?do
dup i mod 0= if i . then
loop cr drop
;
: proper-divisors-count
0 swap
dup 1 ?do
dup i mod 0= if swap 1 + swap then
loop drop
;
: rosetta-proper-divisors
cr
11 1 do
i . ." : " i .proper-divisors
loop
1 0
20000 2 do
i proper-divisors-count
2dup <... |
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... | #JavaScript | JavaScript | var 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,
heth: 1759/27720
};
var sum = 0;
var iterations = 1000000;
var cumulative = {};
var randomly = {};
for (var name in probabilities) {
sum += probabiliti... |
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... | #Haskell | Haskell | import Data.PQueue.Prio.Min
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")])) |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #REXX | REXX | /*REXX program solves the problem of Apollonius, named after the Greek Apollonius of */
/*────────────────────────────────────── Perga [Pergæus] (circa 262 BCE ──► 190 BCE). */
numeric digits 15; x1= 0; y1= 0; r1= 1
x2= 4; y2= 0; r2= 1
... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Smalltalk | Smalltalk | "exec" "gst" "-f" "$0" "$0" "$@"
"exit"
| program |
program := Smalltalk getArgv: 1.
Transcript show: 'Program: ', program; cr. |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Standard_ML | Standard ML | #!/usr/bin/env sml
let
val program = CommandLine.name ()
in
print ("Program: " ^ program ^ "\n")
end; |
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,... | #REXX | REXX | /*REXX program counts the number of Pythagorean triples that exist given a maximum */
/*──────────────────── perimeter of N, and also counts how many of them are primitives.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 100 ... |
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... | #QB64 | QB64 | INPUT "Press any key...", a$
IF 1 THEN SYSTEM |
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... | #R | R | if(problem) q(status=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... | #Racket | Racket |
#lang racket
(run-stuff)
(when (something-bad-happened) (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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + ... |
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
| #Phix | Phix | function wilson(integer n)
integer facmod = 1
for i=2 to n-1 do
facmod = remainder(facmod*i,n)
end for
return facmod+1=n
end function
atom t0 = time()
sequence primes = {}
integer p = 2
while length(primes)<1015 do
if wilson(p) then
primes &= p
end if
p += 1
end while
prin... |
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 ... | #R | R |
suppressMessages(library(gmp))
limit <- 1e6
result <- vector('numeric', 99)
prev_prime <- 2
count <- 0
getOutput <- function(transition) {
if (result[transition] == 0) return()
second <- transition %% 10
first <- (transition - second) / 10
cat(first,"->",second,"count:", sprintf("%6d",result[transitio... |
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 ... | #C.2B.2B | C++ | #include <iostream>
#include <gmpxx.h>
// This function template works for any type representing integers or
// nonnegative integers, and has the standard operator overloads for
// arithmetic and comparison operators, as well as explicit conversion
// from int.
//
// OutputIterator must be an output iterator with val... |
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 |... | #C_and_C.2B.2B | C and C++ | int var = 3;
int *pointer = &var; |
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 |... | #C.23 | C# |
static void Main(string[] args)
{
int p;
p = 1;
Console.WriteLine("Ref Before: " + p);
Value(ref p);
Console.WriteLine("Ref After : " + p);
p = 1;
Console.WriteLine("Val Before: " + p);
Value(p);
Console.WriteLine("Val After : " + p);
Console.ReadLine();
}
private static void Value(ref int 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.... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
DEFINE BUF_SIZE="100"
DEFINE REAL_SIZE="3"
TYPE Settings=[
INT xMin,xMax,xStep,yMin,yMax,yStep
INT xLeft,xRight,yTop,yBottom
INT tickLength]
BYTE ARRAY xs(BUF_SIZE),ys(BUF_SIZE)
BYTE count=[0]
PTR FUNC GetXPtr(BYTE i)
RETURN (xs+3*i)
PTR... |
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.... | #Ada | Ada |
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Handlers; use Gtk.Handlers;
with Glib; use Glib;
with Gtk.Extra.Plot; use Gtk.Extra.Plot;
with Gtk.Extra.Plot_Data; use Gtk.Extra.Plot_Data;
with Gtk.Extra.Plot_Canvas; use Gtk.Extra.Plot_Canvas;
with Gtk.Extra.Plot_Canva... |
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
| #Arturo | Arturo | define :point [x,y][
init: [
ensure -> is? :floating this\x
ensure -> is? :floating this\y
]
print: [
render "point (x: |this\x|, y: |this\y|)"
]
]
define :circle [center,radius][
init: [
ensure -> is? :point this\center
ensure -> is? :floating this\radius... |
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
| #AutoHotkey | AutoHotkey | MyPoint := new Point(1, 8)
MyPoint.Print()
MyCircle := new Circle(4, 7, 9)
MyCircle2 := MyCircle.Copy()
MyCircle.SetX(2) ;Assignment method
MyCircle.y := 3 ;Direct assignment
MyCircle.Print()
MyCircle2.Print()
MyCircle.SetX(100), MyCircle.SetY(1000), MyCircle.r := 10000
MsgBox, % MyCircle.__Class
. "`n`nx:`t" MyCirc... |
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,... | #C | C | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define FACES "23456789tjqka"
#define SUITS "shdc"
typedef int bool;
typedef struct {
int face; /* FACES map to 0..12 respectively */
char suit;
} card;
card cards[5];
int compare_card(const... |
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
... | #APL | APL |
APL (DYALOG APL)
popDemo←{⎕IO←0
N←⍵
⍝ popCount: Does a popCount of integers (8-32 bits) or floats (64-bits) that can be represented as integers
popCount←{
i2bits←{∊+/2⊥⍣¯1⊣⍵} ⍝ Use ⊥⍣¯1 (inverted decode) for ⊤ (encode) to automatically detect nubits needed
+/i2bits ⍵ ⍝ Coun... |
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... | #Clojure | Clojure | (defn grevlex [term1 term2]
(let [grade1 (reduce +' term1)
grade2 (reduce +' term2)
comp (- grade2 grade1)] ;; total degree
(if (not= 0 comp)
comp
(loop [term1 term1
term2 term2]
(if (empty? term1)
0
(let [grade1 (last term1)
gra... |
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... | #E | E | def deSubgraphKit := <elib:serial.deSubgraphKit>
def copy(object) {
return deSubgraphKit.recognize(object, deSubgraphKit.makeBuilder())
} |
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... | #EchoLisp | EchoLisp |
(lib 'types)
(lib 'struct)
(struct T (integer:x)) ;; super class
(struct S T (integer:y)) ;; sub class
(struct K (T:box)) ;; container class, box must be of type T, or derived
(define k-source (K (S 33 42)))
(define k-copy (copy k-source))
k-source
→ #<K> (#<S> (33 42)) ;; new container, with a S in box
k-... |
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... | #Lua | Lua | function love.load ()
love.window.setTitle("Polyspiral")
incr = 0
end
function love.update (dt)
incr = (incr + 0.05) % 360
x1 = love.graphics.getWidth() / 2
y1 = love.graphics.getHeight() / 2
length = 5
angle = incr
end
function love.draw ()
for i = 1, 150 do
x2 = x1 + math.c... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | linedata = {};
Dynamic[Graphics[Line[linedata], PlotRange -> 1000]]
Do[
linedata = AnglePath[{#, \[Theta]} & /@ Range[5, 300, 3]];
Pause[0.1];
,
{\[Theta], Subdivide[0.1, 1, 100]}
] |
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... | #Common_Lisp | Common Lisp | ;; Least square fit of a polynomial of order n the x-y-curve.
(defun polyfit (x y n)
(let* ((m (cadr (array-dimensions x)))
(A (make-array `(,m ,(+ n 1)) :initial-element 0)))
(loop for i from 0 to (- m 1) do
(loop for j from 0 to n do
(setf (aref A i j)
(e... |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #BQN | BQN | P ← (⥊·↕2⥊˜≠)/¨< |
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
... | #AutoIt | AutoIt | #cs ----------------------------------------------------------------------------
AutoIt Version: 3.3.8.1
Author: Alexander Alvonellos
Script Function:
Perform primality test on a given integer $number.
RETURNS: TRUE/FALSE
#ce -------------------------------------------------------------------------... |
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 ... | #Common_Lisp | Common Lisp | (defun scale (value)
(cond ((minusp value) (error "invalid value: ~A" value))
((< value 0.06) 0.10)
((< value 0.11) 0.18)
((< value 0.16) 0.26)
((< value 0.21) 0.32)
((< value 0.26) 0.38)
((< value 0.31) 0.44)
((< value 0.36) 0.50)
((< value 0.41) 0.54)
... |
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... | #Fortran | Fortran |
function icntprop(num )
icnt=0
do i=1 , num-1
if (mod(num , i) .eq. 0) then
icnt = icnt + 1
if (num .lt. 11) print *,' ',i
end if
end do
icntprop = icnt
end function
limit = 20000
maxcnt = 0
print *,'N divis... |
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... | #Julia | Julia | using Printf
p = [1/i for i in 5:11]
plen = length(p)
q = [0.0, [sum(p[1:i]) for i = 1:plen]]
plab = [char(i) for i in 0x05d0:(0x05d0+plen)]
hi = 10^6
push!(p, 1.0 - sum(p))
plen += 1
accum = zeros(Int, plen)
for i in 1:hi
accum[sum(rand() .>= q)] += 1
end
r = accum/hi
println("Rates at which items are se... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val letters = arrayOf("aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth")
val actual = IntArray(8)
val probs = doubleArrayOf(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 0.0)
val cumProbs = DoubleArray(8)
cumProbs[0] = pr... |
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... | #Icon_and_Unicon | Icon and Unicon | import Utils # For Closure class
import Collections # For Heap (dense priority queue) class
procedure main()
pq := Heap(, Closure("[]",Arg,1) )
pq.add([3, "Clear drains"])
pq.add([4, "Feed cat"])
pq.add([5, "Make tea"])
pq.add([1, "Solve RC tasks"])
pq.add([2, "Tax return"])
while task :... |
http://rosettacode.org/wiki/Problem_of_Apollonius | Problem of Apollonius |
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the ... | #Ruby | Ruby | class Circle
def initialize(x, y, r)
@x, @y, @r = [x, y, r].map(&:to_f)
end
attr_reader :x, :y, :r
def self.apollonius(c1, c2, c3, s1=1, s2=1, s3=1)
x1, y1, r1 = c1.x, c1.y, c1.r
x2, y2, r2 = c2.x, c2.y, c2.r
x3, y3, r3 = c3.x, c3.y, c3.r
v11 = 2*x2 - 2*x1
v12 = 2*y2 - 2*y1
v13 =... |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #Tcl | Tcl | #!/usr/bin/env tclsh
proc main {args} {
set program $::argv0
puts "Program: $program"
}
if {$::argv0 eq [info script]} {
main {*}$::argv
} |
http://rosettacode.org/wiki/Program_name | Program name | The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A... | #TXR | TXR | #!/usr/local/bin/txr -B
@(bind my-name @self-path) |
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,... | #Ring | Ring |
size = 100
sum = 0
prime = 0
for i = 1 to size
for j = i + 1 to size
for k = 1 to size
if pow(i,2) + pow(j,2) = pow(k,2) and (i+j+k) < 101
if gcd(i,j) = 1 prime += 1 ok
sum += 1
see "" + i + " " + j + " " + k + nl ok
next
next
next
see "Total ... |
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... | #Raku | Raku | if $problem { exit $error-code } |
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... | #REBOL | REBOL | if error? try [6 / 0] [quit] |
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
| #Plain_English | Plain English | To run:
Start up.
Show some primes (via Wilson's theorem).
Wait for the escape key.
Shut down.
The maximum representable factorial is a number equal to 12. \32-bit signed
To show some primes (via Wilson's theorem):
If a counter is past the maximum representable factorial, exit.
If the counter is prime (via Wilson... |
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.