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/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
#PL.2FI
PL/I
/* primality by Wilson's theorem */ wilson: procedure options( main ); declare n binary(15)fixed;   isWilsonPrime: procedure( n )returns( bit(1) ); declare n binary(15)fixed; declare ( fmodp, i ) binary(15)fixed; fmodp = 1; do i = 2 to n - 1; fmodp = mod( fmodp * i, n ); end; return ( fmodp = n - 1 ); end isWilsonPrime ;   do n = 1 to 100; if isWilsonPrime( n ) then do; put edit( n ) ( f(3) ); end; end; end wilson ;
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 %
#Racket
Racket
#lang racket   (require math/number-theory)   (define limit 1000000)   (define table (for/fold ([table (hash)] [prev 2] #:result table) ([p (in-list (next-primes 2 (sub1 limit)))]) (define p-mod (modulo p 10)) (values (hash-update table (cons prev p-mod) add1 0) p-mod)))   (define (pair<? p q) (or (< (car p) (car q)) (and (= (car p) (car q)) (< (cdr p) (cdr q)))))   (printf "~a first primes. Transitions prime % 10 → next-prime % 10.\n" limit) (for ([item (sort (hash->list table) pair<? #:key car)]) (match-define (cons (cons x y) freq) item) (printf "~a → ~a count: ~a frequency: ~a %\n" x y (~a freq #:min-width 8 #:align 'right) (~r (* 100 freq (/ 1 limit)) #:precision '(= 2))))
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 %
#Raku
Raku
use Math::Primesieve;   my %conspiracy; my $upto = 1_000_000; my $sieve = Math::Primesieve.new; my @primes = $sieve.n-primes($upto+1);   @primes[^($upto+1)].reduce: -> $a, $b { my $d = $b % 10; %conspiracy{"$a → $d count:"}++; $d; }   say "$_ \tfrequency: {($_.value/$upto*100).round(.01)} %" for %conspiracy.sort;
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
#Clojure
Clojure
;;; No stack consuming algorithm (defn factors "Return a list of factors of N." ([n] (factors n 2 ())) ([n k acc] (if (= 1 n) acc (if (= 0 (rem n k)) (recur (quot n k) k (cons k acc)) (recur n (inc k) acc)))))
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | 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.2B.2B
C++
int* pointer2(&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.
#COBOL
COBOL
01 ptr USAGE POINTER TO Some-Type. 01 prog-ptr USAGE PROGRAM-POINTER "some-program". *> TO is optional
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.
#Common_Lisp
Common Lisp
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By value: structs, statically sized arrays, and other // primitives (int, char, etc...); // By reference: classes; // By kind of reference: dynamically sized arrays, array slices.   struct S {} class C {}   void foo1(S s) {} // By value. void foo2(C c) {} // By reference. void foo3(int i) {} // By value. void foo4(int[4] i) {} // By value (unlike C). void foo6(int[] i) {} // Just length-pointer struct by value. void foo5(T)(ref T t) {} // By reference regardless of what type // T really is. }
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.
#ALGOL_68
ALGOL 68
#!/usr/bin/algol68g-full --script # # -*- coding: utf-8 -*- #   PR READ "prelude/errata.a68" PR; PR READ "prelude/exception.a68" PR; PR READ "prelude/math_lib.a68" PR;   CO REQUIRED BY "prelude/graph_2d.a68" CO MODE GREAL= REAL; # single precision # FORMAT greal repr = $g(-3,0)$; PR READ "prelude/graph_2d.a68" PR;   []REAL x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9); []REAL y = (2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);   test:( REF GRAPHDD test graph = INIT LOC GRAPHDD; type OF window OF test graph := "gif"; # or gif, ps, X, pnm etc #   title OF test graph := "Plot coordinate pairs"; sub title OF test graph := "Algol68";   interval OF (axis OF test graph)[x axis] := (0, 8); label OF (axis OF test graph)[x axis] := "X axis";   interval OF (axis OF test graph)[y axis] := (0, 200); label OF (axis OF test graph)[y axis] := "Y axis";   PROC curve = (POINTYIELD yield)VOID: FOR i TO UPB x DO yield((x[i],y[i])) OD;   (begin curve OF (METHODOF test graph))(~); (add curve OF (METHODOF test graph))(curve, (red,solid)); (end curve OF (METHODOF test graph))(~) );   PR READ "postlude/exception.a68" PR
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
#BASIC
BASIC
INSTALL @lib$ + "CLASSLIB"   REM Create parent class with void 'doprint' method: DIM PrintableShape{doprint} PROC_class(PrintableShape{})   REM Create derived class for Point: DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor} PROC_inherit(Point{}, PrintableShape{}) DEF Point.setxy (x,y) : Point.x# = x : Point.y# = y : ENDPROC DEF Point.retx = Point.x# DEF Point.rety = Point.y# DEF Point.@constructor Point.x# = 1.23 : Point.y# = 4.56 : ENDPROC DEF Point.@@destructor : ENDPROC DEF Point.doprint : PRINT Point.x#, Point.y# : ENDPROC PROC_class(Point{})   REM Create derived class for Circle: DIM Circle{x#, y#, r#, setxy, setr, retx, rety, retr, @con, @@des} PROC_inherit(Circle{}, PrintableShape{}) DEF Circle.setxy (x,y) : Circle.x# = x : Circle.y# = y : ENDPROC DEF Circle.setr (r) : Circle.r# = r : ENDPROC DEF Circle.retx = Circle.x# DEF Circle.rety = Circle.y# DEF Circle.retr = Circle.r# DEF Circle.@con Circle.x# = 3.2 : Circle.y# = 6.5 : Circle.r# = 7 : ENDPROC DEF Circle.@@des : ENDPROC DEF Circle.doprint : PRINT Circle.x#, Circle.y#, Circle.r# : ENDPROC PROC_class(Circle{})   REM Test the polymorphic 'doprint' function: PROC_new(mypoint{}, Point{}) PROC(mypoint.doprint) PROC_discard(mypoint{}) PROC_new(mycircle{}, Circle{}) PROC(mycircle.doprint) PROC_discard(mycircle{}) 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
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind }   private const bool Y = true; private const char C = '♣', D = '♦', H = '♥', S = '♠'; private const int rankMask = 0b11_1111_1111_1111; private const int suitMask = 0b1111 << 14; private static readonly string[] ranks = { "a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k" }; private static readonly string[] suits = { C + "", D + "", H + "", S + "" }; private static readonly Card[] deck = (from suit in Range(1, 4) from rank in Range(1, 13) select new Card(rank, suit)).ToArray();   public static void Main() { string[] hands = { "2♥ 2♦ 2♣ k♣ q♦", "2♥ 5♥ 7♦ 8♣ 9♠", "a♥ 2♦ 3♣ 4♣ 5♦", "2♥ 3♥ 2♦ 3♣ 3♦", "2♥ 7♥ 2♦ 3♣ 3♦", "2♥ 7♥ 7♦ 7♣ 7♠", "10♥ j♥ q♥ k♥ a♥", "4♥ 4♠ k♠ 5♦ 10♠", "q♣ 10♣ 7♣ 6♣ 4♣", "4♥ 4♣ 4♥ 4♠ 4♦", //duplicate card "joker 2♦ 2♠ k♠ q♦", "joker 5♥ 7♦ 8♠ 9♦", "joker 2♦ 3♠ 4♠ 5♠", "joker 3♥ 2♦ 3♠ 3♦", "joker 7♥ 2♦ 3♠ 3♦", "joker 7♥ 7♦ 7♠ 7♣", "joker j♥ q♥ k♥ A♥", "joker 4♣ k♣ 5♦ 10♠", "joker k♣ 7♣ 6♣ 4♣", "joker 2♦ joker 4♠ 5♠", "joker Q♦ joker A♠ 10♠", "joker Q♦ joker A♦ 10♦", "joker 2♦ 2♠ joker q♦" }; foreach (var h in hands) { Console.WriteLine($"{h}: {Analyze(h).Name()}"); } }   static string Name(this Hand hand) => string.Join('-', hand.ToString().Split('_')).ToLower();   static List<T> With<T>(this List<T> list, int index, T item) { list[index] = item; return list; }   struct Card : IEquatable<Card>, IComparable<Card> { public static readonly Card Invalid = new Card(-1, -1); public static readonly Card Joker = new Card(0, 0);   public Card(int rank, int suit) { (Rank, Suit, Code) = (rank, suit) switch { (_, -1) => (-1, -1, -1), (-1, _) => (-1, -1, -1), (0, _) => (0, 0, 0), (1, _) => (rank, suit, (1 << (13 + suit)) | ((1 << 13) | 1)), (_, _) => (rank, suit, (1 << (13 + suit)) | (1 << (rank - 1))) }; }   public static implicit operator Card((int rank, int suit) tuple) => new Card(tuple.rank, tuple.suit); public int Rank { get; } public int Suit { get; } public int Code { get; }   public override string ToString() => Rank switch { -1 => "invalid", 0 => "joker", _ => $"{ranks[Rank-1]}{suits[Suit-1]}" };   public override int GetHashCode() => Rank << 16 | Suit; public bool Equals(Card other) => Rank == other.Rank && Suit == other.Suit;   public int CompareTo(Card other) { int c = Rank.CompareTo(other.Rank); if (c != 0) return c; return Suit.CompareTo(other.Suit); } }   static Hand Analyze(string hand) { var cards = ParseHand(hand); if (cards.Count != 5) return Hand.Invalid; //hand must consist of 5 cards cards.Sort(); if (cards[0].Equals(Card.Invalid)) return Hand.Invalid; int jokers = cards.LastIndexOf(Card.Joker) + 1; if (jokers > 2) return Hand.Invalid; //more than 2 jokers if (cards.Skip(jokers).Distinct().Count() + jokers != 5) return Hand.Invalid; //duplicate cards   if (jokers == 2) return (from c0 in deck from c1 in deck select Evaluate(cards.With(0, c0).With(1, c1))).Max(); if (jokers == 1) return (from c0 in deck select Evaluate(cards.With(0, c0))).Max(); return Evaluate(cards); }   static List<Card> ParseHand(string hand) => hand.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries) .Select(card => ParseCard(card.ToLower())).ToList();   static Card ParseCard(string card) => (card.Length, card) switch { (5, "joker") => Card.Joker, (3, _) when card[..2] == "10" => (10, ParseSuit(card[2])), (2, _) => (ParseRank(card[0]), ParseSuit(card[1])), (_, _) => Card.Invalid };   static int ParseRank(char rank) => rank switch { 'a' => 1, 'j' => 11, 'q' => 12, 'k' => 13, _ when rank >= '2' && rank <= '9' => rank - '0', _ => -1 };   static int ParseSuit(char suit) => suit switch { C => 1, 'c' => 1, D => 2, 'd' => 2, H => 3, 'h' => 3, S => 4, 's' => 4, _ => -1 };   static Hand Evaluate(List<Card> hand) { var frequencies = hand.GroupBy(c => c.Rank).Select(g => g.Count()).OrderByDescending(c => c).ToArray(); (int f0, int f1) = (frequencies[0], frequencies.Length > 1 ? frequencies[1] : 0);   return (IsFlush(), IsStraight(), f0, f1) switch { (_, _, 5, _) => Hand.Five_Of_A_Kind, (Y, Y, _, _) => Hand.Straight_Flush, (_, _, 4, _) => Hand.Four_Of_A_Kind, (_, _, 3, 2) => Hand.Full_House, (Y, _, _, _) => Hand.Flush, (_, Y, _, _) => Hand.Straight, (_, _, 3, _) => Hand.Three_Of_A_Kind, (_, _, 2, 2) => Hand.Two_Pair, (_, _, 2, _) => Hand.One_Pair, _ => Hand.High_Card };   bool IsFlush() => hand.Aggregate(suitMask, (r, c) => r & c.Code) > 0;   bool IsStraight() { int r = hand.Aggregate(0, (r, c) => r | c.Code) & rankMask; for (int i = 0; i < 4; i++) r &= r << 1; return r > 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.
#AppleScript
AppleScript
--------------------- POPULATION COUNT ---------------------   -- populationCount :: Int -> Int on populationCount(n) -- The number of non-zero bits in the binary -- representation of the integer n.   script go on |λ|(x) if 0 < x then Just({x mod 2, x div 2}) else Nothing() end if end |λ| end script   integerSum(unfoldr(go, n)) end populationCount     --------------------------- TEST --------------------------- on run set {evens, odds} to partition(compose(even, populationCount), ¬ enumFromTo(0, 59))   unlines({"Population counts of the first 30 powers of three:", ¬ tab & showList(map(compose(populationCount, raise(3)), ¬ enumFromTo(0, 29))), ¬ "", ¬ "First thirty 'evil' numbers:", ¬ tab & showList(evens), ¬ "", ¬ "First thirty 'odious' numbers:", ¬ tab & showList(odds)}) end run     ------------------------- GENERIC --------------------------   -- Just :: a -> Maybe a on Just(x) -- Constructor for an inhabited Maybe (option type) value. -- Wrapper containing the result of a computation. {type:"Maybe", Nothing:false, Just:x} end Just     -- Nothing :: Maybe a on Nothing() -- Constructor for an empty Maybe (option type) value. -- Empty wrapper returned where a computation is not possible. {type:"Maybe", Nothing:true} end Nothing     -- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c on compose(f, g) script property mf : mReturn(f) property mg : mReturn(g) on |λ|(x) mf's |λ|(mg's |λ|(x)) end |λ| end script end compose     -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo     -- even :: Int -> Bool on even(x) 0 = x mod 2 end even     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn   -- partition :: (a -> Bool) -> [a] -> ([a], [a]) on partition(f, xs) tell mReturn(f) set ys to {} set zs to {} repeat with x in xs set v to contents of x if |λ|(v) then set end of ys to v else set end of zs to v end if end repeat end tell {ys, zs} end partition   -- raise :: Num -> Int -> Num on raise(m) script on |λ|(n) m ^ n end |λ| end script end raise     -- integerSum :: [Num] -> Num on integerSum(xs) script addInt on |λ|(a, b) a + (b as integer) end |λ| end script   foldl(addInt, 0, xs) end integerSum     -- intercalate :: String -> [String] -> String on intercalate(delim, xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, delim} set s to xs as text set my text item delimiters to dlm s end intercalate     -- showList :: [a] -> String on showList(xs) "[" & intercalate(",", map(my str, xs)) & "]" end showList     -- str :: a -> String on str(x) x as string end str     -- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] on unfoldr(f, v) -- A list derived from a simple value. -- Dual to foldr. -- unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- -> [10,9,8,7,6,5,4,3,2,1] set xr to {v, v} -- (value, remainder) set xs to {} tell mReturn(f) repeat -- Function applied to remainder. set mb to |λ|(item 2 of xr) if Nothing of mb then exit repeat else -- New (value, remainder) tuple, set xr to Just of mb -- and value appended to output list. set end of xs to item 1 of xr end if end repeat end tell return xs end unfoldr     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s end unlines
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
#Common_Lisp
Common Lisp
(defun add (p1 p2) (do ((sum '())) ((and (endp p1) (endp p2)) (nreverse sum)) (let ((pd1 (if (endp p1) -1 (caar p1))) (pd2 (if (endp p2) -1 (caar p2)))) (multiple-value-bind (c1 c2) (cond ((> pd1 pd2) (values (cdr (pop p1)) 0)) ((< pd1 pd2) (values 0 (cdr (pop p2)))) (t (values (cdr (pop p1)) (cdr (pop p2))))) (let ((csum (+ c1 c2))) (unless (zerop csum) (setf sum (acons (max pd1 pd2) csum sum))))))))   (defun multiply (p1 p2) (flet ((*p2 (p) (destructuring-bind (d . c) p (loop for (pd . pc) in p2 collecting (cons (+ d pd) (* c pc)))))) (reduce 'add (mapcar #'*p2 p1) :initial-value '())))   (defun subtract (p1 p2) (add p1 (multiply '((0 . -1)) p2)))   (defun divide (dividend divisor &aux (sum '())) (assert (not (endp divisor)) (divisor) 'division-by-zero :operation 'divide :operands (list dividend divisor)) (flet ((floor1 (dividend divisor) (if (endp dividend) (values '() ()) (destructuring-bind (d1 . c1) (first dividend) (destructuring-bind (d2 . c2) (first divisor) (if (> d2 d1) (values '() dividend) (let* ((quot (list (cons (- d1 d2) (/ c1 c2)))) (rem (subtract dividend (multiply divisor quot)))) (values quot rem)))))))) (loop (multiple-value-bind (quotient remainder) (floor1 dividend divisor) (if (endp quotient) (return (values sum remainder)) (setf dividend remainder sum (add quotient sum)))))))
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.
#Elena
Elena
import extensions;   class T { Name = "T";   T clone() = new T(); }   class S : T { Name = "S";   T clone() = new S(); }   public program() { T original := new S(); T clone := original.clone();   console.printLine(original.Name); console.printLine(clone.Name) }
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.
#F.23
F#
type T() = // expose protected MemberwiseClone method (and downcast the result) member x.Clone() = x.MemberwiseClone() :?> T // virtual method Print with default implementation abstract Print : unit -> unit default x.Print() = printfn "I'm a T!"   type S() = inherit T() override x.Print() = printfn "I'm an S!"   let s = new S() let s2 = s.Clone() // the static type of s2 is T, but it "points" to an S s2.Print() // prints "I'm an S!"
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be 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.
#Factor
Factor
USING: classes kernel prettyprint serialize ; TUPLE: A ; TUPLE: C < A ; : serial-clone ( obj -- obj' ) object>bytes bytes>object ;   C new [ clone ] [ serial-clone ] bi [ class . ] bi@
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
#Nim
Nim
# Pendulum simulation.   import math, random   import gintro/[gobject, gdk, gtk, gio, glib, cairo]   const Width = 500 Height = 500 DrawIters = 72 Red = [float 1, 0, 0] Green = [float 0, 1, 0] Blue = [float 0, 0, 1] Black = [float 0, 0, 0] White = [float 255, 255, 255] Gold = [float 255, 215, 0] Colors = [Blue, Red, Green, White, Gold] Angles = [75, 100, 135, 160]   type   Vec2 = tuple[x, y: float] Point = Vec2   # Description of the simulation. Simulation = ref object area: DrawingArea xmax, ymax: float center: Point itercount: int   #---------------------------------------------------------------------------------------------------   proc newSimulation(area: DrawingArea; width, height: int): Simulation {.noInit.} = ## Allocate and initialize the simulation object.   new(result) result.area = area result.xmax = float(width - 1) result.ymax = float(height - 1) result.center = (result.xmax * 0.5, result.ymax * 0.5)   #---------------------------------------------------------------------------------------------------   func δ(r, θ: float): Vec2 = (r * cos(degToRad(θ)), r * sin(degToRad(θ)))   #---------------------------------------------------------------------------------------------------   func nextPoint(p: Point; r, θ: float): Point = let dp = δ(r, θ) result = (p.x + dp.x, p.y + dp.y)   #---------------------------------------------------------------------------------------------------   proc draw(sim: Simulation; context: cairo.Context) = ## Draw the spiral.   context.setSource(Black) context.rectangle(0, 0, sim.xmax, sim.ymax) context.fill()   let colorIndex = sim.itercount mod Colors.len let color = Colors[colorIndex]   var p1 = sim.center let δθ = Angles[sim.itercount mod Angles.len].toFloat var θ = δθ * rand(1.0) * 3 var r = 5.0 let δr = 3.0   for _ in 1..DrawIters: let p2 = p1.nextPoint(r, θ) context.moveTo(p1.x, p1.y) context.setSource(color) context.lineTo(p2.x, p2.y) context.setLineWidth(2) context.stroke() θ += δθ r += δr p1 = p2   #---------------------------------------------------------------------------------------------------   proc update(sim: Simulation): gboolean = ## Update the simulation state.   result = gboolean(1) sim.draw(sim.area.window.cairoCreate()) inc sim.itercount   #---------------------------------------------------------------------------------------------------   proc activate(app: Application) = ## Activate the application.   let window = app.newApplicationWindow() window.setSizeRequest(Width, Height) window.setTitle("Polyspiral")   let area = newDrawingArea() window.add(area)   let sim = newSimulation(area, Width, Height)   timeoutAdd(500, update, sim)   window.showAll()   #———————————————————————————————————————————————————————————————————————————————————————————————————   let app = newApplication(Application, "Rosetta.polyspiral") discard app.connect("activate", activate) discard app.run()
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
#PARI.2FGP
PARI/GP
  \\ Plot the line from x1,y1 to x2,y2. plotline(x1,y1,x2,y2,w=0)={plotmove(w, x1,y1);plotrline(w,x2-x1,y2-y1);} \\ Convert degrees to radians. rad2(degs)={return(degs*Pi/180.0)} \\ Convert Polar coordinates to Cartesian. cartes2(r,a,rndf=0)={my(v,x,y); x=r*cos(a); y=r*sin(a); if(rndf==0, return([x,y]), return(round([x,y])))}  
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.
#D
D
import std.algorithm; import std.range; import std.stdio;   auto average(R)(R r) { auto t = r.fold!("a+b", "a+1")(0, 0); return cast(double) t[0] / t[1]; }   void polyRegression(int[] x, int[] y) { auto n = x.length; auto r = iota(0, n).array; auto xm = x.average(); auto ym = y.average(); auto x2m = r.map!"a*a".average(); auto x3m = r.map!"a*a*a".average(); auto x4m = r.map!"a*a*a*a".average(); auto xym = x.zip(y).map!"a[0]*a[1]".average(); auto x2ym = x.zip(y).map!"a[0]*a[0]*a[1]".average();   auto sxx = x2m - xm * xm; auto sxy = xym - xm * ym; auto sxx2 = x3m - xm * x2m; auto sx2x2 = x4m - x2m * x2m; auto sx2y = x2ym - x2m * ym;   auto b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); auto c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); auto a = ym - b * xm - c * x2m;   real abc(int xx) { return a + b * xx + c * xx * xx; }   writeln("y = ", a, " + ", b, "x + ", c, "x^2"); writeln(" Input Approximation"); writeln(" x y y1"); foreach (i; 0..n) { writefln("%2d %3d  %5.1f", x[i], y[i], abc(x[i])); } }   void main() { auto x = iota(0, 11).array; auto y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; polyRegression(x, 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.
#Bracmat
Bracmat
( ( powerset = done todo first .  !arg:(?done.?todo) & (  !todo:%?first ?todo & (powerset$(!done !first.!todo),powerset$(!done.!todo)) | !done ) ) & out$(powerset$(.1 2 3 4)) );
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or 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.
#Burlesque
Burlesque
  blsq ) {1 2 3 4}R@ {{} {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}}  
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
#AWK
AWK
$ awk 'func prime(n){for(d=2;d<=sqrt(n);d++)if(!(n%d)){return 0};return 1}{print prime($1)}'
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to 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
#D
D
import std.stdio, std.range;   double priceRounder(in double price) pure nothrow in { assert(price >= 0 && price <= 1.0); } body { static immutable cin = [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01], cout = [.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00]; return cout[cin.assumeSorted.lowerBound(price).length]; }   void main() { foreach (const price; [0.7388727, 0.8593103, 0.826687, 0.3444635]) price.priceRounder.writeln; }
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
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64   Sub ListProperDivisors(limit As Integer) If limit < 1 Then Return For i As Integer = 1 To limit Print Using "##"; i; Print " ->"; If i = 1 Then Print " (None)" Continue For End if For j As Integer = 1 To i \ 2 If i Mod j = 0 Then Print " "; j; Next j Print Next i End Sub   Function CountProperDivisors(number As Integer) As Integer If number < 2 Then Return 0 Dim count As Integer = 0 For i As Integer = 1 To number \ 2 If number Mod i = 0 Then count += 1 Next Return count End Function   Dim As Integer n, count, most = 1, maxCount = 0   Print "The proper divisors of the following numbers are :" Print ListProperDivisors(10)   For n As Integer = 2 To 20000 count = CountProperDivisors(n) If count > maxCount Then maxCount = count most = n EndIf Next   Print Print Str(most); " has the most proper divisors, namely"; maxCount Print Print "Press any key to exit the program" Sleep 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)
#Liberty_BASIC
Liberty BASIC
  names$="aleph beth gimel daleth he waw zayin heth" dim sum(8) dim counter(8)   s = 0 for i = 1 to 7 s = s+1/(i+4) sum(i)=s next   N =1000000 ' number of throws   for i =1 to N rand =rnd( 1) for j = 1 to 7 if sum(j)> rand then exit for next counter(j)=counter(j)+1 next   print "Observed", "Intended" for i = 1 to 8 print word$(names$, i), using( "#.#####", counter(i) /N), using( "#.#####", 1/(i+4)) next  
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.
#J
J
coclass 'priorityQueue'   PRI=: '' QUE=: ''   insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 )   topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
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.
#Scala
Scala
object ApolloniusSolver extends App { case class Circle(x: Double, y: Double, r: Double) object Tangent extends Enumeration { type Tangent = Value val intern = Value(-1) val extern = Value(1) }   import Tangent._ import scala.Math._   val solveApollonius: (Circle, Circle, Circle, Triple[Tangent, Tangent, Tangent]) => Circle = (c1, c2, c3, tangents) => { val fv: (Circle, Circle, Int, Int) => Tuple4[Double, Double, Double, Double] = (c1, c2, s1, s2) => { val v11 = 2 * c2.x - 2 * c1.x val v12 = 2 * c2.y - 2 * c1.y val v13 = pow(c1.x, 2) - pow(c2.x, 2) + pow(c1.y, 2) - pow(c2.y, 2) - pow(c1.r, 2) + pow(c2.r, 2) val v14 = 2 * s2 * c2.r - 2 * s1 * c1.r Tuple4(v11, v12, v13, v14) } val (s1, s2, s3) = (tangents._1.id, tangents._2.id, tangents._3.id)   val (v11, v12, v13, v14) = fv(c1, c2, s1, s2) val (v21, v22, v23, v24) = fv(c2, c3, s2, s3)   val w12 = v12 / v11 val w13 = v13 / v11 val w14 = v14 / v11   val w22 = v22 / v21 - w12 val w23 = v23 / v21 - w13 val w24 = v24 / v21 - w14   val P = -w23 / w22 val Q = w24 / w22 val M = -w12 * P - w13 val N = w14 - w12 * Q   val a = N*N + Q*Q - 1 val b = 2*M*N - 2*N*c1.x + 2*P*Q - 2*Q*c1.y + 2*s1*c1.r val c = pow(c1.x, 2) + M*M - 2*M*c1.x + P*P + pow(c1.y, 2) - 2*P*c1.y - pow(c1.r, 2)   // Find a root of a quadratic equation. This requires the circle centers not to be e.g. colinear val D = b*b - 4*a*c val rs = (-b - sqrt(D)) / (2*a)   Circle(x=M + N*rs, y=P + Q*rs, r=rs) }   val c1 = Circle(x=0.0, y=0.0, r=1.0) val c2 = Circle(x=4.0, y=0.0, r=1.0) val c3 = Circle(x=2.0, y=4.0, r=2.0)   println("c1: "+c1) println("c2: "+c2) println("c3: "+c3)   println{ val tangents = Triple(intern, intern, intern) "red circle: tangents="+tangents+" cs=" + solveApollonius(c1, c2, c3, tangents) } println{ val tangents = Triple(extern, extern, extern) "green circle: tangents="+tangents+" cs=" + solveApollonius(c1, c2, c3, tangents) }   println("all combinations:") for ( ti <- Tangent.values) for ( tj <- Tangent.values) for ( tk <- Tangent.values) { println{ val format: Circle => String = c => { "Circle(x=%8.5f, y=%8.5f, r=%8.5f)".format(c.x, c.y, c.r) } val tangents = Triple(ti, tj, tk) "tangents: " + tangents + " -> cs=" + format(solveApollonius(c1, c2, c3, tangents)) } } }
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.
#UNIX_Shell
UNIX Shell
#!/bin/sh   echo "Program: $0"
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.
#Vala
Vala
  public static void main(string[] args){ string command_name = args[0];   stdout.printf("%s\n", command_name); }  
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
#Ruby
Ruby
class PythagoranTriplesCounter def initialize(limit) @limit = limit @total = 0 @primitives = 0 generate_triples(3, 4, 5) end attr_reader :total, :primitives   private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit   @primitives += 1 @total += @limit / perim   generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c) generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c) end end   perim = 10 while perim <= 100_000_000 c = PythagoranTriplesCounter.new perim p [perim, c.total, c.primitives] perim *= 10 end
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.
#Retro
Retro
problem? [ bye ] if
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.
#REXX
REXX
/*REXX program showing five ways to perform a REXX program termination. */   /*─────1st way────────────────────────────────────────────────────────*/ exit     /*─────2nd way────────────────────────────────────────────────────────*/ exit (expression) /*Note: the "expression" doesn't need parentheses*/ /*"expression" is any REXX expression. */     /*─────3rd way────────────────────────────────────────────────────────*/ return /*which returns to this program's invoker. If */ /*this is the main body (and not a subroutine), */ /*the REXX interpreter terminates the program. */     /*─────4th way────────────────────────────────────────────────────────*/ return (expression) /* [See the note above concerning parentheses.] */     /*─────5th way────────────────────────────────────────────────────────*/ /*control*/ /* │ */ /*if there is no EXIT and program control "falls */ /* │ */ /*through" to the "bottom" (end) of the program, */ /* │ */ /*an EXIT is simulated and the program is */ /* │ */ /*terminated. */ /* ↓ */ /* e-o-f */ /* e-o-f = end-of-file. */
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
#PL.2FM
PL/M
100H: /* FIND PRIMES USING WILSON'S THEOREM: */ /* P IS PRIME IF ( ( P - 1 )! + 1 ) MOD P = 0 */   DECLARE FALSE LITERALLY '0';   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */ DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END BDOS; PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PRINT$NUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; V = N; W = LAST( N$STR ); N$STR( W ) = '$'; N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL PRINT$STRING( .N$STR( W ) ); END PRINT$NUMBER;   /* RETURNS TRUE IF P IS PRIME BY WILSON'S THEOREM, FALSE OTHERWISE */ /* COMPUTES THE FACTORIAL MOD P AT EACH STAGE, SO AS TO ALLOW */ /* FOR NUMBERS WHOSE FACTORIAL WON'T FIT IN 16 BITS */ IS$WILSON$PRIME: PROCEDURE( P )BYTE; DECLARE P ADDRESS; IF P < 2 THEN RETURN FALSE; ELSE DO; DECLARE ( I, FACTORIAL$MOD$P ) ADDRESS; FACTORIAL$MOD$P = 1; DO I = 2 TO P - 1; FACTORIAL$MOD$P = ( FACTORIAL$MOD$P * I ) MOD P; END; RETURN FACTORIAL$MOD$P = P - 1; END; END IS$WILSON$PRIME;   DECLARE I ADDRESS; DO I = 1 TO 100; IF IS$WILSON$PRIME( I ) THEN DO; CALL PRINT$CHAR( ' ' ); CALL PRINT$NUMBER( I ); END; END;   EOF
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 %
#REXX
REXX
/*REXX pgm shows a table of what last digit follows the previous last digit for N primes*/ parse arg N . /*N: the number of primes to be genned*/ if N=='' | N=="," then N= 1000000 /*Not specified? Then use the default.*/ Np= N+1; w= length(N-1) /*W: width used for formatting output.*/ H= N* (2**max(4, (w%2+1) ) ) /*used as a rough limit for the sieve. */ @.= . /*assume all numbers are prime (so far)*/ #= 1 /*primes found so far {assume prime 2}.*/ do j=3 by 2; if @.j=='' then iterate /*Is composite? Then skip this number.*/ #= #+1 /*bump the prime number counter. */ do m=j*j to H by j+j; @.m= /*strike odd multiples as composite. */ end /*m*/ if #==Np then leave /*Enough primes? Then done with gen. */ end /*j*/ /* [↑] gen using Eratosthenes' sieve. */ !.= 0 /*initialize all the frequency counters*/ say 'For ' N " primes used in this study:" /*show hdr information about this run. */ r= 2 /*the last digit of the very 1st prime.*/ #= 1 /*the number of primes looked at so far*/ do i=3 by 2; if @.i=='' then iterate /*This number composite? Then ignore it*/ #= # + 1; parse var i '' -1 x /*bump prime counter; get its last dig.*/  !.r.x= !.r.x +1; r= x /*bump the last digit counter for prev.*/ if #==Np then leave /*Done? Then leave this DO loop. */ end /*i*/ /* [↑] examine almost all odd numbers.*/ say /* [↓] display the results to the term*/ do d=1 for 9; if d//2 | d==2 then say /*display a blank line (if appropriate)*/ do f=1 for 9; if !.d.f==0 then iterate /*don't show if the count is zero. */ say 'digit ' d "──►" f ' has a count of: ', right(!.d.f, w)", frequency of:" right(format(!.d.f / N*100, , 4)'%.', 10) end /*f*/ end /*d*/ /*stick a fork in it, we're all done. */
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
#Commodore_BASIC
Commodore BASIC
9000 REM ----- function generate 9010 REM in ... i ... number 9020 REM out ... pf() ... factors 9030 REM mod ... ca ... pf candidate 9040 pf(0)=0 : ca=2 : REM special case 9050 IF i=1 THEN RETURN 9060 IF INT(i/ca)*ca=i THEN GOSUB 9200 : GOTO 9050 9070 FOR ca=3 TO INT( SQR(i)) STEP 2 9080 IF i=1 THEN RETURN 9090 IF INT(i/ca)*ca=i THEN GOSUB 9200 : GOTO 9080 9100 NEXT 9110 IF i>1 THEN ca=i : GOSUB 9200 9120 RETURN 9200 pf(0)=pf(0)+1 9210 pf(pf(0))=ca 9220 i=i/ca 9230 RETURN
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.
#D
D
void main() { // Take the address of 'var' and placing it in a pointer: int var; int* ptr = &var;   // Take the pointer to the first item of an array: int[10] data; auto p2 = data.ptr;     // Depending on variable type, D will automatically pass either // by value or reference. // By value: structs, statically sized arrays, and other // primitives (int, char, etc...); // By reference: classes; // By kind of reference: dynamically sized arrays, array slices.   struct S {} class C {}   void foo1(S s) {} // By value. void foo2(C c) {} // By reference. void foo3(int i) {} // By value. void foo4(int[4] i) {} // By value (unlike C). void foo6(int[] i) {} // Just length-pointer struct by value. void foo5(T)(ref T t) {} // By reference regardless of what type // T really is. }
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.
#Delphi
Delphi
pMyPointer : Pointer ;
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.
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1 OnExit, Exit FileOut := A_Desktop "\MyNewFile.png" Font := "Arial" 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] ; Uncomment if Gdip.ahk is not in your standard library ; #Include, Gdip.ahk if (!pToken := Gdip_Startup()) { MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. ExitApp } If (!Gdip_FontFamilyCreate(Font)) { MsgBox, 48, Font error!, The font you have specified does not exist on your system. ExitApp }   pBitmap := Gdip_CreateBitmap(900, 900) , G := Gdip_GraphicsFromImage(pBitmap) , Gdip_SetSmoothingMode(G, 4) , pBrush := Gdip_BrushCreateSolid(0xff000000) , Gdip_FillRectangle(G, pBrush, -3, -3, 906, 906) , Gdip_DeleteBrush(pBrush) , pPen1 := Gdip_CreatePen(0xffffcc00, 2) , pPen2 := Gdip_CreatePen(0xffffffff, 2) , pPen3 := Gdip_CreatePen(0xff447821, 1) , pPen4 := Gdip_CreatePen(0xff0066ff, 2) , Gdip_DrawLine(G, pPen2, 50, 50, 50, 850) , Gdip_DrawLine(G, pPen2, 50, 850, 850, 850) , FontOptions1 := "x0 y870 Right cbbffffff r4 s16 Bold" , Gdip_TextToGraphics(G, 0, FontOptions1, Font, 40, 20)   Loop, % x.MaxIndex() - 1 { Offset1 := 50 + (x[A_Index] * 80) , Offset2 := Offset1 + 80 , Gdip_DrawLine(G, pPen1, Offset1, 850 - (y[A_Index] * 4), Offset1 + 80, 850 - (y[A_Index + 1] * 4)) }   Loop, % x.MaxIndex() { Offset1 := 50 + ((A_Index - 1) * 80) , Offset2 := Offset1 + 80 , Offset3 := 45 + (x[A_Index] * 80) , Offset4 := 845 - (y[A_Index] * 4) , Gdip_DrawLine(G, pPen2, 45, Offset1, 55, Offset1) , Gdip_DrawLine(G, pPen2, Offset2, 845, Offset2, 855) , Gdip_DrawLine(G, pPen3, 50, Offset1, 850, Offset1) , Gdip_DrawLine(G, pPen3, Offset2, 50, Offset2, 850) , Gdip_DrawLine(G, pPen4, Offset3, Offset4, Offset3 + 10, Offset4 + 10) , Gdip_DrawLine(G, pPen4, Offset3, Offset4 + 10, Offset3 + 10, Offset4) , FontOptions1 := "x0 y" (Offset1 - 7) " Right cbbffffff r4 s16 Bold" , FontOptions2 := "x" (Offset2 - 7) " y870 Left cbbffffff r4 s16 Bold" , Gdip_TextToGraphics(G, 220 - (A_Index * 20), FontOptions1, Font, 40, 20) , Gdip_TextToGraphics(G, A_Index, FontOptions2, Font, 40, 20) }   Gdip_DeletePen(pPen1) , Gdip_DeletePen(pPen2) , Gdip_DeletePen(pPen3) , Gdip_DeletePen(pPen4) , Gdip_SaveBitmapToFile(pBitmap, FileOut) , Gdip_DisposeImage(pBitmap) , Gdip_DeleteGraphics(G) Run, % FileOut   Exit: Gdip_Shutdown(pToken) ExitApp
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
#BBC_BASIC
BBC BASIC
INSTALL @lib$ + "CLASSLIB"   REM Create parent class with void 'doprint' method: DIM PrintableShape{doprint} PROC_class(PrintableShape{})   REM Create derived class for Point: DIM Point{x#, y#, setxy, retx, rety, @constructor, @@destructor} PROC_inherit(Point{}, PrintableShape{}) DEF Point.setxy (x,y) : Point.x# = x : Point.y# = y : ENDPROC DEF Point.retx = Point.x# DEF Point.rety = Point.y# DEF Point.@constructor Point.x# = 1.23 : Point.y# = 4.56 : ENDPROC DEF Point.@@destructor : ENDPROC DEF Point.doprint : PRINT Point.x#, Point.y# : ENDPROC PROC_class(Point{})   REM Create derived class for Circle: DIM Circle{x#, y#, r#, setxy, setr, retx, rety, retr, @con, @@des} PROC_inherit(Circle{}, PrintableShape{}) DEF Circle.setxy (x,y) : Circle.x# = x : Circle.y# = y : ENDPROC DEF Circle.setr (r) : Circle.r# = r : ENDPROC DEF Circle.retx = Circle.x# DEF Circle.rety = Circle.y# DEF Circle.retr = Circle.r# DEF Circle.@con Circle.x# = 3.2 : Circle.y# = 6.5 : Circle.r# = 7 : ENDPROC DEF Circle.@@des : ENDPROC DEF Circle.doprint : PRINT Circle.x#, Circle.y#, Circle.r# : ENDPROC PROC_class(Circle{})   REM Test the polymorphic 'doprint' function: PROC_new(mypoint{}, Point{}) PROC(mypoint.doprint) PROC_discard(mypoint{}) PROC_new(mycircle{}, Circle{}) PROC(mycircle.doprint) PROC_discard(mycircle{}) END
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
#C
C
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } }   public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); }   public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); 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
#C.2B.2B
C++
  #include <iostream> #include <sstream> #include <algorithm> #include <vector>   using namespace std;   class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h ); copy( istream_iterator<string>( i ), istream_iterator<string>(), back_inserter<vector<string> >( hand ) ); if( hand.size() != 5 ) return "invalid hand."; vector<string>::iterator it = hand.begin(); sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand."; while( it != hand.end() ) { if( ( *it ).length() != 2 ) return "invalid hand."; int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) ); if( n < 0 || l < 0 ) return "invalid hand."; faceCnt[n]++; suitCnt[l]++; it++; } cout << h << ": "; return analyzeHand(); } private: string analyzeHand() { bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false; for( int x = 0; x < 13; x++ ) switch( faceCnt[x] ) { case 2: if( p1 ) p2 = true; else p1 = true; break; case 3: t = true; break; case 4: f = true; } for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; }   if( !p1 && !p2 && !t && !f ) { int s = 0; for( int x = 0; x < 13; x++ ) { if( faceCnt[x] ) s++; else s = 0; if( s == 5 ) break; } st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] ); }   if( st && fl ) return "straight-flush"; else if( f ) return "four-of-a-kind"; else if( p1 && t ) return "full-house"; else if( fl ) return "flush"; else if( st ) return "straight"; else if( t ) return "three-of-a-kind"; else if( p1 && p2 ) return "two-pair"; else if( p1 ) return "one-pair"; return "high-card"; } string face, suit; unsigned char faceCnt[13], suitCnt[4]; };   int main( int argc, char* argv[] ) { poker p; cout << p.analyze( "2h 2d 2s ks qd" ) << endl; cout << p.analyze( "2h 5h 7d 8s 9d" ) << endl; cout << p.analyze( "ah 2d 3s 4s 5s" ) << endl; cout << p.analyze( "2h 3h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 7d 7s 7c" ) << endl; cout << p.analyze( "th jh qh kh ah" ) << endl; cout << p.analyze( "4h 4c kc 5d tc" ) << endl; cout << p.analyze( "qc tc 7c 6c 4c" ) << endl << endl; return system( "pause" ); }  
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.
#Arturo
Arturo
popCount: function [num][ size select split to :string as.binary num 'x -> x="1" ]   print "population count for the first thirty powers of 3:" print map 0..29 => [popCount 3^&]   print "first thirty evil numbers" print take select 0..100 => [even? popCount &] 30   print "first thirty odious numbers" print take select 0..100 => [odd? popCount &] 30
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for 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
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD) nothrow pure @safe { // Code smell: a function that does two things. static int trimAndDegree(T)(ref T[] poly) nothrow pure @safe @nogc { poly = poly.retro.find!q{ a != b }(0.0).retro; return poly.length.signed - 1; }   auto N = inN.dup; const(double)[] D = inD; const dD = trimAndDegree(D); auto dN = trimAndDegree(N); double[] q; if (dD < 0) throw new Error("ZeroDivisionError"); if (dN >= dD) { q = [0.0].replicate(dN); while (dN >= dD) { auto d = [0.0].replicate(dN - dD) ~ D; immutable mult = q[dN - dD] = N[$ - 1] / d[$ - 1]; d[] *= mult; N[] -= d[]; dN = trimAndDegree(N); } } else q = [0.0]; return tuple(q, N); }     int trimAndDegree1(T)(ref T[] poly) nothrow pure @safe @nogc { poly.length -= poly.retro.countUntil!q{ a != 0 }; return poly.length.signed - 1; }   void main() { immutable N = [-42.0, 0.0, -12.0, 1.0]; immutable D = [-3.0, 1.0, 0.0, 0.0]; writefln("%s / %s = %s remainder %s", N, D, polyDiv(N, D)[]); }
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.
#Forth
Forth
include lib/memcell.4th include 4pp/lib/foos.4pp ( a1 -- a2) :token fork dup allocated dup (~~alloc) swap >r swap over r> smove ; \ allocate an empty object :: T() \ super class T class method: print \ print message method: clone \ clone yourself end-class { \ implementing methods  :method { ." class T" cr } ; defines print fork defines clone ( -- addr) } ;   :: S() \ class S extends T() \ derived from T end-extends { \ print message  :method { ." class S" cr } ; defines print } \ clone yourself ;   new T() t \ create a new object t new S() s \ create a new object s   ." before copy" cr t => print \ use "print" methods s => print   t => clone to tcopy \ cloning t, spawning tcopy s => clone to scopy \ cloning s, spawning scopy   ." after copy" cr tcopy => print \ use "print" methods scopy => print
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.
#Fortran
Fortran
  !----------------------------------------------------------------------- !Module polymorphic_copy_example_module !----------------------------------------------------------------------- module polymorphic_copy_example_module implicit none private ! all by default public :: T,S   type, abstract :: T contains procedure (T_procedure1), deferred, pass :: identify procedure (T_procedure2), deferred, pass :: duplicate end type T     abstract interface subroutine T_procedure1(this) import :: T class(T), intent(inout) :: this end subroutine T_procedure1 function T_procedure2(this) result(Tobj) import :: T class(T), intent(inout) :: this class(T), allocatable :: Tobj end function T_procedure2 end interface   type, extends(T) :: S contains procedure, pass :: identify procedure, pass :: duplicate end type S   contains   subroutine identify(this) implicit none class(S), intent(inout) :: this write(*,*) "S" end subroutine identify   function duplicate(this) result(obj) class(S), intent(inout) :: this class(T), allocatable :: obj allocate(obj, source = S()) end function duplicate   end module polymorphic_copy_example_module   !----------------------------------------------------------------------- !Main program test !----------------------------------------------------------------------- program test use polymorphic_copy_example_module implicit none   class(T), allocatable :: Sobj class(T), allocatable :: Sclone   allocate(Sobj, source = S()) allocate(Sclone, source = Sobj % duplicate())   call Sobj % identify() call Sclone % identify()   end program test  
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
#Perl
Perl
  #!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Polyspiral use warnings; use Tk; use List::Util qw( min );   my $size = 500; my ($width, $height, $x, $y, $dist); my $angleinc = 0; my $active = 0; my $wait = 1000 / 30; my $radian = 90 / atan2 1, 0;   my $mw = MainWindow->new; $mw->title( 'Polyspiral' ); my $c = $mw->Canvas( -width => $size, -height => $size, -relief => 'raised', -borderwidth => 2, )->pack(-fill => 'both', -expand => 1); $mw->bind('<Configure>' => sub { $width = $c->width; $height = $c->height; $dist = min($width, $height) ** 2 / 4 } ); $mw->Button(-text => $_->[0], -command => $_->[1], )->pack(-side => 'right') for [ Exit => sub {$mw->destroy} ], [ 'Start / Pause' => sub { $active ^= 1; step() } ];   MainLoop; -M $0 < 0 and exec $0;   sub step { $active or return; my @pts = ($x = $width >> 1, $y = $height >> 1); my $length = 5; my $angle = $angleinc; $angleinc += 0.05 / $radian; while( ($x - $width / 2)**2 + ($y - $height / 2)**2 < $dist && @pts < 300 ) { push @pts, $x, $y; $x += $length * cos($angle); $y += $length * sin($angle); $length += 3; $angle += $angleinc; } $c->delete('all'); $c->createLine( @pts ); $mw->after($wait => \&step); }
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.
#Emacs_Lisp
Emacs Lisp
(let ((x '(0 1 2 3 4 5 6 7 8 9 10)) (y '(1 6 17 34 57 86 121 162 209 262 321))) (calc-eval "fit(a*x^2+b*x+c,[x],[a,b,c],[$1 $2])" nil (cons 'vec x) (cons 'vec 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.
#C
C
#include <stdio.h>   struct node { char *s; struct node* prev; };   void powerset(char **v, int n, struct node *up) { struct node me;   if (!n) { putchar('['); while (up) { printf(" %s", up->s); up = up->prev; } puts(" ]"); } else { me.s = *v; me.prev = up; powerset(v + 1, n - 1, up); powerset(v + 1, n - 1, &me); } }   int main(int argc, char **argv) { powerset(argv + 1, argc - 1, 0); return 0; }
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
#B
B
isprime(n) { auto p; if(n<2) return(0); if(!(n%2)) return(n==2); p=3; while(n/p>p) { if(!(n%p)) return(0); p=p+2; } return(1); }
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to 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
#Delphi
Delphi
  class APPLICATION   create make   feature   make --Tests the price_adjusted feature. local i: REAL do create price_fraction.initialize from i := 5 until i = 100 loop io.put_string ("Given: ") io.put_real (i / 100) io.put_string ("%TAdjusted:") io.put_real (price_fraction.adjusted_price (i / 100)) io.new_line i := i + 5 end end   price_fraction: PRICE_FRACTION   end  
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
#Free_Pascal
Free Pascal
  Program ProperDivisors;   Uses fgl;   Type TIntegerList = Specialize TfpgList<longint>;   Var list : TintegerList;   Function GetProperDivisors(x : longint): longint; {this function will return the number of proper divisors and put them in the list}   Var i : longint; Begin list.clear; If x = 1 Then {by default 1 has no proper divisors} GetProperDivisors := 0 Else Begin list.add(1); //add 1 as a proper divisor; i := 2; While i * i < x Do Begin If (x Mod i) = 0 Then //found a proper divisor Begin list.add(i); // add divisor list.add(x Div i); // add result End; inc(i); End; If i*i=x Then list.add(i); //make sure to capture the sqrt only once GetProperDivisors := list.count; End; End;   Var i,j,count,most : longint; Begin   list := TIntegerList.Create; For i := 1 To 10 Do Begin write(i:4,' has ', GetProperDivisors(i),' proper divisors:'); For j := 0 To pred(list.count) Do write(list[j]:3); writeln(); End; count := 0; //store highest number of proper divisors most := 0; //store number with highest number of proper divisors For i := 1 To 20000 Do If GetProperDivisors(i) > count Then Begin count := list.count; most := i; End; writeln(most,' has ',count,' proper divisors'); list.free; 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)
#Lua
Lua
items = {} items["aleph"] = 1/5.0 items["beth"] = 1/6.0 items["gimel"] = 1/7.0 items["daleth"] = 1/8.0 items["he"] = 1/9.0 items["waw"] = 1/10.0 items["zayin"] = 1/11.0 items["heth"] = 1759/27720   num_trials = 1000000   samples = {} for item, _ in pairs( items ) do samples[item] = 0 end   math.randomseed( os.time() ) for i = 1, num_trials do z = math.random()   for item, _ in pairs( items ) do if z < items[item] then samples[item] = samples[item] + 1 break; else z = z - items[item] end end end   for item, _ in pairs( items ) do print( item, samples[item]/num_trials, items[item] ) end
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.
#Java
Java
import java.util.PriorityQueue;   class Task implements Comparable<Task> { final int priority; final String name;   public Task(int p, String n) { priority = p; name = n; }   public String toString() { return priority + ", " + name; }   public int compareTo(Task other) { return priority < other.priority ? -1 : priority > other.priority ? 1 : 0; }   public static void main(String[] args) { PriorityQueue<Task> pq = new PriorityQueue<Task>(); pq.add(new Task(3, "Clear drains")); pq.add(new Task(4, "Feed cat")); pq.add(new Task(5, "Make tea")); pq.add(new Task(1, "Solve RC tasks")); pq.add(new Task(2, "Tax return"));   while (!pq.isEmpty()) System.out.println(pq.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.
#Sidef
Sidef
class Circle(x,y,r) { method to_s { "Circle(#{x}, #{y}, #{r})" } }   func solve_apollonius(c, s) {   var(c1, c2, c3) = c...; var(s1, s2, s3) = s...;   var 𝑣11 = (2*c2.x - 2*c1.x); var 𝑣12 = (2*c2.y - 2*c1.y); var 𝑣13 = (c1.x**2 - c2.x**2 + c1.y**2 - c2.y**2 - c1.r**2 + c2.r**2); var 𝑣14 = (2*s2*c2.r - 2*s1*c1.r);   var 𝑣21 = (2*c3.x - 2*c2.x); var 𝑣22 = (2*c3.y - 2*c2.y); var 𝑣23 = (c2.x**2 - c3.x**2 + c2.y**2 - c3.y**2 - c2.r**2 + c3.r**2); var 𝑣24 = (2*s3*c3.r - 2*s2*c2.r);   var 𝑤12 = (𝑣12 / 𝑣11); var 𝑤13 = (𝑣13 / 𝑣11); var 𝑤14 = (𝑣14 / 𝑣11);   var 𝑤22 = (𝑣22/𝑣21 - 𝑤12); var 𝑤23 = (𝑣23/𝑣21 - 𝑤13); var 𝑤24 = (𝑣24/𝑣21 - 𝑤14);   var 𝑃 = (-𝑤23 / 𝑤22); var 𝑄 = (𝑤24 / 𝑤22); var 𝑀 = (-𝑤12*𝑃 - 𝑤13); var 𝑁 = (𝑤14 - 𝑤12*𝑄);   var 𝑎 = (𝑁**2 + 𝑄**2 - 1); var 𝑏 = (2*𝑀*𝑁 - 2*𝑁*c1.x + 2*𝑃*𝑄 - 2*𝑄*c1.y + 2*s1*c1.r); var 𝑐 = (c1.x**2 + 𝑀**2 - 2*𝑀*c1.x + 𝑃**2 + c1.y**2 - 2*𝑃*c1.y - c1.r**2);   var 𝐷 = (𝑏**2 - 4*𝑎*𝑐); var rs = ((-𝑏 - 𝐷.sqrt) / 2*𝑎);   var xs = (𝑀 + 𝑁*rs); var ys = (𝑃 + 𝑄*rs);   Circle(xs, ys, rs); }   var c = [Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)]; say solve_apollonius(c, %n<1 1 1>); say solve_apollonius(c, %n<-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.
#VBA
VBA
Debug.Print Application.Name
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.
#vbscript
vbscript
  Wscript.Echo "FullName:",Wscript.FullName Wscript.Echo "Name:",Wscript.Name Wscript.Echo "Path:",Wscript.Path Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName Wscript.Echo "ScriptName:",Wscript.ScriptName  
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.
#Visual_Basic
Visual Basic
appname = App.EXEName 'appname = "MyVBapp"
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
#Rust
Rust
use std::thread;   fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 { let mut primitive_count = 0; for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { let l = triangle[0] + triangle[1] + triangle[2]; if l > d { continue; } primitive_count += 1 + f1(triangle[0], triangle[1], triangle[2], d); } primitive_count }   fn f2 (a : u64, b : u64, c : u64, d : u64) -> u64 { let mut triplet_count = 0; for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { let l = triangle[0] + triangle[1] + triangle[2]; if l > d { continue; } triplet_count += (d/l) + f2(triangle[0], triangle[1], triangle[2], d); } triplet_count }   fn main () { let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { let mut i = 100; while i <= 100_000_000_000 { println!(" Primitive triples below {} : {}", i, f1(3, 4, 5, i) + 1); i *= 10; } }).unwrap();   let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { let mut i = 100; while i <= 100_000_000_000 { println!(" Triples below {} : {}", i, f2(3, 4, 5, i) + i/12); i *= 10; } }).unwrap();   new_th_1.join().unwrap(); new_th_2.join().unwrap(); }
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.
#Ring
Ring
  for n = 1 to 10 see n + nl if n = 5 exit ok next  
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.
#Ruby
Ruby
if problem exit(1) end   # or if problem abort # equivalent to exit(1) end
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
#Polyglot:PL.2FI_and_PL.2FM
Polyglot:PL/I and PL/M
/* PRIMALITY BY WILSON'S THEOREM */ wilson_100H: procedure options (main);   /* PL/I DEFINITIONS */ %include 'pg.inc'; /* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /* DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE'; DECLARE SADDR LITERALLY '.', BIT LITERALLY 'BYTE'; BDOSF: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; PRCHAR: PROCEDURE( C ); DECLARE C CHARACTER; CALL BDOS( 2, C ); END; PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END; PRNUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; N$STR( W := LAST( N$STR ) ) = '$'; N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL BDOS( 9, .N$STR( W ) ); END PRNUMBER; MODF: PROCEDURE( A, B )ADDRESS; DECLARE ( A, B )ADDRESS; RETURN( A MOD B ); END MODF; /* END LANGUAGE DEFINITIONS */   /* TASK */ DECLARE N BINARY;   ISWILSONPRIME: PROCEDURE( N )returns ( BIT ) ; DECLARE N BINARY; DECLARE ( FMODP, I ) BINARY; FMODP = 1; DO I = 2 TO N - 1; FMODP = MODF( FMODP * I, N ); END; RETURN ( FMODP = N - 1 ); END ISWILSONPRIME ;   DO N = 1 TO 100; IF ISWILSONPRIME( N ) THEN DO; CALL PRCHAR( ' ' ); CALL PRNUMBER( N ); END; END;   EOF: end wilson_100H ;
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
#Python
Python
from math import factorial   def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 )   if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
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 %
#Ruby
Ruby
require "prime"   def prime_conspiracy(m) conspiracy = Hash.new(0) Prime.take(m).map{|n| n%10}.each_cons(2){|a,b| conspiracy[[a,b]] += 1} puts "#{m} first primes. Transitions prime % 10 → next-prime % 10." conspiracy.sort.each do |(a,b),v| puts "%d → %d count:%10d frequency:%7.4f %" % [a, b, v, 100.0*v/m] end end   prime_conspiracy(1_000_000)
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 %
#Rust
Rust
// main.rs mod bit_array; mod prime_sieve;   use prime_sieve::PrimeSieve;   // See https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number fn upper_bound_for_nth_prime(n: usize) -> usize { let x = n as f64; (x * (x.ln() + x.ln().ln())) as usize }   fn compute_transitions(limit: usize) { use std::collections::BTreeMap; let mut transitions = BTreeMap::new(); let mut prev = 2; let mut count = 0; let sieve = PrimeSieve::new(upper_bound_for_nth_prime(limit)); let mut n = 3; while count < limit { if sieve.is_prime(n) { count += 1; let digit = n % 10; let key = (prev, digit); if let Some(v) = transitions.get_mut(&key) { *v += 1; } else { transitions.insert(key, 1); } prev = digit; } n += 2; } println!("First {} prime numbers:", limit); for ((from, to), c) in &transitions { let freq = 100.0 * (*c as f32) / (limit as f32); println!( "{} -> {}: count = {:7}, frequency = {:.2} %", from, to, c, freq ); } }   fn main() { compute_transitions(1000000); println!(); compute_transitions(100000000); }
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
#Common_Lisp
Common Lisp
;;; Recursive algorithm (defun factor (n) "Return a list of factors of N." (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (+ d 1) (+ d 2)) do (cond ((> d max-d) (return (list n))) ; n is prime ((zerop (rem n d)) (return (cons d (factor (truncate n d)))))))))
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | 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.
#E
E
var x := 0 def slot := &x # define "slot" to be x's slot x := 1 # direct assignment; value is now 1 slot.put(2) # via slot object; value is now 2
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.
#EchoLisp
EchoLisp
  (define B (box 42)) → B ;; box reference (unbox B) → 42 ;; box contents   ;; sets new value for box contents (define ( change-by-ref abox avalue) (set-box! abox avalue) )   (change-by-ref B 666) → #[box 666] (unbox B) → 666  
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.
#Forth
Forth
variable myvar \ stores 1 cell fvariable myfvar \ stores 1 floating point number (often 8 bytes) 2variable my2var \ stores 2 cells
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.
#BBC_BASIC
BBC BASIC
DIM x(9), y(9) x() = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 y() = 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0   ORIGIN 100,100 VDU 23,23,2;0;0;0; VDU 5   FOR x = 1 TO 9 GCOL 7 : LINE 100*x,720,100*x,0 GCOL 0 : PLOT 0,-10,-4 : PRINT ; x ; NEXT   FOR y = 20 TO 180 STEP 20 GCOL 7 : LINE 900,4*y,0,4*y GCOL 0 : PLOT 0,-212,20 : PRINT y ; NEXT   LINE 0,0,0,720 LINE 0,0,900,0   GCOL 4 FOR i% = 0 TO 9 IF i%=0 THEN MOVE 100*x(i%),4*y(i%) ELSE DRAW 100*x(i%),4*y(i%) ENDIF NEXT
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h>   #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};   void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i;   *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } }   /* likely we must play with this parameter to make the plot looks better when using different set of data */ #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0)   #define MAXLABLEN 32   #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)   int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy;   char labs[MAXLABLEN+1];   plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1);   /* determines minx, miny, maxx, maxy */ minmax(x, y, &minx, &maxx, &miny, &maxy, NP);   lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);   /* compute x,y-ticstep */ xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV;   pl_flinewidth(0.25);   /* compute scale factors to adjust aspect */ if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; }   pl_erase();   /* a frame... */ pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy));   /* labels and "tics" */ pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); }   /* plot data "point" */ pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); }   pl_flushpl(); pl_closepl(); }
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
#C.23
C#
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } }   public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); }   public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); 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
#Clojure
Clojure
(defn rank [card] (let [[fst _] card] (if (Character/isDigit fst) (Integer/valueOf (str fst)) ({\T 10, \J 11, \Q 12, \K 13, \A 14} fst))))   (defn suit [card] (let [[_ snd] card] (str snd)))   (defn n-of-a-kind [hand n] (not (empty? (filter #(= true %) (map #(>= % n) (vals (frequencies (map rank hand))))))))   (defn ranks-with-ace [hand] (let [ranks (sort (map rank hand))] (if (some #(= 14 %) ranks) (cons 1 ranks) ranks)))   (defn pair? [hand] (n-of-a-kind hand 2))   (defn three-of-a-kind? [hand] (n-of-a-kind hand 3))   (defn four-of-a-kind? [hand] (n-of-a-kind hand 4))   (defn flush? [hand] (not (empty? (filter #(= true %) (map #(>= % 5) (vals (frequencies (map suit hand))))))))   (defn full-house? [hand] (true? (and (some #(= 2 %) (vals (frequencies (map rank hand)))) (some #(= 3 %) (vals (frequencies (map rank hand)))))))   (defn two-pairs? [hand] (or (full-house? hand) (four-of-a-kind? hand) (= 2 (count (filter #(= true %) (map #(>= % 2) (vals (frequencies (map rank hand)))))))))   (defn straight? [hand] (let [hand-a (ranks-with-ace hand) fst (first hand-a) snd (second hand-a)] (or (= (take 5 hand-a) (range fst (+ fst 5))) (= (drop 1 hand-a) (range snd (+ snd 5))))))   (defn straight-flush? [hand] (and (straight? hand) (flush? hand)))   (defn invalid? [hand] (not= 5 (count (set hand))))   (defn check-hand [hand] (cond (invalid? hand) "invalid" (straight-flush? hand) "straight-flush" (four-of-a-kind? hand) "four-of-a-kind" (full-house? hand) "full-house" (flush? hand) "flush" (straight? hand) "straight" (three-of-a-kind? hand) "three-of-a-kind" (two-pairs? hand) "two-pair" (pair? hand) "one-pair"  :else "high-card"))   ; Test examples (def hands [["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"]]) (run! println (map #(str % " : " (check-hand %)) hands))  
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.
#AutoHotkey
AutoHotkey
Loop, 30 Out1 .= PopCount(3 ** (A_Index - 1)) " " Loop, 60 i := A_Index - 1 , PopCount(i) & 0x1 ? Out3 .= i " " : Out2 .= i " " MsgBox, % "3^x:`t" Out1 "`nEvil:`t" Out2 "`nOdious:`t" Out3   PopCount(x) { ;https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation x -= (x >> 1) & 0x5555555555555555 , x := (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333) , x := (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f return (x * 0x0101010101010101) >> 56 }
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
#Delphi
Delphi
  program Polynomial_long_division;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type PPolySolution = ^TPolySolution;   TPolynomio = record private class function Degree(p: TPolynomio): Integer; static; class function ShiftRight(p: TPolynomio; places: Integer): TPolynomio; static; class function PolyMultiply(p: TPolynomio; m: double): TPolynomio; static; class function PolySubtract(p, s: TPolynomio): TPolynomio; static; class function PolyLongDiv(n, d: TPolynomio): PPolySolution; static; function GetSize: Integer; public value: TArray<Double>; class operator RightShift(p: TPolynomio; b: Integer): TPolynomio; class operator Multiply(p: TPolynomio; m: double): TPolynomio; class operator Subtract(p, s: TPolynomio): TPolynomio; class operator Divide(p, s: TPolynomio): PPolySolution; class operator Implicit(a: TArray<Double>): TPolynomio; class operator Implicit(a: TPolynomio): string; procedure Assign(other: TPolynomio); overload; procedure Assign(other: TArray<Double>); overload; property Size: Integer read GetSize; function ToString: string; end;   TPolySolution = record Quotient, Remainder: TPolynomio; constructor Create(q, r: TPolynomio); end;   { TPolynomio }   procedure TPolynomio.Assign(other: TPolynomio); begin Assign(other.value); end;   procedure TPolynomio.Assign(other: TArray<Double>); begin SetLength(value, length(other)); for var i := 0 to High(other) do value[i] := other[i]; end;   class function TPolynomio.Degree(p: TPolynomio): Integer; begin var len := high(p.value);   for var i := len downto 0 do begin if p.value[i] <> 0.0 then exit(i); end; Result := -1; end;   class operator TPolynomio.Divide(p, s: TPolynomio): PPolySolution; begin Result := PolyLongDiv(p, s); end;   function TPolynomio.GetSize: Integer; begin Result := Length(value); end;   class operator TPolynomio.Implicit(a: TPolynomio): string; begin Result := a.toString; end;   class operator TPolynomio.Implicit(a: TArray<Double>): TPolynomio; begin Result.Assign(a); end;   class operator TPolynomio.Multiply(p: TPolynomio; m: double): TPolynomio; begin Result := TPolynomio.PolyMultiply(p, m); end;   class function TPolynomio.PolyLongDiv(n, d: TPolynomio): PPolySolution; var Solution: TPolySolution; begin if length(n.value) <> Length(d.value) then raise Exception.Create('Numerator and denominator vectors must have the same size');   var nd := Degree(n); var dd := Degree(d);   if dd < 0 then raise Exception.Create('Divisor must have at least one one-zero coefficient');   if nd < dd then raise Exception.Create('The degree of the divisor cannot exceed that of the numerator');   var n2, q: TPolynomio; n2.Assign(n); SetLength(q.value, length(n.value));   while nd >= dd do begin var d2 := d shr (nd - dd); q.value[nd - dd] := n2.value[nd] / d2.value[nd]; d2 := d2 * q.value[nd - dd]; n2 := n2 - d2; nd := Degree(n2); end; new(Result); Result^.Create(q, n2); end;   class function TPolynomio.PolyMultiply(p: TPolynomio; m: double): TPolynomio; begin Result.Assign(p); for var i := 0 to High(p.value) do Result.value[i] := p.value[i] * m; end;   class operator TPolynomio.RightShift(p: TPolynomio; b: Integer): TPolynomio; begin Result := TPolynomio.ShiftRight(p, b); end;   class function TPolynomio.ShiftRight(p: TPolynomio; places: Integer): TPolynomio; begin Result.Assign(p); if places <= 0 then exit;   var pd := Degree(p);   Result.Assign(p); for var i := pd downto 0 do begin Result.value[i + places] := Result.value[i]; Result.value[i] := 0.0; end; end;   class operator TPolynomio.Subtract(p, s: TPolynomio): TPolynomio; begin Result := TPolynomio.PolySubtract(p, s); end;   class function TPolynomio.PolySubtract(p, s: TPolynomio): TPolynomio; begin Result.Assign(p); for var i := 0 to High(p.value) do Result.value[i] := p.value[i] - s.value[i]; end;   function TPolynomio.ToString: string; begin Result := ''; var pd := Degree(self); for var i := pd downto 0 do begin var coeff := value[i]; if coeff = 0.0 then Continue; if coeff = 1.0 then begin if i < pd then Result := Result + ' + '; end else begin if coeff = -1 then begin if i < pd then Result := Result + ' - ' else Result := Result + '-'; end else begin if coeff < 0.0 then begin if i < pd then Result := Result + format(' - %.1f', [-coeff]) else Result := Result + format('%.1f', [coeff]); end else begin if i < pd then Result := Result + format(' + %.1f', [coeff]) else Result := Result + format('%.1f', [coeff]); end; end; end; if i > 1 then Result := Result + 'x^' + i.tostring else if i = 1 then Result := Result + 'x'; end; end;   { TPolySolution }   constructor TPolySolution.Create(q, r: TPolynomio); begin Quotient.Assign(q); Remainder.Assign(r); end;   // Just for force implicitty string conversion procedure Writeln(s: string); begin System.Writeln(s); end;   var n, d: TPolynomio; Solution: PPolySolution;   begin n := [-42.0, 0.0, -12.0, 1.0]; d := [-3.0, 1.0, 0.0, 0.0];   Write('Numerator  : '); Writeln(n); Write('Denominator : '); Writeln(d); Writeln('-------------------------------------'); Solution := n / d; Write('Quotient  : '); Writeln(Solution^.Quotient); Write('Remainder  : '); Writeln(Solution^.Remainder); FreeMem(Solution, sizeof(TPolySolution)); Readln; end.
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.
#Go
Go
package main   import ( "fmt" "reflect" )   // interface types provide polymorphism, but not inheritance. type i interface { identify() string }   // "base" type type t float64   // "derived" type. in Go terminology, it is simply a struct with an // anonymous field. fields and methods of anonymous fields however, // can be accessed without additional qualification and so are // "inherited" in a sense. type s struct { t kōan string }   // another type with an "embedded" t field. (t is the *type*, this field // has no *name*.) type r struct { t ch chan int }   // a method on t. this method makes t satisfy interface i. // since a t is embedded in types s and r, they automatically "inherit" // the method. func (x t) identify() string { return "I'm a t!" }   // the same method on s. although s already satisfied i, calls to identify // will now find this method rather than the one defined on t. // in a sense it "overrides" the method of the "base class." func (x s) identify() string { return "I'm an s!" }   func main() { // three variables with different types, initialized from literals. var t1 t = 5 var s1 s = s{6, "one"} var r1 r = r{t: 7}   // variables declared with the same type. initial value is nil. var i1, i2, i3 i fmt.Println("Initial (zero) values of interface variables:") fmt.Println("i1:", i1) fmt.Println("i2:", i2) fmt.Println("i3:", i3)   // in the terminology of the Go language reference, i1, i2, and i3 // still have static type i, but now have different dynamic types. i1, i2, i3 = t1, s1, r1 fmt.Println("\nPolymorphic:") fmt.Println("i1:", i1, "/", i1.identify(), "/", reflect.TypeOf(i1)) fmt.Println("i2:", i2, "/", i2.identify(), "/", reflect.TypeOf(i2)) fmt.Println("i3:", i3, "/", i3.identify(), "/", reflect.TypeOf(i3))   // copy: declare and assign in one step using "short declaration." i1c, i2c, i3c := i1, i2, i3   // modify first set of polymorphic variables. i1, i2, i3 = s{3, "dog"}, r{t: 1}, t(2)   // demonstrate that copies are distinct from first set // and that types are preserved. fmt.Println("\nFirst set now modified:") fmt.Println("i1:", i1, "/", i1.identify(), "/", reflect.TypeOf(i1)) fmt.Println("i2:", i2, "/", i2.identify(), "/", reflect.TypeOf(i2)) fmt.Println("i3:", i3, "/", i3.identify(), "/", reflect.TypeOf(i3))   fmt.Println("\nCopies made before modifications:") fmt.Println("i1c:", i1c, "/", i1c.identify(), "/", reflect.TypeOf(i1c)) fmt.Println("i2c:", i2c, "/", i2c.identify(), "/", reflect.TypeOf(i2c)) fmt.Println("i3c:", i3c, "/", i3c.identify(), "/", reflect.TypeOf(i3c)) }
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
#Phix
Phix
-- -- demo\rosetta\Polyspiral.exw -- =========================== -- -- Space toggles the timer, '+' increases speed (up to 100 FPS), '-' decreases speed -- 'M' toggles "mod360", which inverts the angle every 360/2PI or so, since sin/cos -- accept arguments in radians not degrees (and mod 2*PI changes nothing), producing -- non-true polyspirals, but quite interesting nevertheless. -- with javascript_semantics constant TITLE = "Polyspiral" include pGUI.e Ihandle dlg, canvas, timer cdCanvas cddbuffer, cdcanvas atom incr = 0 bool mod360 = false procedure Polyspiral(atom x1, y1) atom angle = incr integer len = 5 incr += 0.05 if mod360 then incr = mod(incr,360) end if for i=1 to 150 do atom x2 = x1 + cos(angle)*len, y2 = y1 + sin(angle)*len cdCanvasSetForeground(cddbuffer, i*#200+i*#40+i*#10) cdCanvasLine(cddbuffer, x1, y1, x2, y2) {x1, y1} = {x2, y2} len += 3 angle += incr if mod360 then angle = mod(angle,360) end if end for end procedure function redraw_cb(Ihandle /*ih*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) Polyspiral(w/2, h/2) cdCanvasFlush(cddbuffer) integer ms = IupGetInt(timer,"TIME") IupSetStrAttribute(dlg, "TITLE", "%s (timer=%d [%g FPS], angle %3.2f%s)", {TITLE,ms,1000/ms,incr,iff(mod360?" (mod360)":"")}) return IUP_DEFAULT end function function timer_cb(Ihandle /*timer*/) IupUpdate(canvas) return IUP_IGNORE end function function map_cb(Ihandle canvas) cdcanvas = cdCreateCanvas(CD_IUP, canvas) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_GRAY) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c=' ' then IupSetInt(timer,"RUN",not IupGetInt(timer,"RUN")) elsif find(c,"+-") then IupSetInt(timer,"RUN",false) c = -(','-c) -- ('+' ==> +1, '-' ==> -1) IupSetInt(timer,"TIME",max(10,IupGetInt(timer,"TIME")+c*10)) IupSetInt(timer,"RUN",true) elsif upper(c)='M' then mod360 = not mod360 end if return IUP_CONTINUE end function IupOpen() canvas = IupCanvas("RASTERSIZE=640x640") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) timer = IupTimer(Icallback("timer_cb"), 20) dlg = IupDialog(canvas,`TITLE="%s"`, {TITLE}) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if
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.
#Fortran
Fortran
module fitting contains   function polyfit(vx, vy, d) implicit none integer, intent(in) :: d integer, parameter :: dp = selected_real_kind(15, 307) real(dp), dimension(d+1) :: polyfit real(dp), dimension(:), intent(in) :: vx, vy   real(dp), dimension(:,:), allocatable :: X real(dp), dimension(:,:), allocatable :: XT real(dp), dimension(:,:), allocatable :: XTX   integer :: i, j   integer :: n, lda, lwork integer :: info integer, dimension(:), allocatable :: ipiv real(dp), dimension(:), allocatable :: work   n = d+1 lda = n lwork = n   allocate(ipiv(n)) allocate(work(lwork)) allocate(XT(n, size(vx))) allocate(X(size(vx), n)) allocate(XTX(n, n))   ! prepare the matrix do i = 0, d do j = 1, size(vx) X(j, i+1) = vx(j)**i end do end do   XT = transpose(X) XTX = matmul(XT, X)   ! calls to LAPACK subs DGETRF and DGETRI call DGETRF(n, n, XTX, lda, ipiv, info) if ( info /= 0 ) then print *, "problem" return end if call DGETRI(n, XTX, lda, ipiv, work, lwork, info) if ( info /= 0 ) then print *, "problem" return end if   polyfit = matmul( matmul(XTX, XT), vy)   deallocate(ipiv) deallocate(work) deallocate(X) deallocate(XT) deallocate(XTX)   end function   end module
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.
#C.23
C#
  public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list) { return from m in Enumerable.Range(0, 1 << list.Count) select from i in Enumerable.Range(0, list.Count) where (m & (1 << i)) != 0 select list[i]; }   public void PowerSetofColors() { var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green, KnownColor.Blue, KnownColor.Yellow };   var result = GetPowerSet(colors);   Console.Write( string.Join( Environment.NewLine, result.Select(subset => string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray())); }    
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
#BASIC
BASIC
FUNCTION prime% (n!) STATIC i AS INTEGER IF n = 2 THEN prime = 1 ELSEIF n <= 1 OR n MOD 2 = 0 THEN prime = 0 ELSE prime = 1 FOR i = 3 TO INT(SQR(n)) STEP 2 IF n MOD i = 0 THEN prime = 0 EXIT FUNCTION END IF NEXT i END IF END FUNCTION   ' Test and display primes 1 .. 50 DECLARE FUNCTION prime% (n!) FOR n = 1 TO 50 IF prime(n) = 1 THEN PRINT n; NEXT n
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to 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
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make --Tests the price_adjusted feature. local i: REAL do create price_fraction.initialize from i := 5 until i = 100 loop io.put_string ("Given: ") io.put_real (i / 100) io.put_string ("%TAdjusted:") io.put_real (price_fraction.adjusted_price (i / 100)) io.new_line i := i + 5 end end   price_fraction: PRICE_FRACTION   end  
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
#Frink
Frink
  for n = 1 to 10 println["$n\t" + join[" ", properDivisors[n]]]   println[]   d = new dict for n = 1 to 20000 { c = length[properDivisors[n]] d.addToList[c, n] }   most = max[keys[d]] println[d@most + " have $most factors"]   properDivisors[n] := allFactors[n, true, false, true]  
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)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
choices={{"aleph", 1/5},{"beth", 1/6},{"gimel", 1/7},{"daleth", 1/8},{"he", 1/9},{"waw", 1/10},{"zayin", 1/11},{"heth", 1759/27720}}; data=RandomChoice[choices[[All,2]]->choices[[All,1]],10^6];
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)
#MATLAB
MATLAB
function probChoice choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'}; w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]; R = randsample(length(w), 1e6, true, w); T = tabulate(R); fprintf('Value\tCount\tPercent\tGoal\n') for k = 1:size(T, 1) fprintf('%6s\t%.f\t%.2f%%\t%.2f%%\n', ... choices{k}, T(k, 2), T(k, 3), 100*w(k)) end end
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.
#jq
jq
# In the following, pq stands for "priority queue".   # Add an item with the given priority (an integer, # or a string representing an integer) # Input: a pq def pq_add(priority; item): (priority|tostring) as $p | if .priorities|index($p) then if (.[$p] | index(item)) then . else .[$p] += [item] end else .[$p] = [item] | .priorities = (.priorities + [$p] | sort) end ;   # emit [ item, pq ] # Input: a pq def pq_pop: .priorities as $keys | if ($keys|length) == 0 then [ null, . ] else if (.[$keys[0]] | length) == 1 then .priorities = .priorities[1:] else . end | [ (.[$keys[0]])[0], (.[$keys[0]] = .[$keys[0]][1:]) ] end ;   # Emit the item that would be popped, or null if there is none # Input: a pq def pq_peep: .priorities as $keys | if ($keys|length) == 0 then null else (.[$keys[0]])[0] end ;   # Add a bunch of tasks, presented as an array of arrays # Input: a pq def pq_add_tasks(list): reduce list[] as $pair (.; . + pq_add( $pair[0]; $pair[1]) ) ;   # Pop all the tasks, producing a stream # Input: a pq def pq_pop_tasks: pq_pop as $pair | if $pair[0] == null then empty else $pair[0], ( $pair[1] | pq_pop_tasks ) end ;   # Input: a bunch of tasks, presented as an array of arrays def prioritize: . as $list | {} | pq_add_tasks($list) | pq_pop_tasks ;  
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.
#Swift
Swift
import Foundation   struct Circle { let center:[Double]! let radius:Double!   init(center:[Double], radius:Double) { self.center = center self.radius = radius }   func toString() -> String { return "Circle[x=\(center[0]),y=\(center[1]),r=\(radius)]" } }   func solveApollonius(c1:Circle, c2:Circle, c3:Circle, s1:Double, s2:Double, s3:Double) -> Circle {   let x1 = c1.center[0] let y1 = c1.center[1] let r1 = c1.radius let x2 = c2.center[0] let y2 = c2.center[1] let r2 = c2.radius let x3 = c3.center[0] let y3 = c3.center[1] let r3 = c3.radius   let v11 = 2*x2 - 2*x1 let v12 = 2*y2 - 2*y1 let v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 let v14 = 2*s2*r2 - 2*s1*r1   let v21 = 2*x3 - 2*x2 let v22 = 2*y3 - 2*y2 let v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 let v24 = 2*s3*r3 - 2*s2*r2   let w12 = v12/v11 let w13 = v13/v11 let w14 = v14/v11   let w22 = v22/v21-w12 let w23 = v23/v21-w13 let w24 = v24/v21-w14   let P = -w23/w22 let Q = w24/w22 let M = -w12*P-w13 let N = w14 - w12*Q   let a = N*N + Q*Q - 1 let b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 let c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1   let D = b*b-4*a*c   let rs = (-b - sqrt(D)) / (2*a) let xs = M + N * rs let ys = P + Q * rs   return Circle(center: [xs,ys], radius: rs)   }   let c1 = Circle(center: [0,0], radius: 1) let c2 = Circle(center: [4,0], radius: 1) let c3 = Circle(center: [2,4], radius: 2)   println(solveApollonius(c1,c2,c3,1,1,1).toString()) println(solveApollonius(c1,c2,c3,-1,-1,-1).toString())
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.
#Tcl
Tcl
package require TclOO; # Just so we can make a circle class   oo::class create circle { variable X Y Radius constructor {x y radius} { namespace import ::tcl::mathfunc::double set X [double $x]; set Y [double $y]; set Radius [double $radius] } method values {} {list $X $Y $Radius} method format {} { format "Circle\[o=(%.2f,%.2f),r=%.2f\]" $X $Y $Radius } }   proc solveApollonius {c1 c2 c3 {s1 1} {s2 1} {s3 1}} { if {abs($s1)!=1||abs($s2)!=1||abs($s3)!=1} { error "wrong sign; must be 1 or -1" }   lassign [$c1 values] x1 y1 r1 lassign [$c2 values] x2 y2 r2 lassign [$c3 values] x3 y3 r3   set v11 [expr {2*($x2 - $x1)}] set v12 [expr {2*($y2 - $y1)}] set v13 [expr {$x1**2 - $x2**2 + $y1**2 - $y2**2 - $r1**2 + $r2**2}] set v14 [expr {2*($s2*$r2 - $s1*$r1)}]   set v21 [expr {2*($x3 - $x2)}] set v22 [expr {2*($y3 - $y2)}] set v23 [expr {$x2**2 - $x3**2 + $y2**2 - $y3**2 - $r2**2 + $r3**2}] set v24 [expr {2*($s3*$r3 - $s2*$r2)}]   set w12 [expr {$v12 / $v11}] set w13 [expr {$v13 / $v11}] set w14 [expr {$v14 / $v11}]   set w22 [expr {$v22 / $v21 - $w12}] set w23 [expr {$v23 / $v21 - $w13}] set w24 [expr {$v24 / $v21 - $w14}]   set P [expr {-$w23 / $w22}] set Q [expr {$w24 / $w22}] set M [expr {-$w12 * $P - $w13}] set N [expr {$w14 - $w12 * $Q}]   set a [expr {$N**2 + $Q**2 - 1}] set b [expr {2*($M*$N - $N*$x1 + $P*$Q - $Q*$y1 + $s1*$r1)}] set c [expr {($x1-$M)**2 + ($y1-$P)**2 - $r1**2}]   set rs [expr {(-$b - sqrt($b**2 - 4*$a*$c)) / (2*$a)}] set xs [expr {$M + $N*$rs}] set ys [expr {$P + $Q*$rs}]   return [circle new $xs $ys $rs] }
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.
#Wren
Wren
import "os" for Process   System.print("My name is %(Process.allArguments[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.
#x86_Assembly
x86 Assembly
FORMAT=-f elf RUN=./ BIN=scriptname OBJ=scriptname.o   all: test   test: $(BIN) $(RUN)$(BIN)   $(BIN): $(OBJ) ld -o $(BIN) $(OBJ)   $(OBJ): scriptname.asm nasm $(FORMAT) -o $(OBJ) scriptname.asm   clean: -rm $(BIN) -rm $(OBJ)
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
#Scala
Scala
object PythagoreanTriples extends App {   println(" Limit Primatives All")   for {e <- 2 to 7 limit = math.pow(10, e).longValue() } { var primCount, tripCount = 0   def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = { val perim = a + b + c val (a2, b2, c2, c3) = (2 * a, 2 * b, 2 * c, 3 * c) if (limit >= perim) { primCount += 1 tripCount += (limit / perim).toInt parChild(a - b2 + c2, a2 - b + c2, a2 - b2 + c3) parChild(a + b2 + c2, a2 + b + c2, a2 + b2 + c3) parChild(-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3) } }   parChild(BigInt(3), BigInt(4), BigInt(5)) println(f"a + b + c <= ${limit.toFloat}%3.1e $primCount%9d $tripCount%12d") } }
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.
#Run_BASIC
Run BASIC
if whatever then end
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.
#Rust
Rust
fn main() { println!("The program is running"); return; println!("This line won't be printed"); }
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
#Quackery
Quackery
[ 1 swap times [ i 1+ * ] ] is ! ( n --> n )   [ dup 2 < iff [ drop false ] done dup 1 - ! 1+ swap mod 0 = ] is prime ( n --> b )   say "Primes less than 500: " 500 times [ i^ prime if [ i^ echo sp ] ]
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
#Raku
Raku
sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] }   sub is-wilson-prime (Int $p where * > 1) { (($p - 1)! + 1) %% $p }   # Pre initialize factorial routine (not thread safe) 9000!;   # Testing put ' p prime?'; printf("%4d  %s\n", $_, .&is-wilson-prime) for 2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659;   my $wilsons = (2,3,*+2…*).hyper.grep: &is-wilson-prime;   put "\nFirst 120 primes:"; put $wilsons[^120].rotor(20)».fmt('%3d').join: "\n";   put "\n1000th through 1015th primes:"; put $wilsons[999..1014];
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 %
#Scala
Scala
import scala.annotation.tailrec import scala.collection.mutable   object PrimeConspiracy extends App { val limit = 1000000 val sieveTop = 15485863/*one millionth prime*/ + 1 val buckets = Array.ofDim[Int](10, 10) var prevPrime = 2   def sieve(limit: Int) = { val composite = new mutable.BitSet(sieveTop) composite(0) = true composite(1) = true   for (n <- 2 to math.sqrt(limit).toInt) if (!composite(n)) for (k <- n * n until limit by n) composite(k) = true composite }   val notPrime = sieve(sieveTop)   def isPrime(n: Long) = { @tailrec def inner(d: Int, end: Int): Boolean = { if (d > end) true else if (n % d != 0 && n % (d + 2) != 0) inner(d + 6, end) else false }   n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) && inner(5, math.sqrt(n).toInt) }   var primeCount = 1 var n = 3   while (primeCount < limit) { if (!notPrime(n)) { val prime = n buckets(prevPrime % 10)(prime % 10) += 1 prevPrime = prime primeCount += 1 } n += 1 }   for {i <- buckets.indices j <- buckets.head.indices} { val nPrime = buckets(i)(j) if (nPrime != 0) println(f"$i%d -> $j%d : $nPrime%5d ${nPrime / (limit / 100.0)}%2f") }   println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") }
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
#D
D
import std.stdio, std.bigint, std.algorithm, std.traits, std.range;   Unqual!T[] decompose(T)(in T number) pure nothrow in { assert(number > 1); } body { typeof(return) result; Unqual!T n = number;   for (Unqual!T i = 2; n % i == 0; n /= i) result ~= i; for (Unqual!T i = 3; n >= i * i; i += 2) for (; n % i == 0; n /= i) result ~= i;   if (n != 1) result ~= n; return result; }   void main() { writefln("%(%s\n%)", iota(2, 10).map!decompose); decompose(1023 * 1024).writeln; BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln; decompose(16860167264933UL.BigInt * 179951).writeln; decompose(2.BigInt ^^ 100_000).group.writeln; }
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.
#Fortran
Fortran
real, pointer :: pointertoreal
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Cat name As String age As Integer End Type   Type CatInfoType As Sub (As Cat Ptr)   Sub printCatInfo(c As Cat Ptr) Print "Name "; c->name, "Age"; c-> age Print End Sub   ' create Cat object on heap and store a pointer to it Dim c As Cat Ptr = New Cat   ' set fields using the pointer and the "crow's foot" operator c->name = "Fluffy" c->age = 9   ' print them out through a procedure pointer Dim cit As CatInfoType = ProcPtr(printCatInfo) cit(c)   Delete c c = 0   Dim i As Integer = 3 ' create an integer pointer variable and set it to the address of 'i' Dim pi As Integer Ptr = @i   'change the variable through the pointer *pi = 4   'print out the result print "i ="; *pi   'create a reference to the variable i Dim ByRef As Integer j = i   ' set j (and hence i) to a new value j = 5   ' print them out Print "i ="; i, "j ="; j Sleep
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.
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <vector>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f;   //-------------------------------------------------------------------------------------------------- class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; }   void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); }   void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); }   void setPenColor( DWORD c ) { clr = c; createPen(); }   void setPenWidth( int w ) { wid = w; createPen(); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];   ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); }   HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; //-------------------------------------------------------------------------------------------------- class plot { public: plot() { bmp.create( 512, 512 ); }   void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs );   HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); //bmp.saveBitmap( "f:\\rc\\plot.bmp" ); }   private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8];   for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );   wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );   wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );   c += 46; b += 46; }   SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );   bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); }   void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc;   bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );   it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); }   DeleteObject( br ); }   myBitmap bmp; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );   pt.draw( &pairs ); system( "pause" );   return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#C.2B.2B
C++
#include <cstdio> #include <cstdlib>   class Point { protected: int x, y;   public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p.y; } return *this; } int getX() { return x; } int getY() { return y; } void setX(int x0) { x = x0; } void setY(int y0) { y = y0; } virtual void print() { printf("Point\n"); } };   class Circle: public Point { private: int r;   public: Circle(Point p, int r0 = 0) : Point(p), r(r0) {} Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {} virtual ~Circle() {} const Circle& operator=(const Circle &c) { if (this != &c) { x = c.x; y = c.y; r = c.r; } return *this; } int getR() { return r; } void setR(int r0) { r = r0; } virtual void print() { printf("Circle\n"); } };   int main() { Point *p = new Point(); Point *c = new Circle(); p->print(); c->print(); delete p; delete c;   return EXIT_SUCCESS; }
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
#D
D
import std.stdio, std.string, std.algorithm, std.range;   string analyzeHand(in string inHand) pure /*nothrow @safe*/ { enum handLen = 5; static immutable face = "A23456789TJQK", suit = "SHCD"; static immutable errorMessage = "invalid hand.";   /*immutable*/ const hand = inHand.toUpper.split.sort().release; if (hand.length != handLen) return errorMessage; if (hand.uniq.walkLength != handLen) return errorMessage ~ " Duplicated cards.";   ubyte[face.length] faceCount; ubyte[suit.length] suitCount; foreach (immutable card; hand) { if (card.length != 2) return errorMessage; immutable n = face.countUntil(card[0]); immutable l = suit.countUntil(card[1]); if (n < 0 || l < 0) return errorMessage; faceCount[n]++; suitCount[l]++; }   return analyzeHandHelper(faceCount, suitCount); }   private string analyzeHandHelper(const ref ubyte[13] faceCount, const ref ubyte[4] suitCount) pure nothrow @safe @nogc { bool p1, p2, t, f, fl, st;   foreach (immutable fc; faceCount) switch (fc) { case 2: (p1 ? p2 : p1) = true; break; case 3: t = true; break; case 4: f = true; break; default: // Ignore. }   foreach (immutable sc; suitCount) if (sc == 5) { fl = true; break; }   if (!p1 && !p2 && !t && !f) { uint s = 0; foreach (immutable fc; faceCount) { if (fc) s++; else s = 0; if (s == 5) break; }   st = (s == 5) || (s == 4 && faceCount[0] && !faceCount[1]); }   if (st && fl) return "straight-flush"; else if (f) return "four-of-a-kind"; else if (p1 && t) return "full-house"; else if (fl) return "flush"; else if (st) return "straight"; else if (t) return "three-of-a-kind"; else if (p1 && p2) return "two-pair"; else if (p1) return "one-pair"; else return "high-card"; }   void main() { // S = Spades, H = Hearts, C = Clubs, D = Diamonds. foreach (immutable 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"]) writeln(hand, ": ", hand.analyzeHand); }
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.
#AWK
AWK
  # syntax: GAWK -f POPULATION_COUNT.AWK # converted from VBSCRIPT BEGIN { nmax = 30 b = 3 n = 0 bb = 1 for (i=1; i<=nmax; i++) { list = list pop_count(bb) " " bb *= b } printf("%s^n: %s\n",b,list) for (j=0; j<=1; j++) { c = (j == 0) ? "evil" : "odious" i = n = 0 list = "" while (n < nmax) { if (pop_count(i) % 2 == j) { n++ list = list i " " } i++ } printf("%s: %s\n",c,list) } exit(0) } function pop_count(xx, xq,xr,y) { while (xx > 0) { xq = int(xx / 2) xr = xx - xq * 2 if (xr == 1) { y++ } xx = xq } return(y) }