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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#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 } MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")
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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 end of output to n end repeat return output
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#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.WriteLine();   for (int x = 0; x < 10; x++) { Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", ((double)x) / 10 + 0.05, SpecialRound(((double)x) / 10 + 0.05)); }   Console.WriteLine(); Console.WriteLine("In: {0:0.00}, Out: {1:0.00}", 1.01, SpecialRound(1.01));   Console.Read(); }   private static double SpecialRound(double inValue) { if (inValue > 1) return 1;   double[] Splitters = new double[] { 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[] replacements = new double[] { 0.10 , 0.18 , 0.26 , 0.32 , 0.38 , 0.44 , 0.50 , 0.54 , 0.58 , 0.62 , 0.66 , 0.70 , 0.74 , 0.78 , 0.82 , 0.86 , 0.90 , 0.94 , 0.98 , 1.00 };   for (int x = 0; x < Splitters.Length - 1; x++) { if (inValue >= Splitters[x] && inValue < Splitters[x + 1]) { return replacements[x]; } }   return inValue; } } }
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#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 divisors.\n" printf
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 involved, this is subject to rounding errors). 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 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#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 (target proportions) prtn (partitions corresponding to target proportions) da (distribution of actual values among partitions) pa (actual proportions) )
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#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[i], self[j] = self[j], self[i] } func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) } func (self *TaskPQ) Pop() (popped interface{}) { popped = (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return }   func main() { pq := &TaskPQ{{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}}   // heapify heap.Init(pq)   // enqueue heap.Push(pq, Task{2, "Tax return"})   for pq.Len() != 0 { // dequeue fmt.Println(heap.Pop(pq)) } }
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 example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#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(x=2.0, y=0.8333333333333333, r=1.1666666666666667) ''' x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3   v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1   v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2   w12 = v12/v11 w13 = v13/v11 w14 = v14/v11   w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14   P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q   a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1   # Find a root of a quadratic equation. This requires the circle centers not to be e.g. colinear D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a)   xs = M+N*rs ys = P+Q*rs   return Circle(xs, ys, rs)   if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) #Expects "Circle[x=2.00,y=2.10,r=3.90]" (green circle in image) print(solveApollonius(c1, c2, c3, -1, -1, -1)) #Expects "Circle[x=2.00,y=0.83,r=1.17]" (red circle in image)
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 ARGV. See also Command-line arguments Examples from GitHub.
#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 ARGV. See also Command-line arguments Examples from GitHub.
#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-index (lambda (x) (string-contains x "-s")) (argv)))) (if (number? s-index) (cons 'interpreted (list-ref (argv) (+ 1 s-index))) (cons 'unknown ""))) (cons 'compiled (car (argv)))))   (if (equal? (car (program)) 'compiled) (main (cdr (argv))))
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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#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 n < m, a simple close non-tight bound on n is P(n, n) < P₀. For each of these the exact set of m's can be enumerated.   Each primitive triple with perimeter p represents one triple for each kp ≤ P₀, of which there are floor(P₀/p) k's. |#   (define (P n m) (* 2 m (+ m n))) (define (number-of-triples P₀) (for/fold ([primitive 0] [all 0]) ([n (in-naturals 1)] #:break (>= (P n n) P₀)) (for*/fold ([primitive′ primitive] [all′ all]) ([m (in-naturals (+ n 1))] #:break (> (P n m) P₀) #:when (and (odd? (- m n)) (coprime? m n))) (values (+ primitive′ 1) (+ all′ (quotient P₀ (P n m)))))))     (define (print-results P₀) (define-values (primitive all) (number-of-triples P₀)) (printf "~a ~a:\n ~a, ~a.\n" "Number of Pythagorean triples and primitive triples with perimeter ≤" P₀ all primitive)) (print-results 100) (time (print-results (* 100 1000 1000)))   #| Number of Pythagorean triples and primitive triples with perimeter ≤ 100: 17, 7. Number of Pythagorean triples and primitive triples with perimeter ≤ 100000000: 113236940, 7023027. cpu time: 11976 real time: 12215 gc time: 2381 |#
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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 "Prime numbers between 2 and 100:" echo primes.join(" ")
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 the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#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(Results) :- forall( member(tr(D1, D2, Count), Results), format("~d -> ~d: ~d~n", [D1, D2, Count])).     % count results   tally(L, R) :- tally(L, [], R). tally([_], T, T) :- !. tally([A|As], T0, R) :- [B|_] = As, Da is A mod 10, Db is B mod 10, count(Da, Db, T0, T1), tally(As, T1, R).   count(D1, D2, [], [tr(D1, D2, 1)]) :- !. count(D1, D2, [tr(D1, D2, N)|Ts], [tr(D1, D2, Sn)|Ts]) :- succ(N, Sn), !. count(D1, D2, [T|Ts], [T|Us]) :- count(D1, D2, Ts, Us).     % implement a prime sieve   sieve(Limit, Ps) :- numlist(2, Limit, Ns), sieve(Limit, Ns, Ps).   sieve(Limit, W, W) :- W = [P|_], P*P > Limit, !. sieve(Limit, [P|Xs], [P|Ys]) :- Q is P*P, remove_multiples(P, Q, Xs, R), sieve(Limit, R, Ys).   remove_multiples(_, _, [], []) :- !. remove_multiples(N, M, [A|As], R) :- A =:= M, !, remove_multiples(N, M, As, R). remove_multiples(N, M, [A|As], [A|R]) :- A < M, !, remove_multiples(N, M, As, R). remove_multiples(N, M, L, R) :- plus(M, N, M2), remove_multiples(N, M2, L, R).  
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 /* because 2^64 is too large for xint */   uint8_t *pbits;   #define MAX_PRIME (~(pint)0) #define MAX_PRIME_SQ 65535U #define PBITS (MAX_PRIME / 30 + 1)   pint next_prime(pint); int is_prime(xint); void sieve(pint);   uint8_t bit_pos[30] = { 0, 1<<0, 0, 0, 0, 0, 0, 1<<1, 0, 0, 0, 1<<2, 0, 1<<3, 0, 0, 0, 1<<4, 0, 1<<5, 0, 0, 0, 1<<6, 0, 0, 0, 0, 0, 1<<7, };   uint8_t rem_num[] = { 1, 7, 11, 13, 17, 19, 23, 29 };   void init_primes() { FILE *fp; pint s, tgt = 4;   if (!(pbits = malloc(PBITS))) { perror("malloc"); exit(1); }   if ((fp = fopen("primebits", "r"))) { fread(pbits, 1, PBITS, fp); fclose(fp); return; }   memset(pbits, 255, PBITS); for (s = 7; s <= MAX_PRIME_SQ; s = next_prime(s)) { if (s > tgt) { tgt *= 2; fprintf(stderr, "sieve %"PRIuPINT"\n", s); } sieve(s); } fp = fopen("primebits", "w"); fwrite(pbits, 1, PBITS, fp); fclose(fp); }   int is_prime(xint x) { pint p; if (x > 5) { if (x < MAX_PRIME) return pbits[x/30] & bit_pos[x % 30];   for (p = 2; p && (xint)p * p <= x; p = next_prime(p)) if (x % p == 0) return 0;   return 1; } return x == 2 || x == 3 || x == 5; }   void sieve(pint p) { unsigned char b[8]; off_t ofs[8]; int i, q;   for (i = 0; i < 8; i++) { q = rem_num[i] * p; b[i] = ~bit_pos[q % 30]; ofs[i] = q / 30; }   for (q = ofs[1], i = 7; i; i--) ofs[i] -= ofs[i-1];   for (ofs[0] = p, i = 1; i < 8; i++) ofs[0] -= ofs[i];   for (i = 1; q < PBITS; q += ofs[i = (i + 1) & 7]) pbits[q] &= b[i]; }   pint next_prime(pint p) { off_t addr; uint8_t bits, rem;   if (p > 5) { addr = p / 30; bits = bit_pos[ p % 30 ] << 1; for (rem = 0; (1 << rem) < bits; rem++); while (pbits[addr] < bits || !bits) { if (++addr >= PBITS) return 0; bits = 1; rem = 0; } if (addr >= PBITS) return 0; while (!(pbits[addr] & bits)) { rem++; bits <<= 1; } return p = addr * 30 + rem_num[rem]; }   switch(p) { case 2: return 3; case 3: return 5; case 5: return 7; } return 2; }   int decompose(xint n, xint *f) { pint p = 0; int i = 0;   /* check small primes: not strictly necessary */ if (n <= MAX_PRIME && is_prime(n)) { f[0] = n; return 1; }   while (n >= (xint)p * p) { if (!(p = next_prime(p))) break; while (n % p == 0) { n /= p; f[i++] = p; } } if (n > 1) f[i++] = n; return i; }   int main() { int i, len; pint p = 0; xint f[MAX_FACTORS], po;   init_primes();   for (p = 1; p < 64; p++) { po = (1LLU << p) - 1; printf("2^%"PRIuPINT" - 1 = %"PRIuXINT, p, po); fflush(stdout); if ((len = decompose(po, f)) > 1) for (i = 0; i < len; i++) printf(" %c %"PRIuXINT, i?'x':'=', f[i]); putchar('\n'); }   return 0; }
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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; function Create return Point; function Create(X : Integer) return Point; function Create(X, Y : Integer) return Point;   private type Point is tagged record X : Integer := 0; Y : Integer := 0; end record; end Shapes;
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 Point (x, y) { public function print { println ("Circle") }   public function getR { return r } public function setR(nr) { r = nr } }   var p = new Point (1, 2) var c = new Circle (1, 2, 3) p.print() c.print()    
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#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 & !f V s = 0 L(fc) faceCount I fc != 0 s++ E s = 0 I s == 5 L.break   st = (s == 5) | (s == 4 & faceCount[0] != 0 & faceCount[1] == 0)   I st & fl {R ‘straight-flush’} E I f {R ‘four-of-a-kind’} E I p1 & t {R ‘full-house’} E I fl {R ‘flush’} E I st {R ‘straight’} E I t {R ‘three-of-a-kind’} E I p1 & p2 {R ‘two-pair’} E I p1 {R ‘one-pair’} E {R ‘high-card’}   F analyzeHand(inHand) V handLen = 5 V face = ‘A23456789TJQK’ V suit = ‘SHCD’ V errorMessage = ‘invalid hand.’   V hand = sorted(inHand.split(‘ ’)) I hand.len != handLen R errorMessage I Set(hand).len != handLen R errorMessage‘ Duplicated cards.’   V faceCount = [0] * face.len V suitCount = [0] * suit.len L(card) hand I card.len != 2 R errorMessage V? n = face.find(card[0]) V? l = suit.find(card[1]) I n == N | l == N R errorMessage faceCount[n]++ suitCount[l]++   R analyzeHandHelper(faceCount, suitCount)   L(hand) [‘2H 2D 2S KS QD’, ‘2H 5H 7D 8S 9D’, ‘AH 2D 3S 4S 5S’, ‘2H 3H 2D 3S 3D’, ‘2H 7H 2D 3S 3D’, ‘2H 7H 7D 7S 7C’, ‘TH JH QH KH AH’, ‘4H 4C KC 5D TC’, ‘QC TC 7C 6C 4C’] print(hand‘: ’analyzeHand(hand))
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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#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 number THEN result +:= 1 FI; number OVERAB 2 OD; result END # population # ;   # population count of 3^0, 3^1, 3*2, ..., 3^29 # LONG INT power of three := 1; print( ( "3^x pop counts:" ) ); FOR power FROM 0 TO 29 DO print( ( " ", whole( population count( power of three ), 0 ) ) ); power of three *:= 3 OD; print( ( newline ) ); # print the first thirty evil numbers (even population count) # INT evil count := 0; print( ( "evil numbers  :" ) ); FOR n FROM 0 WHILE evil count < 30 DO IF NOT ODD population count( n ) THEN print( ( " ", whole( n, 0 ) ) ); evil count +:= 1 FI OD; print( ( newline ) ); # print the first thirty odious numbers (odd population count) # INT odious count := 0; print( ( "odious numbers:" ) ); FOR n WHILE odious count < 30 DO IF ODD population count( n ) THEN print( ( " ", whole( n, 0 ) ) ); odious count +:= 1 FI OD; print( ( newline ) )  
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#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 PolyDegree(double[] p) { for (int i = p.Length - 1; i >= 0; --i) { if (p[i] != 0.0) return i; } return int.MinValue; }   static double[] PolyShiftRight(double[] p, int places) { if (places <= 0) return p; int pd = PolyDegree(p); if (pd + places >= p.Length) { throw new ArgumentOutOfRangeException("The number of places to be shifted is too large"); } double[] d = new double[p.Length]; p.CopyTo(d, 0); for (int i = pd; i >= 0; --i) { d[i + places] = d[i]; d[i] = 0.0; } return d; }   static void PolyMultiply(double[] p, double m) { for (int i = 0; i < p.Length; ++i) { p[i] *= m; } }   static void PolySubtract(double[] p, double[] s) { for (int i = 0; i < p.Length; ++i) { p[i] -= s[i]; } }   static Solution PolyLongDiv(double[] n, double[] d) { if (n.Length != d.Length) { throw new ArgumentException("Numerator and denominator vectors must have the same size"); } int nd = PolyDegree(n); int dd = PolyDegree(d); if (dd < 0) { throw new ArgumentException("Divisor must have at least one one-zero coefficient"); } if (nd < dd) { throw new ArgumentException("The degree of the divisor cannot exceed that of the numerator"); } double[] n2 = new double[n.Length]; n.CopyTo(n2, 0); double[] q = new double[n.Length]; while (nd >= dd) { double[] d2 = PolyShiftRight(d, nd - dd); q[nd - dd] = n2[nd] / d2[nd]; PolyMultiply(d2, q[nd - dd]); PolySubtract(n2, d2); nd = PolyDegree(n2); } return new Solution(q, n2); }   static void PolyShow(double[] p) { int pd = PolyDegree(p); for (int i = pd; i >= 0; --i) { double coeff = p[i]; if (coeff == 0.0) continue; if (coeff == 1.0) { if (i < pd) { Console.Write(" + "); } } else if (coeff == -1.0) { if (i < pd) { Console.Write(" - "); } else { Console.Write("-"); } } else if (coeff < 0.0) { if (i < pd) { Console.Write(" - {0:F1}", -coeff); } else { Console.Write("{0:F1}", coeff); } } else { if (i < pd) { Console.Write(" + {0:F1}", coeff); } else { Console.Write("{0:F1}", coeff); } } if (i > 1) Console.Write("x^{0}", i); else if (i == 1) Console.Write("x"); } Console.WriteLine(); }   static void Main(string[] args) { double[] n = { -42.0, 0.0, -12.0, 1.0 }; double[] d = { -3.0, 1.0, 0.0, 0.0 }; Console.Write("Numerator  : "); PolyShow(n); Console.Write("Denominator : "); PolyShow(d); Console.WriteLine("-------------------------------------"); Solution sol = PolyLongDiv(n, d); Console.Write("Quotient  : "); PolyShow(sol.Quotient); Console.Write("Remainder  : "); PolyShow(sol.Remainder); } } }
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#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 = orig.duplicate();   writeln(orig); writeln(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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#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: coefficients c, it, sc, sc2, sc3 are selected to fit canvas. var c=Math.PI*rng, it=c/w2, sc=2, sc2=50, sc3=0.1, t, x, y; console.log("Polyspiral PARs rng,w2,d:", rng, "/", w2, "/", d); if (rng>1000) {sc=sc3} ctx.beginPath(); for(var i=0; i<sc2*c; i++) { t=it*i; x = sc*t*Math.cos(d*t)+w2; y = sc*t*Math.sin(d*t)+w2; ctx.lineTo(x, y); }//fend i ctx.stroke(); } // ****************************************** // pspiral() - Generating and plotting Polyspirals function pspiral() { // Setting basic vars for canvas and inpu parameters var cvs = document.getElementById('cvsId'); var ctx = cvs.getContext("2d"); var w = cvs.width, h = cvs.height; var w2=w/2; var clr = document.getElementById("color").value; // color var d = document.getElementById("dir").value; // direction var rng = document.getElementById("rng").value; // range rng=Number(rng); ctx.fillStyle="white"; ctx.fillRect(0,0,w,h); ctx.strokeStyle=clr; // Plotting spiral. ppsp(ctx, rng, w2, d) }//func end </script></head> <body style="font-family: arial, helvatica, sans-serif;"> <b>Color: </b> <select id="color"> <option value="red">red</option> <option value="darkred" selected>darkred</option> <option value="green">green</option> <option value="darkgreen">darkgreen</option> <option value="blue">blue</option> <option value="navy">navy</option> <option value="brown">brown</option> <option value="maroon">maroon</option> <option value="black">black</option> </select>&nbsp;&nbsp; <b>Direction: </b> <input id="dir" value="1" type="number" min="-1" max="1" size="1">&nbsp;&nbsp; <b>Range: </b> <input id="rng" value="10" type="number" min="10" max="4000" step="10" size="4">&nbsp;&nbsp; <input type="button" value="Plot it!" onclick="pspiral();">&nbsp;&nbsp;<br> <h3>&nbsp;&nbsp;&nbsp;&nbsp;Polyspiral</h3> <canvas id="cvsId" width="640" height="640" style="border: 2px inset;"></canvas> </body> </html>  
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#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) = sqrt(v.x * v.x + v.y * v.y)   function drawline(ctx, p1, p2, color, width=1) move_to(ctx, p1.x, p1.y) set_source(ctx, color) line_to(ctx, p2.x, p2.y) set_line_width(ctx, width) stroke(ctx) end   @guarded draw(can) do widget δ(r, θ) = Vec2(r * cospi(θ/180), r * sinpi(θ/180)) nextpoint(p, r, θ) = (dp = δ(r, θ); Point(p.x + dp.x, p.y + dp.y)) colorindex = (angleiters[1] % 5) + 1 colr = colorseq[colorindex] ctx = getgc(can) h = height(can) w = width(can) x = 0.5 * w y = 0.5 * h θ = angleiters[2] * rand() * 3 δθ = angleiters[2] r = 5 δr = 3 p1 = Point(x, y) for i in 1:drawiters if angleiters[3] == 0 set_source(ctx, colorant"gray90") rectangle(ctx, 0, 0, w, h) fill(ctx) continue end p2 = nextpoint(p1, r, θ) drawline(ctx, p1, p2, colr, 2) θ = θ + δθ r = r + δr p1 = p2 end end   show(can)   while true angleiters[2] = angles[angleiters[1] % 3 + 1] angleiters[1] += 1 angleiters[3] = angleiters[3] == 0 ? 1 : 0 draw(can) yield() sleep(0.5) end  
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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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); var yv = new DenseVector(y).ToColumnMatrix(); QR<double> qr = v.QR(); // Math.Net doesn't have an "economy" QR, so: // cut R short to square upper triangle, then recompute Q var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1); var q = v.Multiply(r.Inverse()); var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv)); return p.Column(0).ToArray(); }
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#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 , 0.51 , 0.56 , 0.61 , 0.66 , 0.71 , 0.76 , 0.81 , 0.86 , 0.91 , 0.96 , 1.01 } ; double replacements [] = { 0.10 , 0.18 , 0.26 , 0.32 , 0.38 , 0.44 , 0.50 , 0.54 , 0.58 , 0.62 , 0.66 , 0.70 , 0.74 , 0.78 , 0.82 , 0.86 , 0.90 , 0.94 , 0.98 , 1.00 } ; double number = 0.1 ; std::cout << "Enter a fractional number between 0 and 1 ( 0 to end )!\n" ; std::cin >> number ; while ( number != 0 ) { if ( number < 0 || number > 1 ) { std::cerr << "Error! Only positive values between 0 and 1 are allowed!\n" ; return 1 ; } int n = 0 ; while ( ! ( number >= froms[ n ] && number < tos[ n ] ) ) n++ ; std::cout << "-->" << replacements[ n ] << '\n' ; std::cout << "Enter a fractional number ( 0 to end )!\n" ; std::cin >> number ; } return 0 ; }  
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#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; .;   for n = 1 to 10 do Divisors(n);  !!(n,' ',[d); od;   record:=0; champ:=1; for n=2 to 20000 do Divisors(n); m:=Cols[d]; {this gets the length of the array} if m > record then champ:=n; record:=m; fi; od;   !!('The number up to 20,000 with the most divisors was ',champ,' with ',record,' divisors.');
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 involved, this is subject to rounding errors). 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 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#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= expect; this.mapping= mapping; } }   static Expv[] items= {new Expv("aleph", 0, 0.0, 0.0), new Expv("beth", 0, 0.0, 0.0), new Expv("gimel", 0, 0.0, 0.0), new Expv("daleth", 0, 0.0, 0.0), new Expv("he", 0, 0.0, 0.0), new Expv("waw", 0, 0.0, 0.0), new Expv("zayin", 0, 0.0, 0.0), new Expv("heth", 0, 0.0, 0.0)};   public static void main(String[] args){ int i, j; double rnum, tsum= 0.0;   for(i= 0, rnum= 5.0;i < 7;i++, rnum+= 1.0){ items[i].expect= 1.0 / rnum; tsum+= items[i].expect; } items[7].expect= 1.0 - tsum;   items[0].mapping= 1.0 / 5.0; for(i= 1;i < 7;i++){ items[i].mapping= items[i - 1].mapping + 1.0 / ((double)i + 5.0); } items[7].mapping= 1.0;     for(i= 0;i < TRIALS;i++){ rnum= Math.random(); for(j= 0;j < 8;j++){ if(rnum < items[j].mapping){ items[j].probcount++; break; } } }   System.out.printf("Trials: %d\n", TRIALS); System.out.printf("Items: "); for(i= 0;i < 8;i++) System.out.printf("%-8s ", items[i].name); System.out.printf("\nTarget prob.: "); for(i= 0;i < 8;i++) System.out.printf("%8.6f ", items[i].expect); System.out.printf("\nAttained prob.: "); for(i= 0;i < 8;i++) System.out.printf("%8.6f ", (double)(items[i].probcount) / (double)TRIALS); System.out.printf("\n");   } }
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#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 new Task(priority: 5, name: 'Make tea') add new Task(priority: 1, name: 'Solve RC tasks') add new Task(priority: 2, name: 'Tax return')   while (!empty) { println remove() } }
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 example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#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)) (define r3 (circle-r c3))   (define v11 (- (* 2 x2) (* 2 x1))) (define v12 (- (* 2 y2) (* 2 y1))) (define v13 (+ (- (* x1 x1) (* x2 x2)) (- (* y1 y1) (* y2 y2)) (- (* r2 r2) (* r1 r1)))) (define v14 (- (* 2 s2 r2) (* 2 s1 r1)))   (define v21 (- (* 2 x3) (* 2 x2))) (define v22 (- (* 2 y3) (* 2 y2))) (define v23 (+ (- (* x2 x2) (* x3 x3)) (- (* y2 y2) (* y3 y3)) (- (* r3 r3) (* r2 r2)))) (define v24 (- (* 2 s3 r3) (* 2 s2 r2)))   (define w12 (/ v12 v11)) (define w13 (/ v13 v11)) (define w14 (/ v14 v11))   (define w22 (- (/ v22 v21) w12)) (define w23 (- (/ v23 v21) w13)) (define w24 (- (/ v24 v21) w14))   (define P (- (/ w23 w22))) (define Q (/ w24 w22)) (define M (- (+ (* w12 P) w13))) (define N (- w14 (* w12 Q)))   (define a (+ (* N N) (* Q Q) -1)) (define b (+ (- (* 2 M N) (* 2 N x1)) (- (* 2 P Q) (* 2 Q y1)) (* 2 s1 r1))) (define c (- (+ (* x1 x1) (* M M) (* P P) (* y1 y1)) (+ (* 2 M x1) (* 2 P y1) (* r1 r1))))   (define D (- (* b b) (* 4 a c))) (define rs (/ (- (+ b (sqrt D))) (* 2 a))) (define xs (+ M (* N rs))) (define ys (+ P (* Q rs))) (circle xs ys rs))   (define c1 (circle 0.0 0.0 1.0)) (define c2 (circle 4.0 0.0 1.0)) (define c3 (circle 2.0 4.0 2.0))   ;; print solutions (apollonius c1 c2 c3 1.0 1.0 1.0) (apollonius c1 c2 c3 -1.0 -1.0 -1.0)   ;; visualize solutions (require racket/gui/base) (define (show-circles . circles+colors) (define f (new frame% [label "Apollonius"] [width 300] [height 300])) (define c (new canvas% [parent f] [paint-callback (lambda (canvas dc) (send* dc (set-origin 100 100) (set-scale 20 20) (set-pen "black" 1/10 'solid) (set-brush "white" 'transparent)) (for ([x circles+colors]) (if (string? x) (send dc set-pen x 1/5 'solid) (let ([x (circle-x x)] [y (circle-y x)] [r (circle-r x)]) (send dc draw-ellipse (- x r) (- y r) (* 2 r) (* 2 r))))))])) (send f show #t)) (show-circles "black" c1 c2 c3 "green" (apollonius c1 c2 c3 1.0 1.0 1.0) "red" (apollonius c1 c2 c3 -1.0 -1.0 -1.0))  
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 example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#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 = c1.x² - c2.x² + c1.y² - c2.y² - c1.r² + c2.r²; my \𝑣14 = 2 * s2 * c2.r - 2 * s1 * c1.r;   my \𝑣21 = 2 * c3.x - 2 * c2.x; my \𝑣22 = 2 * c3.y - 2 * c2.y; my \𝑣23 = c2.x² - c3.x² + c2.y² - c3.y² - c2.r² + c3.r²; my \𝑣24 = 2 * s3 * c3.r - 2 * s2 * c2.r;   my \𝑤12 = 𝑣12 / 𝑣11; my \𝑤13 = 𝑣13 / 𝑣11; my \𝑤14 = 𝑣14 / 𝑣11;   my \𝑤22 = 𝑣22 / 𝑣21 - 𝑤12; my \𝑤23 = 𝑣23 / 𝑣21 - 𝑤13; my \𝑤24 = 𝑣24 / 𝑣21 - 𝑤14;   my \𝑃 = -𝑤23 / 𝑤22; my \𝑄 = 𝑤24 / 𝑤22; my \𝑀 = -𝑤12 * 𝑃 - 𝑤13; my \𝑁 = 𝑤14 - 𝑤12 * 𝑄;   my \𝑎 = 𝑁² + 𝑄² - 1; my \𝑏 = 2 * 𝑀 * 𝑁 - 2 * 𝑁 * c1.x + 2 * 𝑃 * 𝑄 - 2 * 𝑄 * c1.y + 2 * s1 * c1.r; my \𝑐 = c1.x² + 𝑀² - 2 * 𝑀 * c1.x + 𝑃² + c1.y² - 2 * 𝑃 * c1.y - c1.r²;   my \𝐷 = 𝑏² - 4 * 𝑎 * 𝑐; my \rs = (-𝑏 - sqrt 𝐷) / (2 * 𝑎);   my \xs = 𝑀 + 𝑁 * rs; my \ys = 𝑃 + 𝑄 * rs;   circle(xs, ys, rs); }   my @c = circle(0, 0, 1), circle(4, 0, 1), circle(2, 4, 2); for ([X] [-1,1] xx 3) -> @i { say (solve-Apollonius @c, @i).gist; }
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 ARGV. See also Command-line arguments Examples from GitHub.
#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 ARGV. See also Command-line arguments Examples from GitHub.
#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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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; for m := 2 to n - 1 do begin f := (uint64(f) * uint64(m)) mod n; // typecast is needed end; result := (f = n - 1); end;   (* Function to return whether 32-bit unsigned n is prime. Applies Wilson's theorem with a short cut. *) function WilsonShortCut( n : longword) : boolean; var f, g, h, m, m2inc, r : longword; begin if n < 2 then begin result := false; exit; end; (* Part 1: Factorial (modulo n) of floor(sqrt(n)) *) f := 1; m := 1; m2inc := 3; // (m + 1)^2 - m^2 // Want to loop while m^2 <= n, but if n is close to 2^32 - 1 then least // m^2 > n overflows 32 bits. Work round this by looking at r = n - m^2. r := n - 1; while r >= m2inc do begin inc(m); f := (uint64(f) * uint64(m)) mod n; dec( r, m2inc); inc( m2inc, 2); end; (* Part 2: Euclid's algorithm: at the end, h = HCF( f, n) *) h := n; while f <> 0 do begin g := h mod f; h := f; f := g; end; result := (h = 1); end;   type TPrimalityTest = function( n : longword) : boolean; procedure ShowPrimes( isPrime : TPrimalityTest; minValue, maxValue : longword); var n : longword; begin WriteLn( 'Primes in ', minValue, '..', maxValue); for n := minValue to maxValue do if isPrime(n) then Write(' ', n); WriteLn; end;   (* Main routine *) begin WriteLn( 'By full calculation:'); ShowPrimes( @WilsonFullCalc, 1, 100); ShowPrimes( @WilsonFullCalc, 1000, 1100); WriteLn; WriteLn( 'Using the short cut:'); ShowPrimes( @WilsonShortCut, 1, 100); ShowPrimes( @WilsonShortCut, 1000, 1100); ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 {= 2^32 - 1}); end.  
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 the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#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 generatePrimes(): yield 2 yield 3   p = 5 while p > 0: if isPrime(p): yield p p += 2 if isPrime(p): yield p p += 4   g = generatePrimes() transMap = {} prev = None limit = 1000000 for _ in xrange(limit): prime = next(g) if prev: transition = (prev, prime %10) if transition in transMap: transMap[transition] += 1 else: transMap[transition] = 1 prev = prime % 10   print "First {:,} primes. Transitions prime % 10 > next-prime % 10.".format(limit) for trans in sorted(transMap): print "{0} -> {1} count {2:5} frequency: {3}%".format(trans[0], trans[1], transMap[trans], 100.0 * transMap[trans] / limit)
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 > 1) { int i = 1; while (true) { if (IsPrime(i)) { if (((decimal)n / i) == Math.Round((decimal) n / i)) { n /= i; storage.Add(i); break; } } i++; } } return storage; }   static bool IsPrime(int n) { if (n <= 1) return false; for (int i = 2; i <= Math.Sqrt(n); i++) if (n % i == 0) return false; return true; } } }
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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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 conventional call to initialise pointer_to_myproc = ^PROCmyproc PROC(pointer_to_myproc)   REM Pointer to function: pointer_to_myfunc = ^FNmyfunc PRINT FN(pointer_to_myfunc) END   DEF PROCmyproc PRINT "Executing myproc" ENDPROC   DEF FNmyfunc = "Returned from myfunc"
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 "../includeConstantesARM64.inc" .equ HAUTEUR, 22 .equ LARGEUR, 50 .equ MARGEGAUCHE, 10   /*******************************************/ /* Structures */ /********************************************/ /* structure for points */ .struct 0 point_posX: .struct point_posX + 8 point_posY: .struct point_posY + 8 point_end: /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessError: .asciz "Number of points too large !! \n" szCarriageReturn: .asciz "\n" szMessMovePos: .ascii "\033[" // cursor position posY: .byte '0' .byte '6' .ascii ";" posX: .byte '0' .byte '3' .asciz "H*" szMessEchelleX: .asciz "Y^ X=" szClear1: .byte 0x1B .byte 'c' // other console clear .byte 0 szMessPosEch: .ascii "\033[" // scale cursor position posY1: .byte '0' .byte '0' .ascii ";" posX1: .byte '0' .byte '0' .asciz "H"   //x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; //y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};   /* areas points */ tbPoints: .quad 0 // 1 .quad 27 // Data * 10 for integer operation .quad 1 // 2 .quad 28 .quad 2 // 3 .quad 314 .quad 3 // 4 .quad 381 .quad 4 // 5 .quad 580 .quad 5 // 6 .quad 762 .quad 6 // 7 .quad 1005 .quad 7 // 8 .quad 1300 .quad 8 // 9 .quad 1493 .quad 9 // 10 .quad 1800 /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sZoneConv: .skip 30 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program ldr x0,qAdrtbPoints // area address mov x1,10 // size mov x2,LARGEUR mov x3,HAUTEUR bl plotArea b 100f   100: // standard end of the program mov x0, 0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsZoneConv: .quad sZoneConv qAdrszCarriageReturn: .quad szCarriageReturn qAdrtbPoints: .quad tbPoints /************************************/ /* create graph */ /************************************/ /* x0 contains area points address */ /* x1 contains number points */ /* x2 contains graphic weight */ /* x3 contains graphic height */ /* REMARK : no save x9-x20 registers */ plotArea: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers cmp x1,x2 bge 99f mov x9,x0 mov x4,x1 ldr x10,qAdrposX ldr x11,qAdrposY mov x12,#0 // indice mov x13,point_end // element area size mov x17,0 // Y maxi mov x19,-1 // Y Mini 1: //search mini maxi madd x14,x12,x13,x0 // load coord Y ldr x15,[x14,point_posY] cmp x15,x17 csel x17,x15,x17,hi // maxi ? cmp x15,x19 csel x19,x15,x19,lo // mini ? add x12,x12,#1 cmp x12,x1 // end ? blt 1b // no -> loop // compute ratio udiv x15,x17,x3 // ratio = maxi / height add x15,x15,1 // for adjust ldr x0,qAdrszClear1 // clear screen bl affichageMess udiv x20,x2,x4 // compute interval X = weight / number points mov x12,0 // indice 2: // loop begin for display point madd x14,x12,x13,x9 // charge X coord point ldr x16,[x14,point_posX] mul x16,x20,x12 // interval * indice add x0,x16,MARGEGAUCHE // + left margin mov x1,x10 // conversion ascii and store bl convPos   ldr x18,[x14,point_posY] // charge Y coord point udiv x18,x18,x15 // divide by ratio sub x0,x3,x18 // inversion position ligne mov x1,x11 // conversion ascii and store bl convPos   ldr x0,qAdrszMessMovePos // display * at position X,Y bl affichageMess add x12,x12,1 // next point cmp x12,x4 // end ? blt 2b // no -> loop // display left scale // display Y Mini mov x0,0 ldr x1,qAdrposX1 bl convPos mov x0,HAUTEUR ldr x1,qAdrposY1 bl convPos ldr x0,qAdrszMessPosEch bl affichageMess mov x0,x19 ldr x1,qAdrsZoneConv bl conversion10 ldr x0,qAdrsZoneConv bl affichageMess // display Y Maxi mov x0,0 ldr x1,qAdrposX1 bl convPos mov x0,0 ldr x1,qAdrposY1 bl convPos ldr x0,qAdrszMessPosEch bl affichageMess mov x0,x17 ldr x1,qAdrsZoneConv bl conversion10 ldr x0,qAdrsZoneConv bl affichageMess // display average value mov x0,0 ldr x1,qAdrposX1 bl convPos mov x0,HAUTEUR/2 add x0,x0,#1 ldr x1,qAdrposY1 bl convPos ldr x0,qAdrszMessPosEch bl affichageMess lsr x0,x17,#1 ldr x1,qAdrsZoneConv bl conversion10 ldr x0,qAdrsZoneConv bl affichageMess   // display X scale mov x0,0 ldr x1,qAdrposX1 bl convPos mov x0,HAUTEUR+1 ldr x1,qAdrposY1 bl convPos ldr x0,qAdrszMessPosEch bl affichageMess ldr x0,qAdrszMessEchelleX bl affichageMess     mov x12,0 // indice mov x19,MARGEGAUCHE 10: udiv x20,x2,x4 madd x0,x20,x12,x19 ldr x1,qAdrposX1 bl convPos mov x0,HAUTEUR+1 ldr x1,qAdrposY1 bl convPos ldr x0,qAdrszMessPosEch bl affichageMess madd x14,x12,x13,x9 // load X coord point ldr x0,[x14,point_posX] ldr x1,qAdrsZoneConv bl conversion10 ldr x0,qAdrsZoneConv bl affichageMess add x12,x12,1 cmp x12,x4 blt 10b   ldr x0,qAdrszCarriageReturn bl affichageMess   mov x0,0 // return code b 100f 99: // error ldr x0,qAdrszMessError bl affichageMess mov x0,-1 // return code 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrszMessMovePos: .quad szMessMovePos qAdrszClear1: .quad szClear1 qAdrposX: .quad posX qAdrposY: .quad posY qAdrposX1: .quad posX1 qAdrposY1: .quad posY1 qAdrszMessEchelleX: .quad szMessEchelleX qAdrszMessPosEch: .quad szMessPosEch qAdrszMessError: .quad szMessError /************************************/ /* conv position in ascii and store at address */ /************************************/ /* x0 contains position */ /* x1 contains string address */ convPos: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,10 udiv x3,x0,x2 add x4,x3,48 // convert in ascii strb w4,[x1] // store posX msub x4,x3,x2,x0 add x4,x4,48 strb w4,[x1,1] 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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 # OP PRINT = ( POINT p )VOID: print( ( "Point(", x OF p, ",", y OF p, ")" ) ); OP PRINT = ( CIRCLE c )VOID: print( ( "Circle(", r OF c, " @ ", x OF c, ",", y OF c, ")" ) );   # getters # OP XCOORD = ( POINT p )REAL: x OF p; OP YCOORD = ( POINT p )REAL: y OF p;   OP XCOORD = ( CIRCLE c )REAL: x OF c; OP YCOORD = ( CIRCLE c )REAL: y OF c; OP RADIUS = ( CIRCLE c )REAL: r OF c;   # setters # # the setters are dyadic operators so need a priority - we make them lowest # # priority, like PLUSAB etc. # # They could have the same names as the getters but this seems clearer? # PRIO SETXCOORD = 1 , SETYCOORD = 1 , SETRADIUS = 1 ; # the setters return the POINT/CIRCLE being modified so we can write e.g. # # "PRINT ( p SETXCOORD 3 )" # OP SETXCOORD = ( REF POINT p, REAL x )REF POINT: ( x OF p := x; p ); OP SETYCOORD = ( REF POINT p, REAL y )REF POINT: ( y OF p := y; p );   OP SETXCOORD = ( REF CIRCLE c, REAL x )REF CIRCLE: ( x OF c := x; c ); OP SETYCOORD = ( REF CIRCLE c, REAL y )REF CIRCLE: ( y OF c := y; c ); OP SETRADIUS = ( REF CIRCLE c, REAL r )REF CIRCLE: ( r OF c := r; c );   # operands of an operator are not automatically coerced from INT to REAL so # # we also need these operators # OP SETXCOORD = ( REF POINT p, INT x )REF POINT: ( x OF p := x; p ); OP SETYCOORD = ( REF POINT p, INT y )REF POINT: ( y OF p := y; p );   OP SETXCOORD = ( REF CIRCLE c, INT x )REF CIRCLE: ( x OF c := x; c ); OP SETYCOORD = ( REF CIRCLE c, INT y )REF CIRCLE: ( y OF c := y; c ); OP SETRADIUS = ( REF CIRCLE c, INT r )REF CIRCLE: ( r OF c := r; c );   # copy constructors # # A copy constructor is not needed as assignment will generate a copy # # e.g.: "POINT pa, pb; pa := ...; pb := pa; ..." will make pb a copy of pa #   # assignment # # It is not possible to redefine the assignment "operator" in Algol 68 but # # assignment is automatically provided so no code need be written for e.g. # # "CIRCLE c1 := ...." #   # destructors # # Algol 68 does not include destructors. A particular postlude could, # # in theory be provided if specific cleanup was requried, but this would # # occur at the end of the program, not at the end of the lifetime of the # # object. #   # default constructor # # Algol 68 automatically provides generators HEAP and LOC, which will # # create new objects of the specified MODE, e.g. HEAP CIRCLE will create a # # new CIRCLE. HEAP allocates apace on the heap, LOC allocates in on the # # stack (so the new item disappears when the enclosing block procedure or # # operator finishes) #   # a suitable "display" (value list enclosed in "(" and ")") can be cast to # # the relevent MODE, allowing us to write e.g.: # # "POINT( 3.1, 2.2 )" where we need a new item. #   # "constructors" with other than all the fields in the correct order could # # be provided as procedures but each would need a distinct name # # e.g. # PROC new circle at the origin = ( REAL r )REF CIRCLE: ( ( HEAP CIRCLE SETRADIUS r ) SETXCOORD 0 ) SETYCOORD 0; PROC new point at the origin = REF POINT: ( HEAP POINT SETXCOORD 0 ) SETYCOORD 0;     # examples of use #   BEGIN   CIRCLE c1 := CIRCLE( 1.1, 2.4, 4.1 ); POINT p1 := new point at the origin;   PRINT c1; newline( stand out );   # move c1 so it is centred on p1 # ( c1 SETXCOORD XCOORD p1 ) SETYCOORD YCOORD p1;   PRINT c1; newline( stand out )   END
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#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": "Straight" return (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") && (Straight) ? hand "`t" Royal " Flush" : (hand ~= "([2-9TJQKA]).*?\1.*?\1.*?\1") ? hand "`tFour of a Kind" : (hand ~= "^([2-9TJQKA]).\h\1.\h(?!\1)([2-9TJQKA]).\h\2.\h\2.$") ? hand "`tFull House" ; xxyyy : (hand ~= "^([2-9TJQKA]).\h\1.\h\1.\h(?!\1)([2-9TJQKA]).\h\2.$") ? hand "`tFull House" ; xxxyy : (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") ? hand "`tFlush" : (Straight) ? hand "`tStraight" : (hand ~= "([2-9TJQKA]).*?\1.*?\1") ? hand "`tThree of a Kind" : (hand ~= "([2-9TJQKA]).\h\1.*?([2-9TJQKA]).\h\2") ? hand "`tTwo Pair" : (hand ~= "([2-9TJQKA]).\h\1") ? hand "`tOne Pair" : hand "`tHigh Card" } CardSort(a, b){ a := SubStr(a, 1, 1), b := SubStr(b, 1, 1) a := (a = "T") ? 10 : (a = "J") ? 11 : (a = "Q") ? 12 : (a = "K") ? 13 : a b := (b = "T") ? 10 : (b = "J") ? 11 : (b = "Q") ? 12 : (b = "K") ? 13 : b return a > b ? 1 : a < b ? -1 : 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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#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 odd( v ) then count := count + 1; v  := v div 2 end while_v_gt_0 ; count end populationCount ;  % returns the sum of population counts of the elements of the array n  %  % the bounds of n must be 1 :: length  % integer procedure arrayPopulationCount( integer array n ( * ); integer value length ) ; begin integer count; count := 0; for i := 1 until length do count := count + populationCount( n( i ) ); count end arrayPopulationCount ; begin %task requirements % integer array power( 1 :: 8 ); integer n, count, carry;  % population counts of the first 30 powers of three %  % Algol W integers are 32-bit, so we simulate 64-bit with an array of integers %  % the only operation we need is multiplication by 3  %  % we use 8 bits of each number  %  % start with 3^0, which is 1 % for i := 1 until 8 do power( i ) := 0; power( 1 ) := 1; write( i_w := 1, s_w := 0, "3^x population: ", arrayPopulationCount( power, 8 ) ); for p := 1 until 29 do begin carry := 0; for b := 1 until 8 do begin integer bValue; bValue  := ( power( b ) * 3 ) + carry; carry  := bValue div 256; power( b ) := bValue rem 256 end for_b ; writeon( i_w := 1, s_w := 0, " ", arrayPopulationCount( power, 8 ) ) end for_p ;    % evil numbers (even population count) % write( "evil numbers:" ); n  := 0; count := 0; while count < 30 do begin if not odd( populationCount( n ) ) then begin writeon( i_w := 1, s_w := 0, " ", n ); count := count + 1 end if_not_odd_populationCount ; n := n + 1 end evil_numbers_loop ;    % odious numbers (odd population count % write( "odious numbers:" ); n  := 0; count := 0; while count < 30 do begin if odd( populationCount( n ) ) then begin writeon( i_w := 1, s_w := 0, " ", n ); count := count + 1 end if_odd_populationCount ; n := n + 1 end odious_numbers_loop end end.
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#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.size()-1 << ") = [ "; copy(A.begin(), A.end(), ostream_iterator<decltype(A[0])>(cout, " ")); cout << "]\n"; }   int main() { Poly N, D, d, q, r; // vectors - N / D == q && N % D == r size_t dN, dD, dd, dq, dr; // degrees of vectors size_t i; // loop counter   // setting the degrees of vectors cout << "Enter the degree of N: "; cin >> dN; cout << "Enter the degree of D: "; cin >> dD; dq = dN-dD; dr = dN-dD;   if( dD < 1 || dN < 1 ) { cerr << "Error: degree of D and N must be positive.\n"; return 1; }   // allocation and initialization of vectors N.resize(dN+1); cout << "Enter the coefficients of N:"<<endl; for ( i = 0; i <= dN; i++ ) { cout << "N[" << i << "]= "; cin >> N[i]; }   D.resize(dN+1); cout << "Enter the coefficients of D:"<<endl; for ( i = 0; i <= dD; i++ ) { cout << "D[" << i << "]= "; cin >> D[i]; }   d.resize(dN+1); q.resize(dq+1); r.resize(dr+1);   cout << "-- Procedure --" << endl << endl; if( dN >= dD ) { while(dN >= dD) { // d equals D shifted right d.assign(d.size(), 0);   for( i = 0 ; i <= dD ; i++ ) d[i+dN-dD] = D[i]; dd = dN;   Print( 'd', d );   // calculating one element of q q[dN-dD] = N[dN]/d[dd];   Print( 'q', q );   // d equals d * q[dN-dD] for( i = 0 ; i < dq + 1 ; i++ ) d[i] = d[i] * q[dN-dD];   Print( 'd', d );   // N equals N - d for( i = 0 ; i < dN + 1 ; i++ ) N[i] = N[i] - d[i]; dN--;   Print( 'N', N ); cout << "-----------------------" << endl << endl;   } }   // r equals N for( i = 0 ; i <= dN ; i++ ) r[i] = N[i];   cout << "=========================" << endl << endl; cout << "-- Result --" << endl << endl;   Print( 'q', q ); Print( 'r', r ); }    
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#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;   function S.Name :String; begin Exit('S') end; function S.Clone:T; begin Exit(S.Create)end;   procedure Main; var Original, Clone :T; begin Original := S.Create; Clone := Original.Clone;   WriteLn(Original.Name); WriteLn(Clone.Name); end;   begin Main; end.
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#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() }.start() }   private fun drawSpiral(g: Graphics2D, length: Int, angleIncrement: Double) { var x1 = width / 2.0 var y1 = height / 2.0 var len = length var angle = angleIncrement for (i in 0 until 150) { g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f)) val x2 = x1 + Math.cos(angle) * len val y2 = y1 - Math.sin(angle) * len g.drawLine(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) x1 = x2 y1 = y2 len += 3 angle = (angle + angleIncrement) % (Math.PI * 2.0) } }   override protected fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawSpiral(g, 5, Math.toRadians(inc)) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "PolySpiral" f.setResizable(true) f.add(PolySpiral(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.setVisible(true) } }
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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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(); double ym = std::accumulate(y.begin(), y.end(), 0.0) / y.size(); double x2m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a; }) / r.size(); double x3m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a; }) / r.size(); double x4m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a * a; }) / r.size();   double xym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, std::multiplies<double>{}); xym /= fmin(x.size(), y.size());   double x2ym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, [](double a, double b) { return a * a * b; }); x2ym /= fmin(x.size(), y.size());   double sxx = x2m - xm * xm; double sxy = xym - xm * ym; double sxx2 = x3m - xm * x2m; double sx2x2 = x4m - x2m * x2m; double sx2y = x2ym - x2m * ym;   double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double a = ym - b * xm - c * x2m;   auto abc = [a, b, c](int xx) { return a + b * xx + c * xx*xx; };   std::cout << "y = " << a << " + " << b << "x + " << c << "x^2" << std::endl; std::cout << " Input Approximation" << std::endl; std::cout << " x y y1" << std::endl;   auto xit = x.cbegin(); auto xend = x.cend(); auto yit = y.cbegin(); auto yend = y.cend(); while (xit != xend && yit != yend) { printf("%2d %3d  %5.1f\n", *xit, *yit, abc(*xit)); xit = std::next(xit); yit = std::next(yit); } }   int main() { using namespace std;   vector<int> x(11); iota(x.begin(), x.end(), 0);   vector<int> y{ 1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321 };   polyRegression(x, y);   return 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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#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% = 0 TO DIM(list$(),1) IF i% AND (1 << j%) s$ += list$(j%) + "," NEXT IF RIGHT$(s$) = "," s$ = LEFT$(s$) s$ += "}," NEXT i% = LEFT$(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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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,k) ? (d*d <= n ? IsPrime(n,d) : 1) : 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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#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}, ; {.31,.36,.5}, ; {.36,.41,.54}, ; {.41,.46,.58}, ; {.46,.51,.62}, ; {.51,.56,.66}, ; {.56,.61,.7}, ; {.61,.66,.74}, ; {.66,.71,.78}, ; {.71,.76,.82}, ; {.76,.81,.86}, ; {.81,.86,.9}, ; {.86,.91,.94}, ; {.91,.96,.98} } LOCAL nResult LOCAL nScan IF npQuantDispensed = 0 nResult = 0 ELSEIF npQuantDispensed >= .96 nResult = 1 ELSE nScan := ASCAN( aPriceFraction, ; { |aItem| npQuantDispensed >= aItem[ 1 ] .AND.; npQuantDispensed < aItem[ 2 ] } ) nResult := aPriceFraction[ nScan ][ 3 ] END IF RETURN nResult
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#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 < if nip nip i swap else drop then loop swap cr . ." has " . ." divisors" cr ;   rosetta-proper-divisors
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 involved, this is subject to rounding errors). 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 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#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 += probabilities[name]; cumulative[name] = sum; randomly[name] = 0; } for (var i = 0; i < iterations; i++) { var r = Math.random(); for (var name in cumulative) { if (r <= cumulative[name]) { randomly[name]++; break; } } } for (var name in probabilities) // using WSH WScript.Echo(name + "\t" + probabilities[name] + "\t" + randomly[name]/iterations);
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#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 example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#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 x3= 2; y3= 4; r3= 2 call tell 'external tangent: ', Apollonius( 1, 1, 1) call tell 'internal tangent: ', Apollonius(-1, -1, -1) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Apollonius: parse arg s1,s2,s3 /*could be internal or external tangent*/ numeric digits digits() * 3 /*reduce rounding with thrice digits. */ va= x2*2 - x1*2; vb= y2*2 - y1*2 vc= x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2 vd= s2*r2*2 - s1*r1*2; ve= x3*2 - x2*2; vf= y3*2 - y2*2 vg= x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2; vh= s3*r3*2 - s2*r2*2 vj= vb/va; vk= vc/va; vm= vd/va; vn= vf/ve - vj vp= vg/ve - vk; vr= vh/ve - vm; p = -vp/vn; q = vr/vn m = -vj*p - vk; n = vm - vj*q a = n**2 + q**2 - 1 b = (m*n - n*x1 + p*q - q*y1 + s1*r1) * 2 c = x1**2 + y1**2 + m**2 - r1**2 + p**2 - (m*x1 + p*y1) * 2 $r= (-b - sqrt(b**2 - a*c*4) ) / (a+a) return (m + n*$r) (p + q*$r) ($r) /*return 3 arguments.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric digits m.=9; numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/; return g /*──────────────────────────────────────────────────────────────────────────────────────*/ tell: parse arg _,a b c; w=digits()+4; say _ left(a/1,w%2) left(b/1,w) left(c/1,w); return
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 ARGV. See also Command-line arguments Examples from GitHub.
#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 ARGV. See also Command-line arguments Examples from GitHub.
#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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#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 /*Not specified? Then use the default.*/ do j=1 for N; @.j= j*j; end /*pre-compute some squares. */ N66= N * 2%3 /*calculate 2/3 of N (for a+b). */ T= 0; P= 0 /*set the number of Triples, Primitives*/ do a=3 to N%3 /*limit side to 1/3 of the perimeter.*/ do b= a+1 /*the triangle can't be isosceles. */ ab= a + b /*compute a partial perimeter (2 sides)*/ if ab>=N66 then iterate a /*is a+b≥66% perimeter? Try different A*/ aabb= @.a + @.b /*compute the sum of a²+b² (shortcut)*/ do c=b+1 /*compute the value of the third side. */ if ab+c > N then iterate a /*is a+b+c>perimeter ? Try different A.*/ if @.c >aabb then iterate b /*is c² > a²+b² ? Try " B.*/ if @.c\==aabb then iterate /*is c² ¬= a²+b² ? Try " C.*/ T= T + 1 /*eureka. We found a Pythagorean triple*/ P= P + (gcd(a, b)==1) /*is this triple a primitive triple? */ end /*c*/ end /*b*/ end /*a*/ _= left('', 7) /*for padding the output with 7 blanks.*/ say 'max perimeter =' N _ "Pythagorean triples =" T _ 'primitives =' P exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gcd: procedure; parse arg x,y; do until y==0; parse value x//y y with y x; end; return x
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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 + 10 * $_; $ends_in_7 .= "$n " if is_wilson_prime($n); }   say $ends_in_3; say $ends_in_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 printf(1,"The first 25 primes: %V\n",{primes[1..25]}) printf(1," builtin: %V\n",{get_primes(-25)}) printf(1,"primes[1000..1015]: %V\n",{primes[1000..1015]}) printf(1," builtin: %V\n",{get_primes(-1015)[1000..1015]}) ?elapsed(time()-t0)
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 the primes that immediately follow them. and This conspiracy among prime numbers seems, at first glance, to violate a longstanding assumption in number theory: that prime numbers behave much like random numbers. ─── (original authors from Stanford University): ─── Kannan Soundararajan and Robert Lemke Oliver The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime. Task Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed. Observation (Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime. Extra credit Do the same for one hundred million primes. Example for 10,000 primes 10000 first primes. Transitions prime % 10 → next-prime % 10. 1 → 1 count: 365 frequency: 3.65 % 1 → 3 count: 833 frequency: 8.33 % 1 → 7 count: 889 frequency: 8.89 % 1 → 9 count: 397 frequency: 3.97 % 2 → 3 count: 1 frequency: 0.01 % 3 → 1 count: 529 frequency: 5.29 % 3 → 3 count: 324 frequency: 3.24 % 3 → 5 count: 1 frequency: 0.01 % 3 → 7 count: 754 frequency: 7.54 % 3 → 9 count: 907 frequency: 9.07 % 5 → 7 count: 1 frequency: 0.01 % 7 → 1 count: 655 frequency: 6.55 % 7 → 3 count: 722 frequency: 7.22 % 7 → 7 count: 323 frequency: 3.23 % 7 → 9 count: 808 frequency: 8.08 % 9 → 1 count: 935 frequency: 9.35 % 9 → 3 count: 635 frequency: 6.35 % 9 → 7 count: 541 frequency: 5.41 % 9 → 9 count: 379 frequency: 3.79 %
#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[transition]), "frequency:", sprintf("%5.2f%%\n",result[transition]*100/limit)) }   while (count <= limit) { count <- count + 1 next_prime <- nextprime(prev_prime) transition <- 10*(asNumeric(prev_prime) %% 10) + (asNumeric(next_prime) %% 10) prev_prime <- next_prime result[transition] <- result[transition] + 1 }   cat(sprintf("%d",limit),"first primes. Transitions prime % 10 -> next-prime % 10\n") invisible(sapply(1:99,getOutput))  
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 number   n {\displaystyle n}   greater than   1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). Related tasks   count in factors   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 value_type Integer. // It receives the prime factors. template<typename Integer, typename OutputIterator> void decompose(Integer n, OutputIterator out) { Integer i(2);   while (n != 1) { while (n % i == Integer(0)) { *out++ = i; n /= i; } ++i; } }   // this is an output iterator similar to std::ostream_iterator, except // that it outputs the separation string *before* the value, but not // before the first value (i.e. it produces an infix notation). template<typename T> class infix_ostream_iterator: public std::iterator<T, std::output_iterator_tag> { class Proxy; friend class Proxy; class Proxy { public: Proxy(infix_ostream_iterator& iter): iterator(iter) {} Proxy& operator=(T const& value) { if (!iterator.first) { iterator.stream << iterator.infix; } iterator.stream << value; } private: infix_ostream_iterator& iterator; }; public: infix_ostream_iterator(std::ostream& os, char const* inf): stream(os), first(true), infix(inf) { } infix_ostream_iterator& operator++() { first = false; return *this; } infix_ostream_iterator operator++(int) { infix_ostream_iterator prev(*this); ++*this; return prev; } Proxy operator*() { return Proxy(*this); } private: std::ostream& stream; bool first; char const* infix; };   int main() { std::cout << "please enter a positive number: "; mpz_class number; std::cin >> number;   if (number <= 0) std::cout << "this number is not positive!\n;"; else { std::cout << "decomposition: "; decompose(number, infix_ostream_iterator<mpz_class>(std::cout, " * ")); std::cout << "\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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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 | Comparison | Matching Memory Operations Pointers & references | Addresses In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
#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) { Value += 1; } private static void Value(int Value) { Value += 1; }  
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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 FUNC GetYPtr(BYTE i) RETURN (ys+3*i)   PROC AddPoint(CHAR ARRAY xstr,ystr) REAL POINTER p   p=GetXPtr(count) ValR(xstr,p) p=GetYPtr(count) ValR(ystr,p) count==+1 RETURN   PROC InitData() AddPoint("0.0","2.7") AddPoint("1.0","2.8") AddPoint("2.0","31.4") AddPoint("3.0","38.1") AddPoint("4.0","58.0") AddPoint("5.0","76.2") AddPoint("6.0","100.5") AddPoint("7.0","130.0") AddPoint("8.0","149.3") AddPoint("9.0","180.0") RETURN   INT FUNC GetXPos(Settings POINTER s INT x) INT res   res=x*(s.xRight-s.xLeft)/(s.xMax-s.xMin)+s.xLeft RETURN (res)   INT FUNC GetYPos(Settings POINTER s INT y) INT res   res=y*(s.yTop-s.yBottom)/(s.yMax-s.yMin)+s.yBottom RETURN (res)   INT FUNC GetXPosR(Settings POINTER s REAL POINTER x) REAL nom,denom,div,tmp INT res   IntToReal(s.xRight-s.xLeft,tmp) RealMult(tmp,x,nom) IntToReal(s.xMax-s.xMin,denom) RealDiv(nom,denom,div) res=RealToInt(div)+s.xLeft RETURN (res)   INT FUNC GetYPosR(Settings POINTER s REAL POINTER y) REAL nom,denom,div,tmp INT res   IntToReal(s.yBottom-s.yTop,tmp) RealMult(tmp,y,nom) IntToReal(s.yMax-s.yMin,denom) RealDiv(nom,denom,div) res=-RealToInt(div)+s.yBottom RETURN (res)   BYTE FUNC AtasciiToInternal(CHAR c) BYTE c2   c2=c&$7F IF c2<32 THEN RETURN (c+64) ELSEIF c2<96 THEN RETURN (c-32) FI RETURN (c)   PROC CharOut(INT x,y CHAR c) BYTE i,j,v PTR addr   addr=$E000+AtasciiToInternal(c)*8; FOR j=0 TO 7 DO v=Peek(addr) i=8 WHILE i>0 DO IF v&1 THEN Plot(x+i,y+j) FI   v=v RSH 1 i==-1 OD addr==+1 OD RETURN   PROC TextOut(INT x,y CHAR ARRAY text) BYTE i   FOR i=1 TO text(0) DO CharOut(x,y,text(i)) x==+8 OD RETURN   PROC DrawAxes(Settings POINTER s) INT i,x,y CHAR ARRAY t(10)   Plot(s.xLeft,s.yTop) DrawTo(s.xLeft,s.yBottom) DrawTo(s.xRight,s.yBottom)   FOR i=s.xMin TO s.xMax STEP s.xStep DO x=GetXPos(s,i) Plot(x,s.yBottom) DrawTo(x,s.yBottom+s.tickLength) StrI(i,t) TextOut(x-t(0)*4,s.yBottom+s.tickLength+1,t) OD   FOR i=s.yMin TO s.yMax STEP s.yStep DO y=GetYPos(s,i) Plot(s.xLeft-s.tickLength,y) DrawTo(s.xLeft,y) StrI(i,t) TextOut(s.xLeft-s.tickLength-1-t(0)*8,y-4,t) OD RETURN   PROC DrawPoint(INT x,y) Plot(x-1,y-1) DrawTo(x+1,y-1) DrawTo(x+1,y+1) DrawTo(x-1,y+1) DrawTo(x-1,y-1) RETURN   PROC DrawSeries(Settings POINTER s) INT i,x,y,prevX,prevY REAL POINTER p   FOR i=0 TO count-1 DO p=GetXPtr(i) x=GetXPosR(s,p) p=GetYPtr(i) y=GetYPosR(s,p) DrawPoint(x,y) IF i>0 THEN Plot(prevX,prevY) DrawTo(x,y) FI prevX=x prevY=y OD RETURN   PROC DrawPlot(Settings POINTER s) DrawAxes(s) DrawSeries(s) RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6 Settings s   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   InitData() s.xMin=0 s.xMax=9 s.xStep=1 s.yMin=0 s.yMax=180 s.yStep=20 s.xLeft=30 s.xRight=311 s.yTop=8 s.yBottom=177 s.tickLength=3 DrawPlot(s)   DO UNTIL CH#$FF OD CH=$FF RETURN
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.3, 180.0}; This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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_Canvas.Plot; use Gtk.Extra.Plot_Canvas.Plot;   procedure PlotCoords is package Handler is new Callback (Gtk_Widget_Record);   Window : Gtk_Window; Plot : Gtk_Plot; PCP : Gtk_Plot_Canvas_Plot; Canvas : Gtk_Plot_Canvas; PlotData : Gtk_Plot_Data; x, y, dx, dy : Gdouble_Array_Access;   procedure ExitMain (Object : access Gtk_Widget_Record'Class) is begin Destroy (Object); Gtk.Main.Main_Quit; end ExitMain;   begin x := new Gdouble_Array'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); y := new Gdouble_Array'(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0); Gtk.Main.Init; Gtk_New (Window); Set_Title (Window, "Plot coordinate pairs with GtkAda"); Gtk_New (PlotData); Set_Points (PlotData, x, y, dx, dy); Gtk_New (Plot); Add_Data (Plot, PlotData); Autoscale (Plot); Show (PlotData); Hide_Legends (Plot); Gtk_New (PCP, Plot); Show (Plot); Gtk_New (Canvas, 500, 500); Show (Canvas); Put_Child (Canvas, PCP, 0.15, 0.15, 0.85, 0.85); Add (Window, Canvas); Show_All (Window); Handler.Connect (Window, "destroy", Handler.To_Marshaller (ExitMain'Access)); Gtk.Main.Main; end PlotCoords;  
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 ]   print: [ render "circle (center: |this\center|, radius: |this\radius|)" ] ]   p: to :point [10.0, 20.0] c: to :circle @[p, 10.0]   inspect p inspect c   print p print c
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" MyCircle.GetX() . "`ny:`t" MyCircle.y . "`nr:`t" MyCircle.GetR() return   class Point { Copy() { return this.Clone() } GetX() { return this.x } GetY() { return this.y } __New(x, y) { this.x := x this.y := y } Print() { MsgBox, % this.__Class . "`n`nx:`t" this.x . "`ny:`t" this.y } SetX(aValue) { this.x := aValue } SetY(aValue) { this.y := aValue } }   class Circle extends Point { GetR() { return this.r } __New(x, y, r) { this.r := r base.__New(x, y) } Print() { MsgBox, % this.__Class . "`n`nx:`t" this.x . "`ny:`t" this.y . "`nr:`t" this.r } SetR(aValue) { this.r := aValue } }
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, 5, 6, 7, 8, 9, 10, j, q, k Suits are:    h (hearts),   d (diamonds),   c (clubs),   and   s (spades),   or alternatively,   the unicode card-suit characters:    ♥ ♦ ♣ ♠ Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid Examples 2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind 2♥ 5♥ 7♦ 8♣ 9♠: high-card a♥ 2♦ 3♣ 4♣ 5♦: straight 2♥ 3♥ 2♦ 3♣ 3♦: full-house 2♥ 7♥ 2♦ 3♣ 3♦: two-pair 2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind 10♥ j♥ q♥ k♥ a♥: straight-flush 4♥ 4♠ k♠ 5♦ 10♠: one-pair q♣ 10♣ 7♣ 6♣ q♣: invalid The programs output for the above examples should be displayed here on this page. Extra credit use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). allow two jokers use the symbol   joker duplicates would be allowed (for jokers only) five-of-a-kind would then be the highest hand More extra credit examples joker 2♦ 2♠ k♠ q♦: three-of-a-kind joker 5♥ 7♦ 8♠ 9♦: straight joker 2♦ 3♠ 4♠ 5♠: straight joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind joker j♥ q♥ k♥ A♥: straight-flush joker 4♣ k♣ 5♦ 10♠: one-pair joker k♣ 7♣ 6♣ 4♣: flush joker 2♦ joker 4♠ 5♠: straight joker Q♦ joker A♠ 10♠: straight joker Q♦ joker A♦ 10♦: straight-flush joker 2♦ 2♠ joker q♦: four-of-a-kind Related tasks Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Go Fish
#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 void *a, const void *b) { card c1 = *(card *)a; card c2 = *(card *)b; return c1.face - c2.face; }   bool equals_card(card c1, card c2) { if (c1.face == c2.face && c1.suit == c2.suit) return TRUE; return FALSE; }   bool are_distinct() { int i, j; for (i = 0; i < 4; ++i) for (j = i + 1; j < 5; ++j) if (equals_card(cards[i], cards[j])) return FALSE; return TRUE; }   bool is_straight() { int i; qsort(cards, 5, sizeof(card), compare_card); if (cards[0].face + 4 == cards[4].face) return TRUE; if (cards[4].face == 12 && cards[0].face == 0 && cards[3].face == 3) return TRUE; return FALSE; }   bool is_flush() { int i; char suit = cards[0].suit; for (i = 1; i < 5; ++i) if (cards[i].suit != suit) return FALSE; return TRUE; }   const char *analyze_hand(const char *hand) { int i, j, gs = 0; char suit, *cp; bool found, flush, straight; int groups[13]; if (strlen(hand) != 14) return "invalid"; for (i = 0; i < 14; i += 3) { cp = strchr(FACES, tolower(hand[i])); if (cp == NULL) return "invalid"; j = i / 3; cards[j].face = cp - FACES; suit = tolower(hand[i + 1]); cp = strchr(SUITS, suit); if (cp == NULL) return "invalid"; cards[j].suit = suit; } if (!are_distinct()) return "invalid"; for (i = 0; i < 13; ++i) groups[i] = 0; for (i = 0; i < 5; ++i) groups[cards[i].face]++; for (i = 0; i < 13; ++i) if (groups[i] > 0) gs++; switch(gs) { case 2: found = FALSE; for (i = 0; i < 13; ++i) if (groups[i] == 4) { found = TRUE; break; } if (found) return "four-of-a-kind"; return "full-house"; case 3: found = FALSE; for (i = 0; i < 13; ++i) if (groups[i] == 3) { found = TRUE; break; } if (found) return "three-of-a-kind"; return "two-pairs"; case 4: return "one-pair"; default: flush = is_flush(); straight = is_straight(); if (flush && straight) return "straight-flush"; else if (flush) return "flush"; else if (straight) return "straight"; else return "high-card"; } }   int main(){ int i; const char *type; const char *hands[10] = { "2h 2d 2c kc qd", "2h 5h 7d 8c 9s", "ah 2d 3c 4c 5d", "2h 3h 2d 3c 3d", "2h 7h 2d 3c 3d", "2h 7h 7d 7c 7s", "th jh qh kh ah", "4h 4s ks 5d ts", "qc tc 7c 6c 4c", "ah ah 7c 6c 4c" }; for (i = 0; i < 10; ++i) { type = analyze_hand(hands[i]); printf("%s: %s\n", hands[i], type); } return 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   bit summation   Hamming weight For example,   5   (which is   101   in binary)   has a population count of   2. Evil numbers   are non-negative integers that have an   even   population count. Odious numbers     are  positive integers that have an    odd   population count. Task write a function (or routine) to return the population count of a non-negative integer. all computation of the lists below should start with   0   (zero indexed). display the   pop count   of the   1st   thirty powers of   3       (30,   31,   32,   33,   34,   ∙∙∙   329). display the   1st   thirty     evil     numbers. display the   1st   thirty   odious   numbers. display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified. See also The On-Line Encyclopedia of Integer Sequences:   A000120 population count. The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers. The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.
#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 ⍵ ⍝ Count the bits }¨   act3←popCount 3*⍳N   M←N×2 actEvil←N↑{⍵/⍨0=2|popCount ⍵}⍳M actOdious←N↑{⍵/⍨1=2|popCount ⍵}⍳M   ⎕←'powers 3'act3 ⎕←'evil 'actEvil ⎕←'odious 'actOdious   ⍝ Extra: Validate answers are correct ⍝ Actual answers ans3←1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 ansEvil←0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58 ansOdious←1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59   '***Passes' '***Fails'⊃⍨(ans3≢act3)∨(actEvil≢ansEvil)∨(actOdious≢ansOdious) }  
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 dividing a polynomial by another polynomial of the same or lower degree. Let us suppose a polynomial is represented by a vector, x {\displaystyle x} (i.e., an ordered collection of coefficients) so that the i {\displaystyle i} th element keeps the coefficient of x i {\displaystyle x^{i}} , and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: degree(P): return the index of the last non-zero element of P; if all elements are 0, return -∞ polynomial_long_division(N, D) returns (q, r): // N, D, q, r are vectors if degree(D) < 0 then error q ← 0 while degree(N) ≥ degree(D) d ← D shifted right by (degree(N) - degree(D)) q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d)) // by construction, degree(d) = degree(N) of course d ← d * q(degree(N) - degree(D)) N ← N - d endwhile r ← N return (q, r) Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based. Error handling (for allocations or for wrong inputs) is not mandatory. Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler. Example for clarification This example is from Wikipedia, but changed to show how the given pseudocode works. 0 1 2 3 ---------------------- N: -42 0 -12 1 degree = 3 D: -3 1 0 0 degree = 1 d(N) - d(D) = 2, so let's shift D towards right by 2: N: -42 0 -12 1 d: 0 0 -3 1 N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2" is like multiplying by x2, and the final multiplication (here by 1) is the coefficient of this monomial. Let's store this into q: 0 1 2 --------------- q: 0 0 1 now compute N - d, and let it be the "new" N, and let's loop N: -42 0 -9 0 degree = 2 D: -3 1 0 0 degree = 1 d(N) - d(D) = 1, right shift D by 1 and let it be d N: -42 0 -9 0 d: 0 -3 1 0 * -9/1 = -9 q: 0 -9 1 d: 0 27 -9 0 N ← N - d N: -42 -27 0 0 degree = 1 D: -3 1 0 0 degree = 1 looping again... d(N)-d(D)=0, so no shift is needed; we multiply D by -27 (= -27/1) storing the result in d, then q: -27 -9 1 and N: -42 -27 0 0 - d: 81 -27 0 0 = N: -123 0 0 0 (last N) d(N) < d(D), so now r ← N, and the result is: 0 1 2 ------------- q: -27 -9 1 → x2 - 9x - 27 r: -123 0 0 → -123 Related task   Polynomial derivative
#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) grade2 (last term2) comp (- grade1 grade2)] ;; differs from grlex because terms are flipped from above (if (not= 0 comp) comp (recur (pop term1) (pop term2)))))))))   (defn mul ;; transducer ([poly1] ;; completion (fn ([] poly1) ([poly2] (mul poly1 poly2)) ([poly2 & more] (mul poly1 poly2 more)))) ([poly1 poly2] (let [product (atom (transient (sorted-map-by grevlex)))] (doall ;; `for` is lazy so must to be forced for side-effects (for [term1 poly1 term2 poly2  :let [vars (mapv +' (key term1) (key term2)) coeff (* (val term1) (val term2))]] (if (contains? @product vars) (swap! product assoc! vars (+ (get @product vars) coeff)) (swap! product assoc! vars coeff)))) (->> product (deref) (persistent!) (denull)))) ([poly1 poly2 & more] (reduce mul (mul poly1 poly2) more)))   (defn compl [term1 term2] (map (fn [x y] (cond (and (zero? x) (not= 0 y)) nil (< x y) nil (>= x y) (- x y))) term1 term2))   (defn s-poly [f g] (let [f-vars (first f) g-vars (first g) lcm (compl f-vars g-vars)] (if (not-any? nil? lcm) {(vec lcm) (/ (second f) (second g))})))   (defn divide [f g] (loop [f f g g result (transient {}) remainder {}] (if (empty? f) (list (persistent! result) (->> remainder (filter #(not (nil? %))) (into (sorted-map-by grevlex)))) (let [term1 (first f) term2 (first g) s-term (s-poly term1 term2)] (if (nil? s-term) (recur (dissoc f (first term1)) (dissoc g (first term2)) result (conj remainder term1)) (recur (sub f (mul g s-term)) g (conj! result s-term) remainder))))))   (deftest divide-tests (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7}) '({[0 0] 1} {}))) (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {[0 0] 1}) '({[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {}))) (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} {[0 1] 1, [0 0] 5}) '({[1 0] 2, [0 0] 3} {}))) (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} {[1 0] 2, [0 0] 3}) '({[0 1] 1, [0 0] 5} {}))))
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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#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 declared of any specific type. The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until run time. The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
#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-copy → #<K> (#<S> (33 42)) ;; copied S type   (set-S-y! (K-box k-source) 666) ;; modify k-source.box.y   k-source → #<K> (#<S> (33 666)) ;; modified k-copy → #<K> (#<S> (33 42)) ;; unmodified   (K "string-inside") ;; trying to put a string in the container box 😡 error: T : type-check failure : string-inside → 'K:box'  
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#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.cos(angle) * length y2 = y1 + math.sin(angle) * length love.graphics.line(x1, y1, x2, y2) x1, y1 = x2, y2 length = length + 3 angle = (angle + incr) % 360 end end
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 background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#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 intended as a subtask for Measure relative performance of sorting algorithms implementations.
#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) (expt (aref x 0 i) j)))) (lsqr A (mtp y))))
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 powerset) of S, written P(S), or 2S, is the set of all subsets of S. Task By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of     {1,2,3,4}     is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set. The power set of the empty set is the set which contains itself (20 = 1): P {\displaystyle {\mathcal {P}}} ( ∅ {\displaystyle \varnothing } ) = { ∅ {\displaystyle \varnothing } } And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2): P {\displaystyle {\mathcal {P}}} ({ ∅ {\displaystyle \varnothing } }) = { ∅ {\displaystyle \varnothing } , { ∅ {\displaystyle \varnothing } } } Extra credit: Demonstrate that your language supports these last two powersets.
#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   count in factors   prime decomposition   AKS test for primes   factors of an integer   Sieve of Eratosthenes   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#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 ---------------------------------------------------------------------------- Func main() ConsoleWrite("The primes up to 100 are: " & @LF) For $i = 1 To 100 Step 1 If(isPrime($i)) Then If($i <> 97) Then ConsoleWrite($i & ", ") Else ConsoleWrite($i) EndIf EndIf Next EndFunc   Func isPrime($n) If($n < 2) Then Return False If($n = 2) Then Return True If(BitAnd($n, 1) = 0) Then Return False For $i = 3 To Sqrt($n) Step 2 If(Mod($n, $i) = 0) Then Return False Next Return True EndFunc main()
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 the following table: >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.58 >= 0.46 < 0.51  := 0.62 >= 0.51 < 0.56  := 0.66 >= 0.56 < 0.61  := 0.70 >= 0.61 < 0.66  := 0.74 >= 0.66 < 0.71  := 0.78 >= 0.71 < 0.76  := 0.82 >= 0.76 < 0.81  := 0.86 >= 0.81 < 0.86  := 0.90 >= 0.86 < 0.91  := 0.94 >= 0.91 < 0.96  := 0.98 >= 0.96 < 1.01  := 1.00
#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) ((< value 0.46) 0.58) ((< value 0.51) 0.62) ((< value 0.56) 0.66) ((< value 0.61) 0.70) ((< value 0.66) 0.74) ((< value 0.71) 0.78) ((< value 0.76) 0.82) ((< value 0.81) 0.86) ((< value 0.86) 0.90) ((< value 0.91) 0.94) ((< value 0.96) 0.98) ((< value 1.01) 1.00) (t (error "invalid value: ~A" value))))
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, 10, 20, 25, and 50. Task Create a routine to generate all the proper divisors of a number. use it to show the proper divisors of the numbers 1 to 10 inclusive. Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has. Show all output here. Related tasks   Amicable pairs   Abundant, deficient and perfect number classifications   Aliquot sequence classifications   Factors of an integer   Prime decomposition
#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 divisors' do j=1,limit,1 if (j .lt. 11) print *,j icnt = icntprop(j)   if (icnt .gt. maxcnt) then maxcnt = icnt maxj = j end if   end do   print *,' ' print *,' from 1 to ',limit print *,maxj,' has max proper divisors: ',maxcnt end  
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). 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 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#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 selected (", hi, " trials).") println(" Item Expected Actual") for i in 1:plen println(@sprintf(" \u2067%s  %8.6f  %8.6f", plab[i], p[i], r[i])) end   println() println("Rates at which items are selected (", hi, " trials).") println(" Item Count Expected Actual") for i in 1:plen println(@sprintf("  %s yields  %6d  %8.6f  %8.6f", plab[i], accum[i], p[i], r[i])) end  
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). 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 # adjusted so that probabilities add to 1 Related task Random number generator (device)
#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] = probs[0] for (i in 1..6) cumProbs[i] = cumProbs[i - 1] + probs[i] cumProbs[7] = 1.0 probs[7] = 1.0 - cumProbs[6] val n = 1000000 (1..n).forEach { val rand = Math.random() when { rand <= cumProbs[0] -> actual[0]++ rand <= cumProbs[1] -> actual[1]++ rand <= cumProbs[2] -> actual[2]++ rand <= cumProbs[3] -> actual[3]++ rand <= cumProbs[4] -> actual[4]++ rand <= cumProbs[5] -> actual[5]++ rand <= cumProbs[6] -> actual[6]++ else -> actual[7]++ } }   var sumActual = 0.0 println("Letter\t Actual Expected") println("------\t-------- --------") for (i in 0..7) { val generated = actual[i].toDouble() / n println("${letters[i]}\t${String.format("%8.6f %8.6f", generated, probs[i])}") sumActual += generated } println("\t-------- --------") println("\t${"%8.6f".format(sumActual)} 1.000000") }
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 insertion order. Task Create a priority queue.   The queue must support at least two operations:   Insertion.   An element is added to the queue with a priority (a numeric value).   Top item removal.   Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: Priority Task ══════════ ════════════════ 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient.   A typical implementation has   O(log n)   insertion and extraction time,   where   n   is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc.   If so, discuss the reasons behind it.
#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 := pq.get() do write(task[1]," -> ",task[2]) end  
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 example in the code are shown in the diagram   (below and to the right). The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.
#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 = x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2 v14 = 2*s2*r2 - 2*s1*r1   v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2 v24 = 2*s3*r3 - 2*s2*r2   w12 = v12/v11 w13 = v13/v11 w14 = v14/v11   w22 = v22/v21 - w12 w23 = v23/v21 - w13 w24 = v24/v21 - w14   p = -w23/w22 q = w24/w22 m = -w12*p - w13 n = w14 - w12*q   a = n**2 + q**2 - 1 b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 c = x1**2 + m**2 - 2*m*x1 + p**2 + y1**2 - 2*p*y1 - r1**2   d = b**2 - 4*a*c rs = (-b - Math.sqrt(d)) / (2*a) xs = m + n*rs ys = p + q*rs   self.new(xs, ys, rs) end   def to_s "Circle: x=#{@x}, y=#{@y}, r=#{@r}" end end   puts c1 = Circle.new(0, 0, 1) puts c2 = Circle.new(2, 4, 2) puts c3 = Circle.new(4, 0, 1)   puts Circle.apollonius(c1, c2, c3) puts Circle.apollonius(c1, c2, c3, -1, -1, -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 ARGV. See also Command-line arguments Examples from GitHub.
#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 ARGV. See also Command-line arguments Examples from GitHub.
#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, that is, if their pairwise greatest common divisors g c d ( a , b ) = g c d ( a , c ) = g c d ( b , c ) = 1 {\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1} . Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ( g c d ( a , b ) = 1 {\displaystyle {\rm {gcd}}(a,b)=1} ).   Each triple forms the length of the sides of a right triangle, whose perimeter is P = a + b + c {\displaystyle P=a+b+c} . Task The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. Extra credit Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner. Related tasks   Euler's sum of powers conjecture   List comprehensions   Pythagorean quadruples
#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 : " + sum + nl see "Primitives : " + prime + nl   func gcd gcd, b while b c = gcd gcd = b b = c % b end return gcd  
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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
#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's theorem), write "" then the counter then " " on the console without advancing. Repeat.   A prime is a number.   A factorial is a number.   To find a factorial of a number: Put 1 into the factorial. Loop. If a counter is past the number, exit. Multiply the factorial by the counter. Repeat.   To decide if a number is prime (via Wilson's theorem): If the number is less than 1, say no. Find a factorial of the number minus 1. Bump the factorial. If the factorial is evenly divisible by the number, say yes. Say no.