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/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.
| #Yabasic | Yabasic | ;assumes this runs inline
org &1000 ;program start
main:
call GetInput ;unimplemented input get routine, returns key press in accumulator
cp 'Y' ;compare to ascii capital Y
ret z ;return to BASIC if equal
jp main ;loop back to main |
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
| #Forth | Forth | : decomp ( n -- )
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or \ next odd number
else -rot nip dup .
then
repeat
drop . ; |
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.
| #Racket | Racket |
#lang racket
(define (inc! b) (set-box! b (add1 (unbox b))))
(define b (box 0))
(inc! b)
(inc! b)
(inc! b)
(unbox b) ; => 3
|
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
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.
| #Raku | Raku | my $foo = 42; # place a reference to 42 in $foo's item container
$foo++; # deref $foo name, then increment the container's contents to 43
$foo.say; # deref $foo name, then $foo's container, and call a method on 43.
$foo := 42; # bind a direct ref to 42
$foo++; # ERROR, cannot modify immutable value
my @bar = 1,2,3; # deref @bar name to array container, then set its values
@bar»++; # deref @bar name to array container, then increment each value with a hyper
@bar.say; # deref @bar name to array container, then call say on that, giving 2 3 4
@bar := (1,2,3); # bind name directly to a List
@bar»++; # ERROR, parcels are not mutable |
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.
| #REXX | REXX | /* Using ADDR to get memory address, and PEEKC / POKE. There is also PEEK for numeric values. */
data _null_;
length a b c $4;
adr_a=addr(a);
adr_b=addr(b);
adr_c=addr(c);
a="ABCD";
b="EFGH";
c="IJKL";
b=peekc(adr_a,1);
call poke(b,adr_c,1);
put a b c;
run; |
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.
| #J | J | require 'plot'
X=: i.10
Y=: 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0
'dot; pensize 2.4' plot X;Y |
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.
| #Java | Java | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static double max(double[] t) {
double maximum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
}
}
return maximum;
}
public static double min(double[] t) {
double minimum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] < minimum) {
minimum = t[i];
}
}
return minimum;
}
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.black);
int x0 = 70;
int y0 = 10;
int xm = 670;
int ym = 410;
int xspan = xm - x0;
int yspan = ym - y0;
double xmax = max(xi);
double xmin = min(xi);
double ymax = max(yi);
double ymin = min(yi);
g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0, ym, xm, ym));
g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0, ym, x0, y0));
for (int j = 0; j < 5; j++) {
int interv = 4;
g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);
g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),
ym - j * yspan / interv + y0 - 5);
g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));
g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));
}
for (int i = 0; i < xi.length; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
g2.drawString("o", x0 + f - 3, h + 14);
}
for (int i = 0; i < xi.length - 1; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));
g2.draw(new double+java.sun.com&btnI=I%27m%20Feeling%20Lucky">Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));
}
}
public static void main(String args[]) {
JFrame f = new JFrame("ShapesDemo2D");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};
JApplet applet = new Plot2d(r, t);
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(720, 480));
f.show();
}
}
|
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
| #Go | Go | package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer // polymorphic variable
i = newPoint(3, 4) // assign one type
i.print() // call polymorphic function
i = newCircle(5, 12, 13) // assign different type to same variable
i.print() // same call accesses different method now.
}
// Above is a sort of polymorphism: both types implement the printer
// interface. The print function can be called through a variable
// of type printer, without knowing the underlying type.
// Below is other stuff the task asks for. Note that none of it is
// needed for cases as simple as this task, and it is not idomatic
// to write any of these functions in these simple cases.
// Accessors are not idiomatic in Go. Instead, simply access struct
// fields directly. To allow access from another package, you "export"
// the field by capitalizing the field name.
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
// Copy constructors, not idiomatic. Structs are assignable so
// you can simply declare and assign them as needed.
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
// Assignment methods, not idiomatic. Just use the assignment operator.
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
// Constructors are idiomatic only when construction involves something
// more than just assigning initial values. By default, structs
// are created as "zero values," that is, with all fields zero,
// empty, or nil. The struct literal synax allows for all fields to
// initialized, or for any subset of fields to be initialized by name.
// These feautures take the place of trivial default constructors.
// When additional initialization is needed, it is conventional to
// name a function New, New<Type>, or within a package, new<Type>
// as shown here.
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
// Destructors are never used in Go. Objects are garbage collected. |
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
| #Perl | Perl |
use strict;
use warnings;
use utf8;
use feature 'say';
use open qw<:encoding(utf-8) :std>;
package Hand {
sub describe {
my $str = pop;
my $hand = init($str);
return "$str: INVALID" if !$hand;
return analyze($hand);
}
sub init {
(my $str = lc shift) =~ tr/234567891jqka♥♦♣♠//cd;
return if $str !~ m/\A (?: [234567891jqka] [♥♦♣♠] ){5} \z/x;
for (my ($i, $cnt) = (0, 0); $i < 10; $i += 2, $cnt = 0) {
my $try = substr $str, $i, 2;
++$cnt while $str =~ m/$try/g;
return if $cnt > 1;
}
my $suits = $str =~ tr/234567891jqka//dr;
my $ranks = $str =~ tr/♥♦♣♠//dr;
return {
hand => $str,
suits => $suits,
ranks => $ranks,
};
}
sub analyze {
my $hand = shift;
my @ranks = split //, $hand->{ranks};
my %cards;
for (@ranks) {
$_ = 10, next if $_ eq '1';
$_ = 11, next if $_ eq 'j';
$_ = 12, next if $_ eq 'q';
$_ = 13, next if $_ eq 'k';
$_ = 14, next if $_ eq 'a';
} continue {
++$cards{ $_ };
}
my $kicker = 0;
my (@pairs, $set, $quads, $straight, $flush);
while (my ($card, $count) = each %cards) {
if ($count == 1) {
$kicker = $card if $kicker < $card;
}
elsif ($count == 2) {
push @pairs, $card;
}
elsif ($count == 3) {
$set = $card;
}
elsif ($count == 4) {
$quads = $card;
}
else {
die "Five of a kind? Cheater!\n";
}
}
$flush = 1 if $hand->{suits} =~ m/\A (.) \1 {4}/x;
$straight = check_straight(@ranks);
return get_high($kicker, \@pairs, $set, $quads, $straight, $flush,);
}
sub check_straight {
my $sequence = join ' ', sort { $a <=> $b } @_;
return 1 if index('2 3 4 5 6 7 8 9 10 11 12 13 14', $sequence) != -1;
return 'wheel' if index('2 3 4 5 14 6 7 8 9 10 11 12 13', $sequence) == 0;
return undef;
}
sub get_high {
my ($kicker, $pairs, $set, $quads, $straight, $flush) = @_;
$kicker = to_s($kicker, 's');
return 'straight-flush: Royal Flush!'
if $straight && $flush && $kicker eq 'Ace' && $straight ne 'wheel';
return "straight-flush: Steel Wheel!"
if $straight && $flush && $straight eq 'wheel';
return "straight-flush: $kicker high"
if $straight && $flush;
return 'four-of-a-kind: '. to_s($quads, 'p')
if $quads;
return 'full-house: '. to_s($set, 'p') .' full of '. to_s($pairs->[0], 'p')
if $set && @$pairs;
return "flush: $kicker high"
if $flush;
return 'straight: Wheel!'
if $straight && $straight eq 'wheel';
return "straight: $kicker high"
if $straight;
return 'three-of-a-kind: '. to_s($set, 'p')
if $set;
return 'two-pairs: '. to_s($pairs->[0], 'p') .' and '. to_s($pairs->[1], 'p')
if @$pairs == 2;
return 'one-pair: '. to_s($pairs->[0], 'p')
if @$pairs == 1;
return "high-card: $kicker";
}
my %to_str = (
2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six',
7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten', 11 => 'Jack',
12 => 'Queen', 13 => 'King', 14 => 'Ace',
);
my %to_str_diffs = (2 => 'Deuces', 6 => 'Sixes',);
sub to_s {
my ($num, $verb) = @_;
# verb is 'singular' or 'plural' (or 's' or 'p')
if ($verb =~ m/\A p/xi) {
return $to_str_diffs{ $num } if $to_str_diffs{ $num };
return $to_str{ $num } .'s';
}
return $to_str{ $num };
}
}
my @cards = (
'10♥ j♥ q♥ k♥ a♥',
'2♥ 3♥ 4♥ 5♥ a♥',
'2♥ 2♣ 2♦ 3♣ 2♠',
'10♥ K♥ K♦ K♣ 10♦',
'q♣ 10♣ 7♣ 6♣ 3♣',
'5♣ 10♣ 7♣ 6♣ 4♣',
'9♥ 10♥ q♥ k♥ j♣',
'a♥ a♣ 3♣ 4♣ 5♦',
'2♥ 2♦ 2♣ k♣ q♦',
'6♥ 7♥ 6♦ j♣ j♦',
'2♥ 6♥ 2♦ 3♣ 3♦',
'7♥ 7♠ k♠ 3♦ 10♠',
'4♥ 4♠ k♠ 2♦ 10♠',
'2♥ 5♥ j♦ 8♣ 9♠',
'2♥ 5♥ 7♦ 8♣ 9♠',
'a♥ a♥ 3♣ 4♣ 5♦', # INVALID: duplicate aces
);
say Hand::describe($_) for @cards;
|
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.
| #Delphi | Delphi |
program Population_count;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Math;
function PopulationCount(AInt: UInt64): Integer;
begin
Result := 0;
repeat
inc(Result, (AInt and 1));
AInt := AInt div 2;
until (AInt = 0);
end;
var
i, count: Integer;
n: Double;
popCount: Integer;
begin
Writeln('Population Counts:'#10);
Write('3^n : ');
for i := 0 to 30 do
begin
n := Math.Power(3, i);
popCount := PopulationCount(round(n));
Write(Format('%d ', [popCount]));
end;
Writeln(#10#10'Evil: ');
count := 0;
i := 0;
while (count < 30) do
begin
popCount := PopulationCount(i);
if not Odd(popCount) then
begin
inc(count);
Write(Format('%d ', [i]));
end;
inc(i);
end;
Writeln(#10#10'Odious: ');
count := 0;
i := 0;
while (count < 30) do
begin
popCount := PopulationCount(i);
if Odd(popCount) then
begin
inc(count);
Write(Format('%d ', [i]));
end;
inc(i);
end;
readln;
end.
|
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
| #Maple | Maple |
> p := randpoly( x ); # pick a random polynomial in x
5 4 3 2
p := -56 - 7 x + 22 x - 55 x - 94 x + 87 x
> rem( p, x^2 + 2, x, 'q' ); # remainder
220 + 169 x
> q; # quotient
3 2
-7 x + 22 x - 41 x - 138
> quo( p, x^2 + 2, x, 'r' ); # quotient
3 2
-7 x + 22 x - 41 x - 138
> r; # remainder
220 + 169 x
> expand( (x^2+2)*q + r - p ); # check
0
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | PolynomialQuotientRemainder[x^3-12 x^2-42,x-3,x] |
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.
| #Sidef | Sidef | class T(value) {
method display {
say value;
}
}
class S(value) < T {
method display {
say value;
}
}
var obj1 = T("T");
var obj2 = S("S");
var obj3 = obj2.dclone; # make a deep clone of obj2
obj1.value = "foo"; # change the value of obj1
obj2.value = "bar"; # change the value of obj2
obj1.display; # prints "foo"
obj2.display; # prints "bar"
obj3.display; # prints "S" |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be 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.
| #Slate | Slate | define: #T &parents: {Cloneable}.
define: #S &parents: {Cloneable}.
define: #obj1 -> T clone.
define: #obj2 -> S clone.
obj1 printName.
obj2 printName. |
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.
| #Swift | Swift | class T {
required init() { } // constructor used in polymorphic initialization must be "required"
func identify() {
println("I am a genuine T")
}
func copy() -> T {
let newObj : T = self.dynamicType() // call an appropriate constructor here
// then copy data into newObj as appropriate here
// make sure to use "self.dynamicType(...)" and
// not "T(...)" to make it polymorphic
return newObj
}
}
class S : T {
override func identify() {
println("I am an S")
}
}
let original : T = S()
let another : T = original.copy()
println(original === another) // prints "false" (i.e. they are different objects)
another.identify() // prints "I am an S" |
http://rosettacode.org/wiki/Polynomial_regression | Polynomial regression | Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | data = Transpose@{Range[0, 10], {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}};
Fit[data, {1, x, x^2}, x] |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or 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.
| #FreeBASIC | FreeBASIC | Function ConjuntoPotencia(set() As String) As String
If Ubound(set,1) > 31 Then Print "Set demasiado grande para representarlo como un entero" : Exit Function
If Ubound(set,1) < 0 Then Print "{}": Exit Function ' Set vacío
Dim As Integer i, j
Dim As String s = "{"
For i = Lbound(set) To (2 Shl Ubound(set,1)) - 1
s += "{"
For j = Lbound(set) To Ubound(set,1)
If i And (1 Shl j) Then s += set(j) + ","
Next j
If Right(s,1) = "," Then s = Left(s,Len(s)-1)
s += "},"
Next i
Return Left(s,Len(s)-1) + "}"
End Function
Print "El power set de [1, 2, 3, 4] comprende:"
Dim As String set(3) = {"1", "2", "3", "4"}
Print ConjuntoPotencia(set())
Print !"\nEl power set de [] comprende:"
Dim As String set0()
Print ConjuntoPotencia(set0())
Print "El power set de [[]] comprende:"
Dim As String set1(0) = {""}
Print ConjuntoPotencia(set1())
Sleep |
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
| #CLU | CLU | isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
prime = proc (n: int) returns (bool)
if n<=2 then return(n=2) end
if n//2=0 then return(false) end
for d: int in int$from_to_by(3,isqrt(n),2) do
if n//d=0 then return(false) end
end
return(true)
end prime
start_up = proc ()
po: stream := stream$primary_input()
for i: int in int$from_to(1,100) do
if prime(i) then
stream$puts(po, int$unparse(i) || " ")
end
end
end start_up |
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
| #Inform_7 | Inform 7 | Home is a room.
Price is a kind of value. 0.99 specifies a price.
Table of Price Standardization
upper bound replacement
0.06 0.10
0.11 0.18
0.16 0.26
0.21 0.32
0.26 0.38
0.31 0.44
0.36 0.50
0.41 0.54
0.46 0.58
0.51 0.62
0.56 0.66
0.61 0.70
0.66 0.74
0.71 0.78
0.76 0.82
0.81 0.86
0.86 0.90
0.91 0.94
0.96 0.98
1.01 1.00
To decide which price is the standardized value of (P - price):
repeat with N running from 1 to the number of rows in the Table of Price Standardization:
choose row N in the Table of Price Standardization;
if P is less than the upper bound entry, decide on the replacement entry.
When play begins:
repeat with N running from 1 to 5:
let P be a random price between 0.00 and 1.00;
say "[P] -> [standardized value of P].";
end the story. |
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
| #J | J | le =: -0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0
out =: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1
priceFraction =: out {~ le I. - |
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
| #Nim | Nim | import strformat
proc properDivisors(n: int) =
var count = 0
for i in 1..<n:
if n mod i == 0:
inc count
write(stdout, fmt"{i} ")
write(stdout, "\n")
proc countProperDivisors(n: int): int =
var nn = n
var prod = 1
var count = 0
while nn mod 2 == 0:
inc count
nn = nn div 2
prod *= (1 + count)
for i in countup(3, n, 2):
count = 0
while nn mod i == 0:
inc count
nn = nn div i
prod *= (1 + count)
if nn > 2:
prod *= 2
prod - 1
for i in 1..10:
write(stdout, fmt"{i:2}: ")
properDivisors(i)
var max = 0
var maxI = 1
for i in 1..20000:
var v = countProperDivisors(i)
if v >= max:
max = v
maxI = i
echo fmt"{maxI} with {max} divisors" |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Rust | Rust | extern crate rand;
use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice};
use rand::{weak_rng, Rng};
const DATA: [(&str, f64); 8] = [
("aleph", 1.0 / 5.0),
("beth", 1.0 / 6.0),
("gimel", 1.0 / 7.0),
("daleth", 1.0 / 8.0),
("he", 1.0 / 9.0),
("waw", 1.0 / 10.0),
("zayin", 1.0 / 11.0),
("heth", 1759.0 / 27720.0),
];
const SAMPLES: usize = 1_000_000;
/// Generate a mapping to be used by `WeightedChoice`
fn gen_mapping() -> Vec<Weighted<usize>> {
DATA.iter()
.enumerate()
.map(|(i, &(_, p))| Weighted {
// `WeightedChoice` requires `u32` weights rather than raw probabilities. For each
// probability, we convert it to a `u32` weight, and associate it with an index. We
// multiply by a constant because small numbers such as 0.2 when casted to `u32`
// become `0`. This conversion decreases the accuracy of the mapping, which is why we
// provide an implementation which uses `f64`s for the best accuracy.
weight: (p * 1_000_000_000.0) as u32,
item: i,
})
.collect()
}
/// Generate a mapping of the raw probabilities
fn gen_mapping_float() -> Vec<f64> {
// This does the work of `WeightedChoice::new`, splitting a number into various ranges. The
// `item` of `Weighted` is represented here merely by the probability's position in the `Vec`.
let mut running_total = 0.0;
DATA.iter()
.map(|&(_, p)| {
running_total += p;
running_total
})
.collect()
}
/// An implementation of `WeightedChoice` which uses probabilities rather than weights. Refer to
/// the `WeightedChoice` source for serious usage.
struct WcFloat {
mapping: Vec<f64>,
}
impl WcFloat {
fn new(mapping: &[f64]) -> Self {
Self {
mapping: mapping.to_vec(),
}
}
// This is roughly the same logic as `WeightedChoice::ind_sample` (though is likely slower)
fn search(&self, sample_prob: f64) -> usize {
let idx = self.mapping
.binary_search_by(|p| p.partial_cmp(&sample_prob).unwrap());
match idx {
Ok(i) | Err(i) => i,
}
}
}
impl IndependentSample<usize> for WcFloat {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> usize {
// Because we know the total is exactly 1.0, we can merely use a raw float value.
// Otherwise caching `Range::new(0.0, running_total)` and sampling with
// `range.ind_sample(&mut rng)` is recommended.
let sample_prob = rng.next_f64();
self.search(sample_prob)
}
}
impl Sample<usize> for WcFloat {
fn sample<R: Rng>(&mut self, rng: &mut R) -> usize {
self.ind_sample(rng)
}
}
fn take_samples<R: Rng, T>(rng: &mut R, wc: &T) -> [usize; 8]
where
T: IndependentSample<usize>,
{
let mut counts = [0; 8];
for _ in 0..SAMPLES {
let sample = wc.ind_sample(rng);
counts[sample] += 1;
}
counts
}
fn print_mapping(counts: &[usize]) {
println!("Item | Expected | Actual ");
println!("-------+----------+----------");
for (&(name, expected), &count) in DATA.iter().zip(counts.iter()) {
let real = count as f64 / SAMPLES as f64;
println!("{:6} | {:.6} | {:.6}", name, expected, real);
}
}
fn main() {
let mut rng = weak_rng();
println!(" ~~~ U32 METHOD ~~~");
let mut mapping = gen_mapping();
let wc = WeightedChoice::new(&mut mapping);
let counts = take_samples(&mut rng, &wc);
print_mapping(&counts);
println!();
println!(" ~~~ FLOAT METHOD ~~~");
// initialize the float version of `WeightedChoice`
let mapping = gen_mapping_float();
let wc = WcFloat::new(&mapping);
let counts = take_samples(&mut rng, &wc);
print_mapping(&counts);
} |
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)
| #Scala | Scala | object ProbabilisticChoice extends App {
import scala.collection.mutable.LinkedHashMap
def weightedProb[A](prob: LinkedHashMap[A,Double]): A = {
require(prob.forall{case (_, p) => p > 0 && p < 1})
assume(prob.values.sum == 1)
def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A = todo.next match {
case (s, i) if rand < (accum + i) => s
case (_, i) => weighted(todo, rand, accum + i)
}
weighted(prob.toIterator, scala.util.Random.nextDouble)
}
def weightedFreq[A](freq: LinkedHashMap[A,Int]): A = {
require(freq.forall{case (_, f) => f >= 0})
require(freq.values.sum > 0)
def weighted(todo: Iterator[(A,Int)], rand: Int, accum: Int = 0): A = todo.next match {
case (s, i) if rand < (accum + i) => s
case (_, i) => weighted(todo, rand, accum + i)
}
weighted(freq.toIterator, scala.util.Random.nextInt(freq.values.sum))
}
// Tests:
val probabilities = LinkedHashMap(
'aleph -> 1.0/5,
'beth -> 1.0/6,
'gimel -> 1.0/7,
'daleth -> 1.0/8,
'he -> 1.0/9,
'waw -> 1.0/10,
'zayin -> 1.0/11,
'heth -> 1759.0/27720
)
val frequencies = LinkedHashMap(
'aleph -> 200,
'beth -> 167,
'gimel -> 143,
'daleth -> 125,
'he -> 111,
'waw -> 100,
'zayin -> 91,
'heth -> 63
)
def check[A](original: LinkedHashMap[A,Double], results: Seq[A]) {
val freq = results.groupBy(x => x).mapValues(_.size.toDouble/results.size)
original.foreach{case (k, v) =>
val a = v/original.values.sum
val b = freq(k)
val c = if (Math.abs(a - b) < 0.001) "ok" else "**"
println(f"$k%10s $a%.4f $b%.4f $c")
}
println(" "*10 + f" ${1}%.4f ${freq.values.sum}%.4f")
}
println("Checking weighted probabilities:")
check(probabilities, for (i <- 1 to 1000000) yield weightedProb(probabilities))
println
println("Checking weighted frequencies:")
check(frequencies.map{case (a, b) => a -> b.toDouble}, for (i <- 1 to 1000000) yield weightedFreq(frequencies))
} |
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.
| #Perl | Perl | use 5.10.0;
use strict;
use Heap::Priority;
my $h = new Heap::Priority;
$h->highest_first(); # higher or lower number is more important
$h->add(@$_) for ["Clear drains", 3],
["Feed cat", 4],
["Make tea", 5],
["Solve RC tasks", 1],
["Tax return", 2];
say while ($_ = $h->pop); |
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.
| #Z80_Assembly | Z80 Assembly | ;assumes this runs inline
org &1000 ;program start
main:
call GetInput ;unimplemented input get routine, returns key press in accumulator
cp 'Y' ;compare to ascii capital Y
ret z ;return to BASIC if equal
jp main ;loop back to main |
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.
| #zkl | zkl | if (die) System.exit();
if (die) System.exit(1);
if (die) System.exit("dumping core"); |
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
| #Fortran | Fortran | module PrimeDecompose
implicit none
integer, parameter :: huge = selected_int_kind(18)
! => integer(8) ... more fails on my 32 bit machine with gfortran(gcc) 4.3.2
contains
subroutine find_factors(n, d)
integer(huge), intent(in) :: n
integer, dimension(:), intent(out) :: d
integer(huge) :: div, next, rest
integer :: i
i = 1
div = 2; next = 3; rest = n
do while ( rest /= 1 )
do while ( mod(rest, div) == 0 )
d(i) = div
i = i + 1
rest = rest / div
end do
div = next
next = next + 2
end do
end subroutine find_factors
end module PrimeDecompose |
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.
| #SAS | SAS | /* Using ADDR to get memory address, and PEEKC / POKE. There is also PEEK for numeric values. */
data _null_;
length a b c $4;
adr_a=addr(a);
adr_b=addr(b);
adr_c=addr(c);
a="ABCD";
b="EFGH";
c="IJKL";
b=peekc(adr_a,1);
call poke(b,adr_c,1);
put a b c;
run; |
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.
| #Scala | Scala | #!/usr/local/bin/shale
aVariable var // Create aVariable
aVariable 0 = // Regular assignment.
aVariable "aVariable = %d\n" printf // Print aVariable
aPointer var // Create aPointer
aPointer aVariable &= // Pointer asssignment, aPointer now points to aVariable
aPointer-> "aPointer-> = %d\n" printf // Pointer dereference. Print what aPointer points to
aPointer-> 3.141593 = // This will change the value of aVariable
aVariable "aVariable = %f\n" printf // Print aVariable
aPPointer var // Create aPPointer
aPPointer aPointer &= // aPPointer is a pointer to a pointer
aPPointer->-> "aPPointer->-> = %f\n" printf
aPPointer->-> "abc123" = // This will change the value of aVariable
aVariable "aVariable = %s\n" printf // Print aVariable
// Shale pointers can point to any Shale object, like numbers, strings, variables
// and code fragments. |
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.
| #Shale | Shale | #!/usr/local/bin/shale
aVariable var // Create aVariable
aVariable 0 = // Regular assignment.
aVariable "aVariable = %d\n" printf // Print aVariable
aPointer var // Create aPointer
aPointer aVariable &= // Pointer asssignment, aPointer now points to aVariable
aPointer-> "aPointer-> = %d\n" printf // Pointer dereference. Print what aPointer points to
aPointer-> 3.141593 = // This will change the value of aVariable
aVariable "aVariable = %f\n" printf // Print aVariable
aPPointer var // Create aPPointer
aPPointer aPointer &= // aPPointer is a pointer to a pointer
aPPointer->-> "aPPointer->-> = %f\n" printf
aPPointer->-> "abc123" = // This will change the value of aVariable
aVariable "aVariable = %s\n" printf // Print aVariable
// Shale pointers can point to any Shale object, like numbers, strings, variables
// and code fragments. |
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.
| #jq | jq | jq -n -M -r -f plot.jq | R CMD BATCH plot.R |
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.
| #Julia | Julia | using Plots
plotlyjs()
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]
p = scatter(x, y)
savefig(p, "/tmp/testplot.png") |
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
| #Golo | Golo | #!/usr/bin/env golosh
----
This module demonstrates Golo's version of polymorphism.
----
module Polymorphism
# Each struct automatically gets a constructor and also accessor and assignment methods for each field.
# For example, the constructor for Point is Point(1, 2)
# and the accessor methods are x() and y()
# and the assignment methods are x(10) and y(10).
struct Point = { x, y }
struct Circle = { x, y, r }
# Augmentations are the way to give your struct methods.
# They're like extension methods in C# or Xtend.
augment Point {
function print = |this| { println("Point " + this: x() + " " + this: y()) }
}
augment Circle {
function print = |this| { println("Circle " + this: x() + " " + this: y() + " " + this: r()) }
}
# You can define functions with the same name as your struct that work
# basically like constructors.
----
A contructor with no arguments that initializes all fields to 0
----
function Point = -> Point(0, 0)
----
This is the copy constructor when the argument is another point
----
function Point = |x| -> match {
when x oftype Point.class then Point(x: x(), x: y())
otherwise Point(x, 0)
}
----
A contructor with no arguments that initializes all fields to 0
----
function Circle = -> Circle(0, 0, 0)
----
This is the copy constructor when the argument is another circle
----
function Circle = |x| -> match {
when x oftype Circle.class then Circle(x: x(), x: y(), x: r())
otherwise Circle(x, 0, 0)
}
----
This one initializes the radius to zero
----
function Circle = |x, y| -> Circle(x, y, 0)
function main = |args| {
let p = Point(10, 20)
let c = Circle(10, 20, 30)
let shapes = vector[
Point(), Point(1), Point(1, 2), Point(p),
Circle(), Circle(1), Circle(1, 2), Circle(1, 2, 3), Circle(c)
]
foreach shape in shapes {
shape: print()
}
} |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Groovy | Groovy | @Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true)
class Point {
Point(Point p) { x = p.x; y = p.y }
void print() { println toString() }
Number x
Number y
}
@Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true, includeSuper = true)
class Circle extends Point {
Circle(Circle c) { super(c); r = c.r }
void print() { println toString() }
Number r
} |
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
| #Phix | Phix | with javascript_semantics
function poker(string hand)
hand = substitute(hand,"10","t")
sequence cards = split(hand)
if length(cards)!=5 then return "invalid hand" end if
sequence ranks = repeat(0,13),
suits = repeat(0,4)
integer jokers = 0
for i=1 to length(cards) do
sequence ci = utf8_to_utf32(cards[i])
if ci="joker" then
jokers += 1
if jokers>2 then return "invalid hand" end if
else
if length(ci)!=2 then return "invalid hand" end if
integer rank = find(lower(ci[1]),"23456789tjqka")
integer suit = find(ci[2],utf8_to_utf32("♥♣♦♠"))
if rank=0 or suit=0 then return "invalid hand" end if
ranks[rank] += 1
suits[suit] += 1
end if
end for
integer straight = match({1,1,1,1,1},ranks)
if not straight then
straight = sort(deep_copy(ranks))[$]=1 and match({0,0,0,0,0,0,0,0},ranks)
end if
integer _flush = (max(suits)+jokers = 5)
integer _pairs = max(ranks)+jokers
integer pair = find(2,ranks)
integer full_house = _pairs=3 and pair and (jokers=0 or find(2,ranks,pair+1))
integer two_pair = find(2,ranks,pair+1)
integer high_card = rfind(1,sq_ne(ranks,0))+1
if jokers and _pairs=jokers+1 then
straight = 1
integer k = find(1,ranks), j = jokers
for l=k to min(k+5-j,13) do
if ranks[l]=0 then
if j=0 then
straight = 0
exit
end if
j -= 1
end if
end for
if straight and j then
high_card = min(high_card+j,14)
end if
elsif straight and ranks[1]!=0 then
high_card = find(0,ranks)
end if
if _pairs=5 then return {10,"five of a kind", find(5-jokers,ranks)+1} end if
if straight and _flush then return {9,"straight flush", high_card} end if
if _pairs=4 then return {8,"four of a kind", find(4-jokers,ranks)+1} end if
if full_house then return {7,"full house", find(3-jokers,ranks)+1} end if
if _flush then return {6,"flush", high_card} end if
if straight then return {5,"straight", high_card} end if
if _pairs=3 then return {4,"three of a kind", find(3-jokers,ranks)+1} end if
if pair and two_pair then return {3,"two pair", two_pair+1} end if
if pair then return {2,"one pair", pair+1} end if
if jokers then return {2,"one pair", high_card} end if
return {1,"high card",high_card}
end function
sequence hands = {{0,"2♥ 2♦ 2♣ k♣ q♦"},
{0,"2♥ 5♥ 7♦ 8♣ 9♠"},
{0,"a♥ 2♦ 3♣ 4♣ 5♦"},
{0,"2♥ 3♥ 2♦ 3♣ 3♦"},
{0,"2♥ 7♥ 2♦ 3♣ 3♦"},
{0,"2♥ 7♥ 7♦ 7♣ 7♠"},
{0,"10♥ j♥ q♥ k♥ a♥"},
{0,"4♥ 4♠ k♠ 5♦ 10♠"},
{0,"q♣ 10♣ 7♣ 6♣ 4♣"},
{0,"joker 2♦ 2♠ k♠ q♦"},
{0,"joker 5♥ 7♦ 8♠ 9♦"},
{0,"joker 2♦ 3♠ 4♠ 5♠"},
{0,"joker 3♥ 2♦ 3♠ 3♦"},
{0,"joker 7♥ 2♦ 3♠ 3♦"},
{0,"joker 7♥ 7♦ 7♠ 7♣"},
{0,"joker j♥ q♥ k♥ A♥"},
{0,"joker 4♣ k♣ 5♦ 10♠"},
{0,"joker k♣ 7♣ 6♣ 4♣"},
{0,"joker 2♦ joker 4♠ 5♠"},
{0,"joker Q♦ joker A♠ 10♠"},
{0,"joker Q♦ joker A♦ 10♦"},
{0,"joker 2♦ 2♠ joker q♦"}}
for i=1 to length(hands) do
hands[i][1] = poker(hands[i][2])
end for
hands = reverse(sort(deep_copy(hands)))
integer rank
string hand,desc
for i=1 to length(hands) do
{{rank,desc},hand} = hands[i]
printf(1,"%d. %s %s\n",{11-rank,hand,desc})
end for
|
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.
| #Elixir | Elixir | defmodule Population do
def count(n), do: count(<<n :: integer>>, 0)
defp count(<<>>, acc), do: acc
defp count(<<bit :: integer-1, rest :: bitstring>>, sum), do: count(rest, sum + bit)
def evil?(n), do: n >= 0 and rem(count(n),2) == 0
def odious?(n), do: n >= 0 and rem(count(n),2) == 1
end
IO.puts "Population count of the first thirty powers of 3:"
IO.inspect Stream.iterate(1, &(&1*3)) |> Enum.take(30) |> Enum.map(&Population.count(&1))
IO.puts "first thirty evil numbers:"
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.evil?(&1)) |> Enum.take(30)
IO.puts "first thirty odious numbers:"
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.odious?(&1)) |> Enum.take(30) |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for 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
| #Nim | Nim | const MinusInfinity = -1
type
Polynomial = seq[int]
Term = tuple[coeff, exp: int]
func degree(p: Polynomial): int =
## Return the degree of a polynomial.
## "p" is supposed to be normalized.
result = if p.len > 0: p.len - 1 else: MinusInfinity
func normalize(p: var Polynomial) =
## Normalize a polynomial, removing useless zeroes.
while p[^1] == 0: discard p.pop()
func `shr`(p: Polynomial; n: int): Polynomial =
## Shift a polynomial of "n" positions to the right.
result.setLen(p.len + n)
result[n..^1] = p
func `*=`(p: var Polynomial; n: int) =
## Multiply in place a polynomial by an integer.
for item in p.mitems: item *= n
p.normalize()
func `-=`(a: var Polynomial; b: Polynomial) =
## Substract in place a polynomial from another polynomial.
for i, val in b: a[i] -= val
a.normalize()
func longdiv(a, b: Polynomial): tuple[q, r: Polynomial] =
## Compute the long division of a polynomial by another.
## Return the quotient and the remainder as polynomials.
result.r = a
if b.degree < 0: raise newException(DivByZeroDefect, "divisor cannot be zero.")
result.q.setLen(a.len)
while (let k = result.r.degree - b.degree; k >= 0):
var d = b shr k
result.q[k] = result.r[^1] div d[^1]
d *= result.q[k]
result.r -= d
result.q.normalize()
const Superscripts: array['0'..'9', string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
func superscript(n: Natural): string =
## Return the Unicode string to use to represent an exponent.
if n == 1:
return ""
for d in $n:
result.add(Superscripts[d])
func `$`(term: Term): string =
## Return the string representation of a term.
if term.coeff == 0: "0"
elif term.exp == 0: $term.coeff
else:
let base = 'x' & superscript(term.exp)
if term.coeff == 1: base
elif term.coeff == -1: '-' & base
else: $term.coeff & base
func `$`(poly: Polynomial): string =
## return the string representation of a polynomial.
for idx in countdown(poly.high, 0):
let coeff = poly[idx]
var term: Term = (coeff: coeff, exp: idx)
if result.len == 0:
result.add $term
else:
if coeff > 0:
result.add '+'
result.add $term
elif coeff < 0:
term.coeff = -term.coeff
result.add '-'
result.add $term
const
N = @[-42, 0, -12, 1]
D = @[-3, 1]
let (q, r) = longdiv(N, D)
echo "N = ", N
echo "D = ", D
echo "q = ", q
echo "r = ", r |
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
| #OCaml | OCaml | let rec shift n l = if n <= 0 then l else shift (pred n) (l @ [0.0])
let rec pad n l = if n <= 0 then l else pad (pred n) (0.0 :: l)
let rec norm = function | 0.0 :: tl -> norm tl | x -> x
let deg l = List.length (norm l) - 1
let zip op p q =
let d = (List.length p) - (List.length q) in
List.map2 op (pad (-d) p) (pad d q) |
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.
| #Tcl | Tcl | set varCopy $varOriginal |
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.
| #Wren | Wren | class Animal {
construct new(name, age) {
_name = name
_age = age
}
name { _name }
age { _age }
copy() { Animal.new(name, age) }
toString { "Name: %(_name), Age: %(_age)" }
}
class Dog is Animal {
construct new(name, age, breed) {
super(name, age) // call Animal's constructor
_breed = breed
}
// name and age properties will be inherited from Animal
breed { _breed }
copy() { Dog.new(name, age, breed) } // overrides Animal's copy() method
toString { super.toString + ", Breed: %(_breed)" } // overrides Animal's toString method
}
var a = Dog.new("Rover", 3, "Terrier") // a's type is Dog
var b = a.copy() // a's copy() method is called and so b's type is Dog
System.print("Dog 'a' -> %(a)") // implicitly calls a's toString method
System.print("Dog 'b' -> %(b)") // ditto
System.print("Dog 'a' is %((Object.same(a, b)) ? "" : "not") the same object as Dog 'b'") |
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.
| #MATLAB | MATLAB | >> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
>> polyfit(x,y,2)
ans =
2.999999999999998 2.000000000000019 0.999999999999956 |
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.
| #Frink | Frink |
a = new set[1,2,3,4]
a.subsets[]
|
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
| #CMake | CMake | # Prime predicate: does n be a prime number? Sets var to true or false.
function(primep var n)
if(n GREATER 2)
math(EXPR odd "${n} % 2")
if(odd)
# n > 2 and n is odd.
set(factor 3)
# Loop for odd factors from 3, while factor <= n / factor.
math(EXPR quot "${n} / ${factor}")
while(NOT factor GREATER quot)
math(EXPR rp "${n} % ${factor}") # Trial division
if(NOT rp)
# factor divides n, so n is not prime.
set(${var} false PARENT_SCOPE)
return()
endif()
math(EXPR factor "${factor} + 2") # Next odd factor
math(EXPR quot "${n} / ${factor}")
endwhile(NOT factor GREATER quot)
# Loop found no factor, so n is prime.
set(${var} true PARENT_SCOPE)
else()
# n > 2 and n is even, so n is not prime.
set(${var} false PARENT_SCOPE)
endif(odd)
elseif(n EQUAL 2)
set(${var} true PARENT_SCOPE) # 2 is prime.
else()
set(${var} false PARENT_SCOPE) # n < 2 is not prime.
endif()
endfunction(primep) |
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
| #Java | Java | import java.util.Random;
public class Main {
private static float priceFraction(float f) {
if (0.00f <= f && f < 0.06f) return 0.10f;
else if (f < 0.11f) return 0.18f;
else if (f < 0.16f) return 0.26f;
else if (f < 0.21f) return 0.32f;
else if (f < 0.26f) return 0.38f;
else if (f < 0.31f) return 0.44f;
else if (f < 0.36f) return 0.50f;
else if (f < 0.41f) return 0.54f;
else if (f < 0.46f) return 0.58f;
else if (f < 0.51f) return 0.62f;
else if (f < 0.56f) return 0.66f;
else if (f < 0.61f) return 0.70f;
else if (f < 0.66f) return 0.74f;
else if (f < 0.71f) return 0.78f;
else if (f < 0.76f) return 0.82f;
else if (f < 0.81f) return 0.86f;
else if (f < 0.86f) return 0.90f;
else if (f < 0.91f) return 0.94f;
else if (f < 0.96f) return 0.98f;
else if (f < 1.01f) return 1.00f;
else throw new IllegalArgumentException();
}
public static void main(String[] args) {
Random rnd = new Random();
for (int i = 0; i < 5; i++) {
float f = rnd.nextFloat();
System.out.format("%8.6f -> %4.2f%n", f, priceFraction(f));
}
}
} |
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
| #Oberon-2 | Oberon-2 |
MODULE ProperDivisors;
IMPORT
Out;
CONST
initialSize = 128;
TYPE
Result* = POINTER TO ResultDesc;
ResultDesc = RECORD
found-: LONGINT; (* number of slots in pd *)
pd-: POINTER TO ARRAY OF LONGINT;
cap: LONGINT; (* Capacity *)
END;
VAR
i,found,max,idxMx: LONGINT;
mx: ARRAY 32 OF LONGINT;
rs: Result;
PROCEDURE (r: Result) Init(size: LONGINT);
BEGIN
r.found := 0;
r.cap := size;
NEW(r.pd,r.cap);
END Init;
PROCEDURE (r: Result) Add(n: LONGINT);
BEGIN
(* Out.String("--->");Out.LongInt(n,0);Out.String(" At: ");Out.LongInt(r.found,0);Out.Ln; *)
IF (r.found < LEN(r.pd^) - 1) THEN
r.pd[r.found] := n;
ELSE
(* expand pd for more room *)
END;
INC(r.found);
END Add;
PROCEDURE (r:Result) Show();
VAR
i: LONGINT;
BEGIN
Out.String("(Result:");Out.LongInt(r.found + 1,0);(* Out.String("/");Out.LongInt(r.cap,0);*)
Out.String("-");
IF r.found > 0 THEN
FOR i:= 0 TO r.found - 1 DO
Out.LongInt(r.pd[i],0);
IF i = r.found - 1 THEN Out.Char(')') ELSE Out.Char(',') END
END
END;
Out.Ln
END Show;
PROCEDURE (r:Result) Reset();
BEGIN
r.found := 0;
END Reset;
PROCEDURE GetFor(n: LONGINT;VAR rs: Result);
VAR
i: LONGINT;
BEGIN
IF n > 1 THEN
rs.Add(1);i := 2;
WHILE (i < n) DO
IF (n MOD i) = 0 THEN rs.Add(i) END;
INC(i)
END
END;
END GetFor;
BEGIN
NEW(rs);rs.Init(initialSize);
FOR i := 1 TO 10 DO
Out.LongInt(i,4);Out.Char(':');
GetFor(i,rs);
rs.Show();
rs.Reset();
END;
Out.LongInt(100,4);Out.Char(':');GetFor(100,rs);rs.Show();rs.Reset();
max := 0;idxMx := 0;found := 0;
FOR i := 1 TO 20000 DO
GetFor(i,rs);
IF rs.found > max THEN
idxMx:= 0;mx[idxMx] := i;max := rs.found
ELSIF rs.found = max THEN
INC(idxMx);mx[idxMx] := i
END;
rs.Reset()
END;
Out.String("Found: ");Out.LongInt(idxMx + 1,0);
Out.String(" Numbers with most proper divisors ");
Out.LongInt(max,0);Out.String(": ");Out.Ln;
FOR i := 0 TO idxMx DO
Out.LongInt(mx[i],0);Out.Ln
END
END ProperDivisors.
|
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)
| #Scheme | Scheme | (use-modules (ice-9 format))
(define (random-choice probs)
(define choice (random 1.0))
(define (helper val prob-lis)
(let ((nval (- val (cadar prob-lis))))
(if
(< nval 0)
(caar prob-lis)
(helper nval (cdr prob-lis)))))
(helper choice probs))
(define (add-result result delta table)
(cond
((null? table) (list (list result delta)))
((eq? (caar table) result)
(cons (list result (+ (cadar table) delta)) (cdr table)))
(#t (cons (car table) (add-result result delta (cdr table))))))
(define (choices trials probs)
(define (helper trial-num freq-table)
(if
(= trial-num trials)
freq-table
(helper
(+ trial-num 1)
(add-result (random-choice probs) (/ 1 trials) freq-table))))
(helper 0 '()))
(define (format-results probs results)
(for-each
(lambda (x)
(format
#t
"~10a~10,5f~10,5f~%"
(car x)
(cadr x)
(cadr (assoc (car x) results))))
probs))
(define probs
'((aleph 1/5) (beth 1/6) (gimel 1/7) (daleth 1/8)
(he 1/9) (waw 1/10) (zayin 1/11) (heth 1759/27720)))
(format-results probs (choices 1000000 probs)) |
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.
| #Phix | Phix | with javascript_semantics
constant tasklist = new_dict()
procedure add_task(integer priority, string desc)
integer k = getd_index(priority,tasklist)
if k=0 then
putd(priority,{desc},tasklist)
else
sequence descs = getd_by_index(k,tasklist)
putd(priority,append(descs,desc),tasklist)
end if
end procedure
function list_task_visitor(integer priority, sequence descs, integer /*user_data*/)
?{priority,descs}
return true -- continue
end function
procedure list_tasks()
traverse_dict(list_task_visitor, 0, tasklist, true)
end procedure
function pop_task_visitor(integer priority, sequence descs, integer rid)
string desc = descs[1]
descs = descs[2..$]
if length(descs)=0 then
deld(priority,tasklist)
else
putd(priority,descs,tasklist)
end if
rid(priority,desc)
return false -- stop
end function
procedure pop_task(integer rid)
if dict_size(tasklist)!=0 then
traverse_dict(pop_task_visitor, rid, tasklist, true)
end if
end procedure
add_task(3,"Clear drains")
add_task(4,"Feed cat")
add_task(5,"Make tea")
add_task(1,"Solve RC tasks")
add_task(2,"Tax return")
procedure do_task(integer priority, string desc)
?{priority,desc}
end procedure
list_tasks()
?"==="
pop_task(do_task)
?"==="
list_tasks()
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
Sub getPrimeFactors(factors() As UInteger, n As UInteger)
If n < 2 Then Return
If isPrime(n) Then
Redim factors(0 To 0)
factors(0) = n
Return
End If
Dim factor As UInteger = 2
Do
If n Mod factor = 0 Then
Redim Preserve factors(0 To UBound(factors) + 1)
factors(UBound(factors)) = factor
n \= factor
If n = 1 Then Return
If isPrime(n) Then factor = n
Else
factor += 1
End If
Loop
End Sub
Dim factors() As UInteger
Dim primes(1 To 17) As UInteger = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
Dim n As UInteger
For i As UInteger = 1 To 17
Erase factors
n = 1 Shl primes(i) - 1
getPrimeFactors factors(), n
Print "2^";Str(primes(i)); Tab(5); " - 1 = "; Str(n); Tab(30);" => ";
For j As UInteger = LBound(factors) To UBound(factors)
Print factors(j);
If j < UBound(factors) Then Print " x ";
Next j
Print
Next i
Print
Print "Press any key to quit"
Sleep |
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.
| #Sidef | Sidef | func assign2ref(ref, value) {
*ref = value;
}
var x = 10;
assign2ref(\x, 20);
say x; # x is now 20 |
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.
| #Standard_ML | Standard ML |
val p = ref 1; (* create a new "reference" data structure with initial value 1 *)
val k = !p; (* "dereference" the reference, returning the value inside *)
p := k + 1; (* set the value inside to a new value *)
|
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.
| #Tcl | Tcl | set var 3
set pointer var; # assign name "var" not value 3
set pointer; # returns "var"
set $pointer; # returns 3
set $pointer 42; # variable var now has value 42 |
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.
| #Kotlin | Kotlin | // Version 1.2.31
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection
import org.jfree.chart.plot.PlotOrientation
import javax.swing.JFrame
import javax.swing.SwingUtilities
import java.awt.BorderLayout
fun main(args: Array<String>) {
val x = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
val y = doubleArrayOf(
2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0
)
val series = XYSeries("plots")
(0 until x.size).forEach { series.add(x[it], y[it]) }
val labels = arrayOf("Plot Demo", "X", "Y")
val data = XYSeriesCollection(series)
val options = booleanArrayOf(false, true, false)
val orient = PlotOrientation.VERTICAL
val chart = ChartFactory.createXYLineChart(
labels[0], labels[1], labels[2], data, orient, options[0], options[1], options[2]
)
val chartPanel = ChartPanel(chart)
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(chartPanel, BorderLayout.CENTER)
title = "Plot coordinate pairs"
isResizable = false
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
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
| #Haskell | Haskell | data Point = Point Integer Integer
instance Show Point where
show (Point x y) = "Point at "++(show x)++","++(show y)
-- Constructor that sets y to 0
ponXAxis = flip Point 0
-- Constructor that sets x to 0
ponYAxis = Point 0
-- Constructor that sets x and y to 0
porigin = Point 0 0
data Circle = Circle Integer Integer Integer
instance Show Circle where
show (Circle x y r) = "Circle at "++(show x)++","++(show y)++" with radius "++(show r)
-- Constructor that sets y to 0
conXAxis = flip Circle 0
-- Constructor that sets x to 0
conYAxis = Circle 0
-- Constructor that sets x and y to 0
catOrigin = Circle 0 0
--Constructor that sets y and r to 0
c0OnXAxis = flip (flip Circle 0) 0
--Constructor that sets x and r to 0
c0OnYAxis = flip (Circle 0) 0 |
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
| #Picat | Picat | go =>
Hands = [
[[2,h], [7,h], [2,d], [3,c], [3,d]], % two-pair
[[2,h], [5,h], [7,d], [8,c], [9,s]], % high-card
[[a,h], [2,d], [3,c], [4,c], [5,d]], % straight
[[2,h], [3,h], [2,d], [3,c], [3,d]], % full-house
[[2,h], [7,h], [2,d], [3,c], [3,d]], % two-pair
[[2,h], [7,h], [7,d], [7,c], [7,s]], % four-of-a-kind
[[10,h],[j,h], [q,h], [k,h], [a,h]], % straight-flush
[[4,h], [4,s], [k,s], [5,d], [10,s]], % one-pair
[[q,c], [10,c],[7,c], [6,c], [4,c]], % flush
[[q,c], [q,d], [q,s], [6,c], [4,c]], % three-of-a-kind
[[q,c], [10,c], [7,c], [7,c], [4,c]], % invalid (duplicates)
[[q,c], [10,c], [7,c], [7,d]] % invalid (too short)
],
foreach(Hand in Hands)
print_hand(Hand),
analyse(Hand, H),
println(hand=H),
nl
end,
nl.
% Print the hand
print_hand(Hand) =>
println([ F.to_string() ++ S.to_string() : [F,S] in Hand]).
% Faces and suites
faces(Faces) => Faces = [a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k].
faces_order1(Order1) =>
Order1 = new_map([a=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, j=11, q=12, k=13]).
faces_order2(Order2) =>
Order2 = new_map([2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, j=11, q=12, k=13, a=14]).
suites(Suites) => Suites = [h,d,c,s].
% Order of the hand
hand_order(HandOrder) =>
HandOrder = [straight_flush,
four_of_a_kind,
full_house,
flush,
straight,
three_of_a_kind,
two_pair,
one_pair,
high_card,
invalid].
% for the straight
in_order(List) =>
foreach(I in 2..List.length)
List[I] = List[I-1] + 1
end.
% Some validity tests first
analyse(Hand,Value) ?=>
(
Hand.remove_dups.length == 5,
faces(Faces),
foreach([F,_] in Hand)
member(F,Faces)
end,
suites(Suites),
foreach([_,S] in Hand)
member(S,Suites)
end,
analyse1(Hand,Value)
;
Value = invalid
).
% Identify the specific hands
% straight flush
analyse1(Hand,Value) ?=>
permutation(Hand,Hand1),
Hand1 = [ [_F1,S], [_F2,S], [_F3,S], [_F4,S], [_F5,S] ],
(
faces_order1(Order1),
in_order([Order1.get(F) : [F,S1] in Hand1])
;
faces_order2(Order2),
in_order([Order2.get(F) : [F,S1] in Hand1]),
println("Royal Straight Flush!")
),
Value=straight_flush.
% four of a kind
analyse1(Hand,Value) ?=>
faces(Faces),
member(A,Faces),
[1 : [F,_S] in Hand, F = A].length == 4,
Value=four_of_a_kind.
% full house
analyse1(Hand,Value) ?=>
permutation(Hand,Hand1),
Hand1 = [ [F1,_S1], [F1,_S2], [F2,_S3], [F2,_S4], [F2,_S5] ],
Value = full_house.
% flush
analyse1(Hand,Value) ?=>
permutation(Hand,Hand1),
Hand1 = [ [_,S], [_,S], [_,S], [_,S], [_,S] ],
Value = flush.
% straight
analyse1(Hand,Value) ?=>
permutation(Hand,Hand1),
(
faces_order1(Order1),
in_order([Order1.get(F) : [F,_S] in Hand1])
;
faces_order2(Order2),
in_order([Order2.get(F) : [F,_S] in Hand1])
),
Value = straight.
% three of a kind
analyse1(Hand,Value) ?=>
faces(Faces),
member(A,Faces),
[1 : [F,_S] in Hand, F = A].length == 3,
Value = three_of_a_kind.
% two pair
analyse1(Hand,Value) ?=>
permutation(Hand,Hand1),
Hand1 = [ [F1,_S1], [F1,_S2], [F2,_S3], [F2,_S4], [_F3,_S5] ],
Value = two_pair.
% one pair
analyse1(Hand,Value) ?=>
faces(Faces),
member(A,Faces),
[1 : [F,_S] in Hand, F = A].length == 2,
Value = one_pair.
% high card
analyse1(_Hand,Value) =>
Value = high_card. |
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.
| #Erlang | Erlang | -module(population_count).
-export([popcount/1]).
-export([task/0]).
popcount(N) ->
popcount(N,0).
popcount(0,Acc) ->
Acc;
popcount(N,Acc) ->
popcount(N div 2, Acc + N rem 2).
threes(_,0,Acc) ->
lists:reverse(Acc);
threes(Threes,N,Acc) ->
threes(Threes * 3, N-1, [popcount(Threes)|Acc]).
threes(N) ->
threes(1,N,[]).
evil(_,0,Acc) ->
lists:reverse(Acc);
evil(N,Count,Acc) ->
case popcount(N) rem 2 of
0 ->
evil(N+1,Count-1,[N|Acc]);
1 ->
evil(N+1,Count,Acc)
end.
evil(Count) ->
evil(0,Count,[]).
odious(_,0,Acc) ->
lists:reverse(Acc);
odious(N,Count,Acc) ->
case popcount(N) rem 2 of
1 ->
odious(N+1,Count-1,[N|Acc]);
0 ->
odious(N+1,Count,Acc)
end.
odious(Count) ->
odious(1,Count,[]).
task() ->
io:format("Powers of 3: ~p~n",[threes(30)]),
io:format("Evil:~p~n",[evil(30)]),
io:format("Odious:~p~n",[odious(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
| #Octave | Octave | function [q, r] = poly_long_div(n, d)
gd = length(d);
pv = zeros(1, length(n));
pv(1:gd) = d;
if ( length(n) >= gd )
q = [];
while ( length(n) >= gd )
q = [q, n(1)/pv(1)];
n = n - pv .* (n(1)/pv(1));
n = shift(n, -1); %
tn = n(1:length(n)-1); % eat the higher power term
n = tn; %
tp = pv(1:length(pv)-1);
pv = tp; % make pv the same length of n
endwhile
r = n;
else
q = [0];
r = n;
endif
endfunction
[q, r] = poly_long_div([1,-12,0,-42], [1,-3]);
polyout(q, 'x');
polyout(r, 'x');
disp("");
[q, r] = poly_long_div([1,-12,0,-42], [1,1,-3]);
polyout(q, 'x');
polyout(r, 'x');
disp("");
[q, r] = poly_long_div([1,3,2], [1,1]);
polyout(q, 'x');
polyout(r, 'x');
disp("");
[q, r] = poly_long_div([1,3], [1,-12,0,-42]);
polyout(q, 'x');
polyout(r, 'x'); |
http://rosettacode.org/wiki/Polynomial_regression | Polynomial regression | Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ПC С/П ПD ИП9 + П9 ИПC ИП5 + П5
ИПC x^2 П2 ИП6 + П6 ИП2 ИПC * ИП7
+ П7 ИП2 x^2 ИП8 + П8 ИПC ИПD *
ИПA + ПA ИП2 ИПD * ИПB + ПB ИПD
КИП4 С/П БП 00 |
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.
| #FunL | FunL | def powerset( s ) = s.subsets().toSet() |
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
| #COBOL | COBOL | Identification Division.
Program-Id. Primality-By-Subdiv.
Data Division.
Working-Storage Section.
78 True-Val Value 0.
78 False-Val Value 1.
Local-Storage Section.
01 lim Pic 9(10).
01 i Pic 9(10).
Linkage Section.
01 num Pic 9(10).
01 result Pic 9.
Procedure Division Using num result.
Main.
If num <= 1
Move False-Val To result
Goback
Else If num = 2
Move True-Val To result
Goback
End-If
Compute lim = Function Sqrt(num) + 1
Perform Varying i From 3 By 1 Until lim < i
If Function Mod(num, i) = 0
Move False-Val To result
Goback
End-If
End-Perform
Move True-Val To Result
Goback
. |
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
| #JavaScript | JavaScript | function getScaleFactor(v) {
var values = ['0.10','0.18','0.26','0.32','0.38','0.44','0.50','0.54',
'0.58','0.62','0.66','0.70','0.74','0.78','0.82','0.86',
'0.90','0.94','0.98','1.00'];
return values[(v * 100 - 1) / 5 | 0];
} |
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Objeck | Objeck | use Collection;
class Proper{
function : Main(args : String[]) ~ Nil {
for(x := 1; x <= 10; x++;) {
Print(x, ProperDivs(x));
};
x := 0;
count := 0;
for(n := 1; n <= 20000; n++;) {
if(ProperDivs(n)->Size() > count) {
x := n;
count := ProperDivs(n)->Size();
};
};
"{$x}: {$count}"->PrintLine();
}
function : ProperDivs(n : Int) ~ IntVector {
divs := IntVector->New();
if(n = 1) {
return divs;
};
divs->AddBack(1);
for(x := 2; x < n; x++;) {
if(n % x = 0) {
divs->AddBack(x);
};
};
divs->Sort();
return divs;
}
function : Print(x : Int, result : IntVector) ~ Nil {
"{$x}: "->Print();
result->ToArray()->ToString()->PrintLine();
}
}
|
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)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const type: letter is new enum
aleph, beth, gimel, daleth, he, waw, zayin, heth
end enum;
const func string: str (in letter: aLetter) is
return [] ("aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth") [succ(ord(aLetter))];
enable_output(letter);
const array [letter] integer: table is [letter] (
5544, 4620, 3960, 3465, 3080, 2772, 2520, 1759);
const func letter: randomLetter is func
result
var letter: resultLetter is aleph;
local
var integer: number is 0;
begin
number := rand(1, 27720);
while number > table[resultLetter] do
number -:= table[resultLetter];
incr(resultLetter);
end while;
end func;
const proc: main is func
local
var integer: count is 0;
var letter: aLetter is aleph;
var array [letter] integer: occurrence is letter times 0;
begin
for count range 1 to 1000000 do
aLetter := randomLetter;
incr(occurrence[aLetter]);
end for;
writeln("Name Count Ratio Expected");
for aLetter range letter.first to letter.last do
writeln(aLetter rpad 7 <& occurrence[aLetter] lpad 6 <&
flt(occurrence[aLetter]) / 10000.9 digits 4 lpad 8 <& "%" <&
100.0 * flt(table[aLetter]) / 27720.0 digits 4 lpad 8 <& "%");
end for;
end func; |
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.
| #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Priority_queue
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
( )
( 3 "Clear drains" ) 0 put ( 4 "Feed cat" ) 0 put ( 5 "Make tea" ) 0 put ( 1 "Solve RC tasks" ) 0 put ( 2 "Tax return" ) 0 put
sort pop swap print pstack
|
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
| #Frink | Frink | println[factor[2^508-1]] |
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.
| #Toka | Toka | variable myvar #! stores 1 cell
|
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.
| #VBA | VBA | Dim samplevariable as New Object
Dim anothervariable as Object
Set anothervariable = sameplevariable |
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.
| #Wren | Wren | // This function takes a string (behaves like a value type) and a list (reference type).
// The value and the reference are copied to their respective parameters.
var f = Fn.new { |s, l|
if (s.type != String) Fiber.abort("First parameter must be a string.")
if (l.type != List) Fiber.abort("Second parameter must be a list.")
// add the first argument to the list
l.add(s) // the original 'l' will reflect this
// mutate the first argument by reversing it
s = s[-1..0] // the original 's' will not reflect this
}
var s = "wren"
var l = ["magpie", "finch"]
f.call(s, l)
System.print(l)
System.print(s) |
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Lambdatalk | Lambdatalk |
1) define X & Y:
{def X 0 1 2 3 4 5 7 8 9}
-> X
{def Y 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0}
-> Y
2) define a function returning a sequence of SVG points
{def curve
{lambda {:curve :kx :ky}
{S.map {{lambda {:curve :kx :ky :i}
{* :kx {S.get :i {{car :curve}}}}
{* :ky {S.get :i {{cdr :curve}}}} } :curve :kx :ky}
{S.serie 0 {- {S.length {X}} 1}} }}}
3) draw a polyline in a SVG context
{svg {@ width="580" height="300" style="background:#eee"}
{g {AXES 580 300}
{polyline {@ points="{curve {cons X Y} 30 0.9}"
stroke="#000" fill="transparent" stroke-width="1"}} }}
where
{def AXES
{lambda {:w :h}
{@ transform="translate({/ :w 2},{/ :h 2}) scale(1,-1)"}
{line {@ x1="-{/ :w 2}:w" y1="0"
x2="{/ :w 2}" y2="0"
stroke="red" fill="transparent"}}
{line {@ x1="0" y1="-{/ :h 2}"
x2="0" y2="{/ :h 2}"
stroke="green" fill="transparent"}} }}
4) the result can be seen in http://lambdaway.free.fr/lambdawalks/?view=plot4
|
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
| #Icon_and_Unicon | Icon and Unicon | class Circle (x, y, r)
# make a new copy of this instance
method copy ()
return Circle (x, y, r)
end
# print a representation of this instance
method print ()
write ("Circle (" || x || ", " || y || ", " || r || ")")
end
# called during instance construction, to pass in field values
initially (x, y, r)
self.x := if /x then 0 else x # set to 0 if argument not present
self.y := if /y then 0 else y
self.r := if /r then 0 else r
end
class Point (x, y)
# make a new copy of this instance
method copy ()
return Point (x, y)
end
# print a representation of this instance
method print ()
write ("Point (" || x || ", " || y || ")")
end
# called during instance construction, to pass in field values
initially (x, y)
self.x := if /x then 0 else x # set to 0 if argument not present
self.y := if /y then 0 else y
end
procedure main ()
p1 := Point ()
p2 := Point (1)
p3 := Point (1,2)
p4 := p3.copy ()
write ("Points:")
p1.print ()
p2.print ()
p3.print ()
p4.print ()
# demonstrate field mutator/accessor
p3.x := 3
write ("p3 value of x is: " || p3.x)
c1 := Circle ()
c2 := Circle (1)
c3 := Circle (1,2)
c4 := Circle (1,2,3)
write ("Circles:")
c1.print ()
c2.print ()
c3.print ()
c4.print ()
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
| #PicoLisp | PicoLisp | (setq *Rank
'(("2" . 0) ("3" . 1) ("4" . 2)
("5" . 3) ("6" . 4) ("7" . 5)
("8" . 6) ("9" . 7) ("t" . 8)
("j" . 9) ("q" . 10) ("k" . 11)
("a" . 12) ) )
(de poker (Str)
(let (S NIL R NIL Seq NIL)
(for (L (chop Str) (cdr L) (cdddr L))
(accu 'R (cdr (assoc (car L) *Rank)) 1)
(accu 'S (cadr L) 1) )
(setq Seq
(make
(for (L (by car sort R) (cdr L) (cdr L))
(link (- (caar L) (caadr L))) ) ) )
(cond
((and
(= 5 (cdar S))
(or
(= (-1 -1 -1 -1) Seq)
(= (-1 -1 -1 -9) Seq) ) )
'straight-flush )
((rassoc 4 R) 'four-of-a-kind)
((and (rassoc 2 R) (rassoc 3 R)) 'full-house)
((= 5 (cdar S)) 'flush)
((or
(= (-1 -1 -1 -1) Seq)
(= (-1 -1 -1 -9) Seq) )
'straight )
((rassoc 3 R) 'three-of-a-kind)
((=
2
(cnt '((L) (= 2 (cdr L))) R) )
'two-pair )
((rassoc 2 R) 'pair)
(T 'high-card) ) ) ) |
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.
| #F.23 | F# |
// Population count. Nigel Galloway: February 18th., 2021
let pC n=Seq.unfold(fun n->match n/2L,n%2L with (0L,0L)->None |(n,g)->Some(g,n))n|>Seq.sum
printf "pow3 :"; [0..29]|>List.iter((pown 3L)>>pC>>(printf "%3d")); printfn ""
printf "evil :"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=0L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""
printf "odious:"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=1L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""
|
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
| #PARI.2FGP | PARI/GP | poldiv(a,b)={
my(rem=a%b);
[(a - rem)/b, rem]
};
poldiv(x^9+1, x^3+x-3) |
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.
| #Modula-2 | Modula-2 | MODULE PolynomialRegression;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Eval(a,b,c,x : REAL) : REAL;
BEGIN
RETURN a + b*x + c*x*x;
END Eval;
PROCEDURE Regression(x,y : ARRAY OF INTEGER);
VAR
n,i : INTEGER;
xm,x2m,x3m,x4m : REAL;
ym : REAL;
xym,x2ym : REAL;
sxx,sxy,sxx2,sx2x2,sx2y : REAL;
a,b,c : REAL;
buf : ARRAY[0..63] OF CHAR;
BEGIN
n := SIZE(x)/SIZE(INTEGER);
xm := 0.0;
ym := 0.0;
x2m := 0.0;
x3m := 0.0;
x4m := 0.0;
xym := 0.0;
x2ym := 0.0;
FOR i:=0 TO n-1 DO
xm := xm + FLOAT(x[i]);
ym := ym + FLOAT(y[i]);
x2m := x2m + FLOAT(x[i]) * FLOAT(x[i]);
x3m := x3m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]);
x4m := x4m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]);
xym := xym + FLOAT(x[i]) * FLOAT(y[i]);
x2ym := x2ym + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(y[i]);
END;
xm := xm / FLOAT(n);
ym := ym / FLOAT(n);
x2m := x2m / FLOAT(n);
x3m := x3m / FLOAT(n);
x4m := x4m / FLOAT(n);
xym := xym / FLOAT(n);
x2ym := x2ym / FLOAT(n);
sxx := x2m - xm * xm;
sxy := xym - xm * ym;
sxx2 := x3m - xm * x2m;
sx2x2 := x4m - x2m * x2m;
sx2y := x2ym - x2m * ym;
b := (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
c := (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
a := ym - b * xm - c * x2m;
WriteString("y = ");
RealToStr(a, buf);
WriteString(buf);
WriteString(" + ");
RealToStr(b, buf);
WriteString(buf);
WriteString("x + ");
RealToStr(c, buf);
WriteString(buf);
WriteString("x^2");
WriteLn;
FOR i:=0 TO n-1 DO
FormatString("%2i %3i ", buf, x[i], y[i]);
WriteString(buf);
RealToStr(Eval(a,b,c,FLOAT(x[i])), buf);
WriteString(buf);
WriteLn;
END;
END Regression;
TYPE R = ARRAY[0..10] OF INTEGER;
VAR
x,y : R;
BEGIN
x := R{0,1,2,3,4,5,6,7,8,9,10};
y := R{1,6,17,34,57,86,121,162,209,262,321};
Regression(x,y);
ReadChar;
END PolynomialRegression. |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | # Built-in
Combinations([1, 2, 3]);
# [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]
# Note that it handles duplicates
Combinations([1, 2, 3, 1]);
# [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ],
# [ 2 ], [ 2, 3 ], [ 3 ] ] |
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
| #CoffeeScript | CoffeeScript | is_prime = (n) ->
# simple prime detection using trial division, works
# for all integers
return false if n <= 1 # by definition
p = 2
while p * p <= n
return false if n % p == 0
p += 1
true
for i in [-1..100]
console.log i if is_prime i |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #jq | jq | def getScaleFactor:
["0.10","0.18","0.26","0.32","0.38","0.44","0.50","0.54",
"0.58","0.62","0.66","0.70","0.74","0.78","0.82","0.86",
"0.90","0.94","0.98","1.00"] as $values
| $values[ (. * 100 - 1) / 5 | floor ] ; |
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
| #Oforth | Oforth | Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) }
10 seq apply(#[ dup print " : " print properDivs println ])
20000 seq map(#[ dup properDivs size Pair new ]) reduce(#maxKey) println |
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)
| #Sidef | Sidef | define TRIALS = 1e4;
func prob_choice_picker(options) {
var n = 0;
var a = [];
options.each { |k,v|
n += v;
a << [n, k];
}
func {
var r = 1.rand;
a.first{|e| r <= e[0] }[1];
}
}
var ps = Hash(
aleph => 1/5,
beth => 1/6,
gimel => 1/7,
daleth => 1/8,
he => 1/9,
waw => 1/10,
zayin => 1/11
)
ps{:heth} = (1 - ps.values.sum)
var picker = prob_choice_picker(ps)
var results = Hash()
TRIALS.times {
results{picker()} := 0 ++;
}
say "Event Occurred Expected Difference";
for k,v in (results.sort_by {|k| results{k} }.reverse) {
printf("%-6s %f %f %f\n",
k, v/TRIALS, ps{k},
abs(v/TRIALS - ps{k})
);
} |
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.
| #PHP | PHP | <?php
$pq = new SplPriorityQueue;
$pq->insert('Clear drains', 3);
$pq->insert('Feed cat', 4);
$pq->insert('Make tea', 5);
$pq->insert('Solve RC tasks', 1);
$pq->insert('Tax return', 2);
// This line causes extract() to return both the data and priority (in an associative array),
// Otherwise it would just return the data
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
while (!$pq->isEmpty()) {
print_r($pq->extract());
}
?> |
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
| #GAP | GAP | FactorsInt(2^67-1);
# [ 193707721, 761838257287 ] |
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.
| #XPL0 | XPL0 | \Paraphrasing the C example:
\This creates a pointer to an integer variable:
int Var, Ptr, V;
Ptr:= @Var;
\Access the integer variable through the pointer:
Var:= 3;
V:= Ptr(0); \set V to the value of Var, i.e. 3
Ptr(0):= 42; \set Var to 42
\Change the pointer to refer to another integer variable:
int OtherVar;
Ptr:= @OtherVar;
\Change the pointer to not point to anything:
Ptr:= 0; \or any integer expression that evaluates to 0
\Set the pointer to the first item of an array:
int Array(10);
Ptr:= Array;
\Or alternatively:
Ptr:= @Array(0);
\Move the pointer to another item in the array:
def IntSize = 4; \number of bytes in an integer
Ptr:= Ptr + 3*IntSize; \pointer now points to Array(3)
Ptr:= Ptr - 2*IntSize; \pointer now points to Array(1)
\Access an item in the array using the pointer:
V:= Ptr(3); \get third item after Array(1), i.e. Array(4)
V:= Ptr(-1); \get item immediately preceding Array(1), i.e. Array(0)
] |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #Z80_Assembly | Z80 Assembly | ld a,(&C000) ;load the accumulator with the value from the memory address &C000.
ld hl,&D000
ld e,(hl) ;load the E register with the byte at memory address &D000.
ld bc,(&E000) ;load the register pair BC from memory address &E000.
; This is the same as:
; ld a,(&E000)
; ld c,a
; ld a,(&E001)
; ld b,a
ld IX,&F000
ld a,(IX+3) ;load A with the byte stored at &F003 |
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.
| #Liberty_BASIC | Liberty BASIC |
'Plotting coordinate pairs MainWin - Style
For i = 0 To 9
x(i) = i
Next i
y(0) = 2.7
y(1) = 2.8
y(2) = 31.4
y(3) = 38.1
y(4) = 58.0
y(5) = 76.2
y(6) = 100.5
y(7) = 130.0
y(8) = 149.3
y(9) = 180.0
Locate 4, 22
For i = 0 To 9
Locate ((i * 4) + 2), 22
Print i
Next i
For i = 0 To 20 Step 2
Locate 0, (21 - i)
Print (i * 10)
Next i
For i = 0 To 9
Locate (x(i) * 4) + 2, (21 - (y(i)/ 10))
Print "."
Next i
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
| #Inform_7 | Inform 7 | Space is a room.
A point is a kind of thing.
A point has a number called X position.
A point has a number called Y position.
A circle is a kind of point.
A circle has a number called radius.
To print (P - point): say "Point: [X position of P], [Y position of P]."
To print (C - circle): say "Circle: [X position of C], [Y position of C] radius [radius of C]."
The origin is a point with X position 0 and Y position 0.
The circle of power is a circle with X position 100, Y position 25, radius 7.
When play begins:
print the origin;
print the circle of power;
end the story. |
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
| #J | J | coclass 'Point'
create=: monad define
'X Y'=:2{.y
)
getX=: monad def 'X'
getY=: monad def 'Y'
setX=: monad def 'X=:y'
setY=: monad def 'Y=:y'
print=: monad define
smoutput 'Point ',":X,Y
)
destroy=: codestroy |
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
| #Prolog | Prolog | :- initialization(main).
faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).
face(F) :- faces(Fs), member(F,Fs).
suit(S) :- member(S, ['♥','♦','♣','♠']).
best_hand(Cards,H) :-
straight_flush(Cards,C) -> H = straight-flush(C)
; many_kind(Cards,F,4) -> H = four-of-a-kind(F)
; full_house(Cards,F1,F2) -> H = full-house(F1,F2)
; flush(Cards,S) -> H = flush(S)
; straight(Cards,F) -> H = straight(F)
; many_kind(Cards,F,3) -> H = three-of-a-kind(F)
; two_pair(Cards,F1,F2) -> H = two-pair(F1,F2)
; many_kind(Cards,F,2) -> H = one-pair(F)
; many_kind(Cards,F,1) -> H = high-card(F)
; H = invalid
.
straight_flush(Cards, c(F,S)) :- straight(Cards,F), flush(Cards,S).
full_house(Cards,F1,F2) :-
many_kind(Cards,F1,3), many_kind(Cards,F2,2), F1 \= F2.
flush(Cards,S) :- maplist(has_suit(S), Cards).
has_suit(S, c(_,S)).
straight(Cards,F) :-
select(c(F,_), Cards, Cs), pred_face(F,F1), straight(Cs,F1).
straight([],_).
pred_face(F,F1) :- F = 2 -> F1 = a ; faces(Fs), append(_, [F,F1|_], Fs).
two_pair(Cards,F1,F2) :-
many_kind(Cards,F1,2), many_kind(Cards,F2,2), F1 \= F2.
many_kind(Cards,F,N) :-
face(F), findall(_, member(c(F,_), Cards), Xs), length(Xs,N).
% utils/parser
parse_line(Cards) --> " ", parse_line(Cards).
parse_line([C|Cs]) --> parse_card(C), parse_line(Cs).
parse_line([]) --> [].
parse_card(c(F,S)) --> parse_face(F), parse_suit(S).
parse_suit(S,In,Out) :- suit(S), atom_codes(S,Xs), append(Xs,Out,In).
parse_face(F,In,Out) :- face(F), face_codes(F,Xs), append(Xs,Out,In).
face_codes(F,Xs) :- number(F) -> number_codes(F,Xs) ; atom_codes(F,Xs).
% tests
test(" 2♥ 2♦ 2♣ k♣ q♦").
test(" 2♥ 5♥ 7♦ 8♣ 9♠").
test(" a♥ 2♦ 3♣ 4♣ 5♦").
test(" 2♥ 3♥ 2♦ 3♣ 3♦").
test(" 2♥ 7♥ 2♦ 3♣ 3♦").
test(" 2♥ 7♥ 7♦ 7♣ 7♠").
test("10♥ j♥ q♥ k♥ a♥").
test(" 4♥ 4♠ k♠ 5♦ 10♠").
test(" q♣ 10♣ 7♣ 6♣ 4♣").
run_tests :-
test(Line), phrase(parse_line(Cards), Line), best_hand(Cards,H)
, write(Cards), write('\t'), write(H), nl
.
main :- findall(_, run_tests, _), halt. |
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.
| #Factor | Factor | USING: formatting kernel lists lists.lazy math math.bitwise
math.functions namespaces prettyprint.config sequences ;
: 3^n ( obj -- obj' ) [ 3 swap ^ bit-count ] lmap-lazy ;
: evil ( obj -- obj' ) [ bit-count even? ] lfilter ;
: odious ( obj -- obj' ) [ bit-count odd? ] lfilter ;
100 margin set 0 lfrom [ 3^n ] [ evil ] [ odious ] tri
[ 30 swap ltake list>array ] tri@
"3^n: %u\nEvil: %u\nOdious: %u\n" printf |
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
| #Perl | Perl | use strict;
use List::Util qw(min);
sub poly_long_div
{
my ($rn, $rd) = @_;
my @n = @$rn;
my $gd = scalar(@$rd);
if ( scalar(@n) >= $gd ) {
my @q = ();
while ( scalar(@n) >= $gd ) {
my $piv = $n[0]/$rd->[0];
push @q, $piv;
$n[$_] -= $rd->[$_] * $piv foreach ( 0 .. min(scalar(@n), $gd)-1 );
shift @n;
}
return ( \@q, \@n );
} else {
return ( [0], $rn );
}
} |
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.
| #Nim | Nim | import lenientops, sequtils, stats, strformat
proc polyRegression(x, y: openArray[int]) =
let xm = mean(x)
let ym = mean(y)
let x2m = mean(x.mapIt(it * it))
let x3m = mean(x.mapIt(it * it * it))
let x4m = mean(x.mapIt(it * it * it * it))
let xym = mean(zip(x, y).mapIt(it[0] * it[1]))
let x2ym = mean(zip(x, y).mapIt(it[0] * it[0] * it[1]))
let sxx = x2m - xm * xm
let sxy = xym - xm * ym
let sxx2 = x3m - xm * x2m
let sx2x2 = x4m - x2m * x2m
let sx2y = x2ym - x2m * ym
let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let a = ym - b * xm - c * x2m
func abc(x: int): float = a + b * x + c * x * x
echo &"y = {a} + {b}x + {c}x²\n"
echo " Input Approximation"
echo " x y y1"
for (xi, yi) in zip(x, y):
echo &"{xi:2} {yi:3} {abc(xi):5}"
let x = toSeq(0..10)
let 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.
| #GAP | GAP | # Built-in
Combinations([1, 2, 3]);
# [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]
# Note that it handles duplicates
Combinations([1, 2, 3, 1]);
# [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ],
# [ 2 ], [ 2, 3 ], [ 3 ] ] |
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
| #Common_Lisp | Common Lisp | (defun primep (n)
"Is N prime?"
(and (> n 1)
(or (= n 2) (oddp n))
(loop for i from 3 to (isqrt n) by 2
never (zerop (rem n i))))) |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Julia | Julia |
const PFCUT = [6:5:101]//100
const PFVAL = [10:8:26, 32:6:50, 54:4:98, 100]//100
function pricefraction{T<:FloatingPoint}(a::T)
zero(T) <= a || error("a = ", a, ", but it must be >= 0.")
a <= one(T) || error("a = ", a, ", but it must be <= 1.")
convert(T, PFVAL[findfirst(a .< PFCUT)])
end
test = [0.:0.05:1., 0.51, 0.56, 0.61, rand(), rand(), rand(), rand()]
println("Testing the price fraction function")
for t in test
println(@sprintf " %.4f -> %.4f" t pricefraction(t))
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
| #PARI.2FGP | PARI/GP | proper(n)=if(n==1, [], my(d=divisors(n)); d[2..#d]);
apply(proper, [1..10])
r=at=0; for(n=1,20000, t=numdiv(n); if(t>r, r=t; at=n)); [at, numdiv(t)-1] |
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)
| #Stata | Stata | clear
mata
letters="aleph","beth","gimel","daleth","he","waw","zayin","heth"
a=letters[rdiscrete(10000,1,(1/5,1/6,1/7,1/8,1/9,1/10,1/11,1759/27720))]'
st_addobs(10000)
st_addvar("str10","a")
st_sstore(.,.,a)
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)
| #Tcl | Tcl | package require Tcl 8.5
set map [dict create]
set sum 0.0
foreach name {aleph beth gimel daleth he waw zayin} \
prob {1/5.0 1/6.0 1/7.0 1/8.0 1/9.0 1/10.0 1/11.0} \
{
set prob [expr $prob]
set sum [expr {$sum + $prob}]
dict set map $name [dict create probability $prob limit $sum count 0]
}
dict set map heth [dict create probability [expr {1.0 - $sum}] limit 1.0 count 0]
set samples 1000000
for {set i 0} {$i < $samples} {incr i} {
set n [expr {rand()}]
foreach name [dict keys $map] {
if {$n <= [dict get $map $name limit]} {
set count [dict get $map $name count]
dict set map $name count [incr count]
break
}
}
}
puts "using $samples samples:"
puts [format "%-10s %-21s %-9s %s" "" expected actual difference]
dict for {name submap} $map {
dict with submap {
set actual [expr {$count * 1.0 / $samples}]
puts [format "%-10s %-21s %-9s %4.2f%%" $name $probability $actual \
[expr {abs($actual - $probability)/$probability*100.0}]
]
}
} |
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.
| #Picat | Picat | main =>
Tasks = [[3,"Clear drains"],
[4,"Feed cat"],
[5,"Make tea"],
[1,"Solve RC tasks"],
[2,"Tax return"]],
Heap = new_min_heap([]),
foreach(Task in Tasks)
Heap.heap_push(Task),
println(top=Heap.heap_top())
end,
nl,
println(Heap),
println(size=Heap.heap_size),
nl,
println("Pop the elements from the queue:"),
println([Heap.heap_pop() : _ in 1..Heap.heap_size]). |
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
| #Go | Go | package main
import (
"fmt"
"math/big"
)
var (
ZERO = big.NewInt(0)
ONE = big.NewInt(1)
)
func Primes(n *big.Int) []*big.Int {
res := []*big.Int{}
mod, div := new(big.Int), new(big.Int)
for i := big.NewInt(2); i.Cmp(n) != 1; {
div.DivMod(n, i, mod)
for mod.Cmp(ZERO) == 0 {
res = append(res, new(big.Int).Set(i))
n.Set(div)
div.DivMod(n, i, mod)
}
i.Add(i, ONE)
}
return res
}
func main() {
vals := []int64{
1 << 31,
1234567,
333333,
987653,
2 * 3 * 5 * 7 * 11 * 13 * 17,
}
for _, v := range vals {
fmt.Println(v, "->", Primes(big.NewInt(v)))
}
} |
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.
| #zkl | zkl | fcn f(r){r.inc()} r:= Ref(1); f(r); r.value; //-->2 |
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #LiveCode | LiveCode |
on plotGraphic
local tCoordinates
local x = "0, 1, 2, 3, 4, 5, 6, 7, 8, 9"
local y = "2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0"
if there is a graphic "graph" then delete graphic "graph"
repeat with i = 1 to the number of items of x
put item i of x into item 1 of line i of tCoordinates
put item i of y into item 2 of line i of tCoordinates
end repeat
create graphic "graph"
set the style of graphic "graph" to "polygon"
set the points of graphic "graph" to tCoordinates
repeat with i = 1 to the number of lines of tCoordinates
put the top of grc "graph" + the height of grc "graph" - item 2 of line i of tCoordinates into item 2 of line i of tCoordinates
end repeat
set the points of graphic "graph" to tCoordinates
set the height of graphic "graph" to 200
set the width of graphic "graph" to 300
set the loc of grc "graph" to the loc of this card
end plotGraphic
|
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.
| #Lua | Lua |
w_width = love.graphics.getWidth()
w_height = love.graphics.getHeight()
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 = {24,24}
points = {}
x_unit = w_width/x[10]/2
y_unit = w_height/10
--add points to an array properly formatted for the line function
for i=1,10,1 do
table.insert(points, (x[i]*x_unit) + origin[1])
table.insert(points, (w_height-(y[i]*2)) - origin[2])
end
function love.draw()
--draw axes and grid
love.graphics.setColor(0, 0.8, 0)
--draw x axis
love.graphics.line(origin[1], w_height-origin[2], w_width, w_height-origin[2])
--draw y axis
love.graphics.line(origin[1], w_height-origin[2], origin[1], origin[2])
--draw grid
for i=1,20,1 do
love.graphics.line(origin[1], (w_height-origin[2])-(i*y_unit), w_width, (w_height-origin[2])-(i*y_unit))
love.graphics.line(origin[1]+(i*x_unit), origin[2], origin[1]+(i*x_unit), w_height-origin[2])
end
--draw line plot
love.graphics.setColor(0.8, 0, 0)
love.graphics.line(points)
--draw labels
love.graphics.setColor(0.8, 0.8, 0.8)
for i=0,9,1 do
--draw x axis labels
love.graphics.print(i, (x_unit*i) + origin[1], love.graphics.getHeight()-origin[2])
--draw y axis labels
love.graphics.print(i*y_unit/2, origin[1], ((love.graphics.getHeight()-i*y_unit)-origin[2]))
end
end
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.