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/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Wren | Wren | import "/fmt" for Fmt
var areSame = Fn.new { |a, b|
for (i in 0...a.count) if (a[i] != b[i]) return false
return true
}
var perfectShuffle = Fn.new { |a|
var n = a.count
var b = List.filled(n, 0)
var hSize = (n/2).floor
for (i in 0...hSize) b[i * 2] = a[i]
var j = 1
for (i in hSize...n) {
b[j] = a[i]
j = j + 2
}
return b
}
var countShuffles = Fn.new { |a|
var n = a.count
if (n < 2 || n % 2 == 1) Fiber.abort("Array must be even-sized and non-empty.")
var b = a
var count = 0
while (true) {
var c = perfectShuffle.call(b)
count = count + 1
if (areSame.call(a, c)) return count
b = c
}
}
System.print("Deck size Num shuffles")
System.print("--------- ------------")
var sizes = [8, 24, 52, 100, 1020, 1024, 10000]
for (size in sizes) {
var a = List.filled(size, 0)
for (i in 1...size) a[i] = i
var count = countShuffles.call(a)
Fmt.print("$-9d $d", size, count)
} |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Picat | Picat | go =>
% Create and print the deck
deck(Deck),
print_deck(Deck),
nl,
% Shuffle the deck
print_deck(shuffle(Deck)),
nl,
% Deal 3 cards
Deck := deal(Deck,Card1),
Deck := deal(Deck,Card2),
Deck := deal(Deck,Card3),
println(deal1=Card1),
println(deal2=Card2),
println(deal3=Card3),
% The remaining deck
print_deck(Deck),
nl,
% Deal 5 cards
Deck := deal(Deck,Card4),
Deck := deal(Deck,Card5),
Deck := deal(Deck,Card6),
Deck := deal(Deck,Card7),
Deck := deal(Deck,Card8),
println(cards4_to_8=[Card4,Card5,Card6,Card7,Card8]),
nl,
% Deal 5 cards
Deck := deal_n(Deck,5,FiveCards),
println(fiveCards=FiveCards),
print_deck(Deck),
nl,
% And deal some more cards
% This chaining works since deal/1 returns the remaining deck
Deck := Deck.deal(Card9).deal(Card10).deal(Card11).deal(Card12),
println("4_more_cards"=[Card9,Card10,Card11,Card12]),
print_deck(Deck),
nl.
% suits(Suits) => Suits = ["♠","♥","♦","♣"].
suits(Suits) => Suits = ["C","H","S","D"].
values(Values) => Values = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"].
% Create a (sorted) deck.
deck(Deck) =>
suits(Suits),
values(Values),
Deck =[S++V :V in Values, S in Suits].sort().
% Shuffle a deck
shuffle(Deck) = Deck2 =>
Deck2 = Deck,
Len = Deck2.length,
foreach(I in 1..Len)
R2 = random(1,Len),
Deck2 := swap(Deck2,I,R2)
end.
% Swap position I <=> J in list L
swap(L,I,J) = L2, list(L) =>
L2 = L,
T = L2[I],
L2[I] := L2[J],
L2[J] := T.
% The first card is returned as the out parameter Card.
% The deck is returned as the function value.
deal(Deck, Card) = Deck.tail() => Card = Deck.first().
% Deal N cards
deal_n(Deck, N, Cards) = [Deck[I] : I in Len+1..Deck.length] =>
Len = min(N,Deck.length),
Cards = [Deck[I] : I in 1..Len].
% Print deck
print_deck(Deck) =>
println("Deck:"),
foreach({Card,I} in zip(Deck,1..Deck.len))
printf("%w ", Card),
if I mod 10 == 0 then
nl
end
end,
nl. |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Swift | Swift |
//
// main.swift
// pi digits
//
// Created by max goren on 11/11/21.
// Copyright © 2021 maxcodes. All rights reserved.
//
import Foundation
var r = [Int]()
var i = 0
var k = 2800
var b = 0
var c = 0
var d = 0
for _ in 0...2800 {
r.append(2000);
}
while k > 0 {
d = 0;
i = k;
while (true) {
d = d + r[i] * 10000
b = 2 * i - 1
r[i] = d % b
d = d / b
i = i - 1
if i == 0 {
break;
}
d = d * i;
}
print(c + d / 10000, "")
c = d % 10000
k = k - 14
}
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Ruby | Ruby | require "prime"
class Integer
def popcount
to_s(2).count("1") #Ruby 2.4: digits(2).count(1)
end
def pernicious?
popcount.prime?
end
end
p 1.step.lazy.select(&:pernicious?).take(25).to_a
p ( 888888877..888888888).select(&:pernicious?) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #VBScript | VBScript | Function pick_random(arr)
Set objRandom = CreateObject("System.Random")
pick_random = arr(objRandom.Next_2(0,UBound(arr)+1))
End Function
WScript.Echo pick_random(Array("a","b","c","d","e","f")) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main()
Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
Dim rng As New Random()
Dim randomElement = list(rng.Next(list.Count)) ' Upper bound is exclusive.
Console.WriteLine("I picked element {0}", randomElement)
End Sub
End Module |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #GAP | GAP | Filtered([1 .. 10000], n -> Sum(DivisorsInt(n)) = 2*n);
# [ 6, 28, 496, 8128 ] |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #FreeBASIC | FreeBASIC | ' version 07-04-2017
' compile with: fbc -s console
' Heap's algorithm non-recursive
Sub perms(n As Long)
Dim As ULong i, j, count = 1
Dim As ULong a(0 To n -1), c(0 To n -1)
For j = 0 To n -1
a(j) = j +1
Print a(j);
Next
Print " ";
i = 0
While i < n
If c(i) < i Then
If (i And 1) = 0 Then
Swap a(0), a(i)
Else
Swap a(c(i)), a(i)
End If
For j = 0 To n -1
Print a(j);
Next
count += 1
If count = 12 Then
Print
count = 0
Else
Print " ";
End If
c(i) += 1
i = 0
Else
c(i) = 0
i += 1
End If
Wend
End Sub
' ------=< MAIN >=------
perms(4)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #XPL0 | XPL0 | int Deck(10000), Deck0(10000);
int Cases, Count, Test, Size, I;
proc Shuffle; \Do perfect shuffle of Deck0 into Deck
int DeckLeft, DeckRight;
int I;
[DeckLeft:= Deck0;
DeckRight:= Deck0 + Size*4/2; \4 bytes per integer
for I:= 0 to Size-1 do
Deck(I):= if I&1 then DeckRight(I/2)
else DeckLeft(I/2);
];
[Cases:= [8, 24, 52, 100, 1020, 1024, 10000];
for Test:= 0 to 7-1 do
[Size:= Cases(Test);
for I:= 0 to Size-1 do Deck(I):= I;
Count:= 0;
repeat for I:= 0 to Size-1 do Deck0(I):= Deck(I);
Shuffle;
Count:= Count+1;
for I:= 0 to Size-1 do
if Deck(I) # I then I:= Size;
until I = Size; \equal starting configuration
IntOut(0, Size); ChOut(0, 9\tab\); IntOut(0, Count); CrLf(0);
];
] |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #PicoLisp | PicoLisp | (de *Suits
Club Diamond Heart Spade )
(de *Pips
Ace 2 3 4 5 6 7 8 9 10 Jack Queen King )
(de mkDeck ()
(mapcan
'((Pip) (mapcar cons *Suits (circ Pip)))
*Pips ) )
(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) ) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Pascal | Pascal | Program Pi_Spigot;
const
n = 1000;
len = 10*n div 3;
var
j, k, q, nines, predigit: integer;
a: array[0..len] of longint;
function OneLoop(i:integer):integer;
var
x: integer;
begin
{Only calculate as far as needed }
{+16 for security digits ~5 decimals}
i := i*10 div 3+16;
IF i > len then
i := len;
result := 0;
repeat {Work backwards}
x := 10*a[i] + result*i;
result := x div (2*i - 1);
a[i] := x - result*(2*i - 1);//x mod (2*i - 1)
dec(i);
until i<= 0 ;
end;
begin
for j := 1 to len do
a[j] := 2; {Start with 2s}
nines := 0;
predigit := 0; {First predigit is a 0}
for j := 1 to n do
begin
q := OneLoop(n-j);
a[1] := q mod 10;
q := q div 10;
if q = 9 then
nines := nines + 1
else
if q = 10 then
begin
write(predigit+1);
for k := 1 to nines do
write(0); {zeros}
predigit := 0;
nines := 0
end
else
begin
write(predigit);
predigit := q;
if nines <> 0 then
begin
for k := 1 to nines do
write(9);
nines := 0
end
end
end;
writeln(predigit);
end. |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Rust | Rust |
extern crate aks_test_for_primes;
use std::iter::Filter;
use std::ops::RangeFrom;
use aks_test_for_primes::is_prime;
fn main() {
for i in pernicious().take(25) {
print!("{} ", i);
}
println!();
for i in (888_888_877u64..888_888_888).filter(is_pernicious) {
print!("{} ", i);
}
}
fn pernicious() -> Filter<RangeFrom<u64>, fn(&u64) -> bool> {
(0u64..).filter(is_pernicious as fn(&u64) -> bool)
}
fn is_pernicious(n: &u64) -> bool {
is_prime(n.count_ones())
}
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #S-lang | S-lang | % Simplistic prime-test from prime-by-trial-division:
define is_prime(n)
{
if (n <= 1) return(0);
if (n == 2) return(1);
if ((n & 1) == 0) return(0);
variable mx = int(sqrt(n)), i;
_for i (3, mx, 1) {
if ((n mod i) == 0)
return(0);
}
return(1);
}
define population(n)
{
variable pc = 0;
do {
if (n & 1) pc++;
n /= 2;
}
while (n);
return(pc);
}
define is_pernicious(n)
{
return(is_prime(population(n)));
}
variable plist = {}, n = 0;
while (length(plist) < 25) {
n++;
if (is_pernicious(n))
list_append(plist, string(n));
}
print(strjoin(list_to_array(plist), " "));
plist = {};
_for n (888888877, 888888888, 1) {
if (is_pernicious(n))
list_append(plist, string(n));
}
print(strjoin(list_to_array(plist), " "));
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Wren | Wren | import "random" for Random
var rand = Random.new()
var colors = ["red", "green", "blue", "yellow", "pink"]
for (i in 0..4) System.print(colors[rand.int(colors.count)]) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #XBS | XBS | set Array = ["Hello","World",1,2,3];
log(Array[rnd(0,?Array-1)]); |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Go | Go | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
// following function satisfies the task, returning true for all
// perfect numbers representable in the argument type
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
// validation
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Frink | Frink | a = [1,2,3,4]
println[formatTable[a.lexicographicPermute[]]] |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #zkl | zkl | fcn perfectShuffle(numCards){
deck,shuffle,n,N:=numCards.pump(List),deck,0,numCards/2;
do{ shuffle=shuffle[0,N].zip(shuffle[N,*]).flatten(); n+=1 }
while(deck!=shuffle);
n
}
foreach n in (T(8,24,52,100,1020,1024,10000)){
println("%5d : %d".fmt(n,perfectShuffle(n)));
} |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #PowerShell | PowerShell |
<#
.Synopsis
Creates a new "Deck" which is a hashtable converted to a dictionary
This is only used for creating the deck, to view/list the deck contents use Get-Deck.
.DESCRIPTION
Casts the string value that the user inputs to the name of the variable that holds the "deck"
Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
multiple decks under different names.
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck
cmdlet New-Deck at command pipeline position 1
Supply values for the following parameters:
YourDeckName: Deck1
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck3
PS C:\WINDOWS\system32>
#>
function New-Deck
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Name your Deck, this will be the name of the variable that holds your deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$False,
Position=0)]$YourDeckName
)
Begin
{
$Suit = @(' of Hearts', ' of Spades', ' of Diamonds', ' of Clubs')
$Pip = @('Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2')
#Creates the hash table that will hold the suit and pip variables
$Deck = @{}
#creates counters for the loop below to make 52 total cards with 13 cards per suit
[int]$SuitCounter = 0
[int]$PipCounter = 0
[int]$CardValue = 0
}
Process
{
#Creates the initial deck
do
{
#card2add is the rows in the hashtable
$Card2Add = ($Pip[$PipCounter]+$Suit[$SuitCounter])
#Addes the row to the hashtable
$Deck.Add($CardValue, $Card2Add)
#Used to create the Keys
$CardValue++
#Counts the amount of cards per suit
$PipCounter ++
if ($PipCounter -eq 13)
{
#once reached the suit is changed
$SuitCounter++
#and the per-suit counter is reset
$PipCounter = 0
}
else
{
continue
}
}
#52 cards in a deck
until ($Deck.count -eq 52)
}
End
{
#sets the name of a variable that is unknown
#Then converts the hash table to a dictionary and pipes it to the Get-Random cmdlet with the arguments to randomize the contents
Set-Variable -Name "$YourDeckName" -Value ($Deck.GetEnumerator() | Get-Random -Count ([int]::MaxValue)) -Scope Global
}
}
<#
.Synopsis
Lists the cards in your selected deck
.DESCRIPTION
Contains a Try-Catch-Finally block in case the deck requested has not been created
.EXAMPLE
PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck1
8 of Clubs
5 of Hearts
--Shortened--
King of Clubs
Jack of Diamonds
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck2
deck2 does not exist...
Creating Deck deck2...
Ace of Spades
10 of Hearts
--Shortened--
5 of Clubs
4 of Clubs
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> deck deck2
Ace of Spades
10 of Hearts
--Shortened--
4 of Spades
6 of Spades
Queen of Spades
PS C:\WINDOWS\system32>
#>
function Get-Deck
{
[CmdletBinding()]
[Alias('Deck')]
[OutputType([int])]
Param
(
#Brings the Vairiable in from Get-Deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName
)
Begin
{
}
Process
{
# Will return a terminal error if the deck has not been created
try
{
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
}
catch
{
Write-Host
Write-Host "$YourDeckName does not exist..."
Write-Host "Creating Deck $YourDeckName..."
New-Deck -YourDeckName $YourDeckName
$temp = Get-Variable -name "$YourDeckName" -ValueOnly
}
finally
{
$temp | select Value | ft -HideTableHeaders
}
}
End
{
Write-Verbose "End of show-deck function"
}
}
<#
.Synopsis
Shuffles a deck of your selection with Get-Random
.DESCRIPTION
This function can be used to Shuffle any deck that has been created.
This can be used on a deck that has less than 52 cards
Contains a Try-Catch-Finally block in case the deck requested has not been created
Does NOT output the value of the deck being shuffled (You wouldn't look at the cards you shuffled, would you?)
.EXAMPLE
PS C:\WINDOWS\system32> Shuffle-Deck -YourDeckName Deck1
Your Deck was shuffled
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> Shuffle NotMadeYet
NotMadeYet does not exist...
Creating and shuffling NotMadeYet...
Your Deck was shuffled
PS C:\WINDOWS\system32>
#>
function Shuffle-Deck
{
[CmdletBinding()]
[Alias('Shuffle')]
[OutputType([int])]
Param
(
#The Deck you want to shuffle
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName)
Begin
{
Write-Verbose 'Shuffles your deck with Get-Random'
}
Process
{
# Will return a missing variable error if the deck has net been created
try
{
#These two commands could be on one line using the pipeline, but look cleaner on two
$temp1 = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
$temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)
}
catch
{
Write-Host
Write-Host "$YourDeckName does not exist..."
Write-Host "Creating and shuffling $YourDeckName..."
New-Deck -YourDeckName $YourDeckName
$temp1 = Get-Variable -name "$YourDeckName" -ValueOnly
$temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)
}
finally
{
#Gets the actual value of variable $YourDeckName from the New-Deck function and uses that string value
#to set the variables name
Set-Variable -Name "$YourDeckName" -value ($temp1) -Scope Global
}
}
End
{
Write-Host "Your Deck was shuffled"
}
}
<#
.Synopsis
Creates a new "Hand" which is a hashtable converted to a dictionary
This is only used for creating the hand, to view/list the deck contents use Get-Hand.
.DESCRIPTION
Casts the string value that the user inputs to the name of the variable that holds the "hand"
Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
multiple hands under different names.
.EXAMPLE
PS C:\WINDOWS\system32> New-Hand -YourHandName JohnDoe
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> New-Hand JaneDoe
PS C:\WINDOWS\system32>
>
#>
function New-Hand
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Name your Deck, this will be the name of the variable that holds your deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$False,
Position=0)]$YourHandName
)
Begin
{
$Hand = @{}
}
Process
{
}
End
{
Set-Variable -Name "$YourHandName" -Value ($Hand.GetEnumerator()) -Scope Global
}
}
<#
.Synopsis
Lists the cards in the selected Hand
.DESCRIPTION
Contains a Try-Catch-Finally block in case the hand requested has not been created
.EXAMPLE
#create a new hand
PS C:\WINDOWS\system32> New-Hand -YourHandName Hand1
PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand1
Hand1's hand contains cards, they are...
PS C:\WINDOWS\system32>
#This hand is empty
.EXAMPLE
PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand2
Hand2 does not exist...
Creating Hand Hand2...
Hand2's hand contains cards, they are...
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> hand hand3
hand3's hand contains 4 cards, they are...
5 of Spades
4 of Spades
6 of Spades
Queen of Diamonds
#>
function Get-Hand
{
[CmdletBinding()]
[Alias('Hand')]
[OutputType([int])]
Param
(
#Brings the Vairiable in from Get-Deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourHandName
)
Begin
{
}
Process
{
# Will return a missing variable error if the deck has net been created
try
{
$temp = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction stop
}
catch
{
Write-Host
Write-Host "$YourHandName does not exist..."
Write-Host "Creating Hand $YourHandName..."
New-Hand -YourHandName $YourHandName
$temp = Get-Variable -name "$YourHandName" -ValueOnly
}
finally
{
$count = $temp.count
Write-Host "$YourHandName's hand contains $count cards, they are..."
$temp | select Value | ft -HideTableHeaders
}
}
End
{
Write-Verbose "End of show-deck function"
}
}
<#
.Synopsis
Draws/returns cards
.DESCRIPTION
Draws/returns cards from your chosen deck , to your chosen hand
Can be used without creating a deck or hand first
.EXAMPLE
PS C:\WINDOWS\system32> DrawFrom-Deck -YourDeckName Deck1 -YourHandName test1 -HowManyCardsToDraw 10
PS C:\WINDOWS\system32>
.EXAMPLE
DrawFrom-Deck -YourDeckName Deck2 -YourHandName test2 -HowManyCardsToDraw 10
Deck2 does not exist...
Creating Deck Deck2...
test2 does not exist...
Creating Hand test2...
test2's hand contains cards, they are...
.EXAMPLE
PS C:\WINDOWS\system32> draw -YourDeckName deck1 -YourHandName test1 -HowManyCardsToDraw 5
#>
function Draw-Deck
{
[CmdletBinding()]
[Alias('Draw')]
[OutputType([int])]
Param
(
# The Deck in which you want to draw cards out of
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName,
#The hand in which you want to draw cards to
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourHandName,
#Quanity of cards being drawn
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$HowManyCardsToDraw
)
Begin
{
Write-Verbose "Draws a chosen amount of cards from the chosen deck"
#try-catch-finally blocks so the user does not have to use New-Deck and New-Hand beforehand.
try
{
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
}
catch
{
Get-Deck -YourDeckName $YourDeckName
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
}
finally
{
Write-Host
}
try
{
$temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
}
catch
{
Get-Hand -YourHandName $YourHandName
$temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
}
finally
{
Write-Host
}
}
Process
{
Write-Host "you drew $HowManyCardsToDraw cards, they are..."
$handValues = Get-Variable -name "$YourDeckName" -ValueOnly
$handValues = $handValues[0..(($HowManyCardsToDraw -1))] | select value | ft -HideTableHeaders
$handValues
}
End
{
#sets the new values for the deck and the hand selected
Set-Variable -Name "$YourDeckName" -value ($temp[$HowManyCardsToDraw..($temp.count)]) -Scope Global
Set-Variable -Name "$YourHandName" -value ($temp2 + $handValues) -Scope Global
}
}
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Perl | Perl | sub pistream {
my $digits = shift;
my(@out, @a);
my($b, $c, $d, $e, $f, $g, $i, $d4, $d3, $d2, $d1);
my $outi = 0;
$digits++;
$b = $d = $e = $g = $i = 0;
$f = 10000;
$c = 14 * (int($digits/4)+2);
@a = (20000000) x $c;
print "3.";
while (($b = $c -= 14) > 0 && $i < $digits) {
$d = $e = $d % $f;
while (--$b > 0) {
$d = $d * $b + $a[$b];
$g = ($b << 1) - 1;
$a[$b] = ($d % $g) * $f;
$d = int($d / $g);
}
$d4 = $e + int($d/$f);
if ($d4 > 9999) {
$d4 -= 10000;
$out[$i-1]++;
for ($b = $i-1; $out[$b] == 1; $b--) {
$out[$b] = 0;
$out[$b-1]++;
}
}
$d3 = int($d4/10);
$d2 = int($d3/10);
$d1 = int($d2/10);
$out[$i++] = $d1;
$out[$i++] = $d2-$d1*10;
$out[$i++] = $d3-$d2*10;
$out[$i++] = $d4-$d3*10;
print join "", @out[$i-15 .. $i-15+3] if $i >= 16;
}
# We've closed the spigot. Print the remainder without rounding.
print join "", @out[$i-15+4 .. $digits-2], "\n";
} |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Scala | Scala | def isPernicious( v:Long ) : Boolean = BigInt(v.toBinaryString.toList.filter( _ == '1' ).length).isProbablePrime(16)
// Generate the output
{
val (a,b1,b2) = (25,888888877L,888888888L)
println( Stream.from(2).filter( isPernicious(_) ).take(a).toList.mkString(",") )
println( {for( i <- b1 to b2 if( isPernicious(i) ) ) yield i}.mkString(",") )
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #XPL0 | XPL0 | code Ran=1, Text=12;
int List;
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"]; \(Thanks REXX)
Text(0, List(Ran(5)));
] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Zig | Zig | const std = @import("std");
const debug = std.debug;
const rand = std.rand;
const time = std.time;
test "pick random element" {
var pcg = rand.Pcg.init(time.milliTimestamp());
const chars = [_]u8{
'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X',
'Y', 'Z', '?', '!',
'<', '>', '(', ')',
};
var i: usize = 0;
while (i < 32) : (i += 1) {
if (i % 4 == 0) {
debug.warn("\n ", .{});
}
debug.warn("'{c}', ", .{chars[pcg.random.int(usize) % chars.len]});
}
debug.warn("\n", .{});
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #zkl | zkl | list:=T("hydrogen", "helium", "lithium", "beryllium", "boron");
list[(0).random(list.len())] |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Groovy | Groovy | def isPerfect = { n ->
n > 4 && (n == (2..Math.sqrt(n)).findAll { n % it == 0 }.inject(1) { factorSum, i -> factorSum += i + n/i })
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #GAP | GAP | gap>List(SymmetricGroup(4), p -> Permuted([1 .. 4], p));
perms(4);
[ [ 1, 2, 3, 4 ], [ 4, 2, 3, 1 ], [ 2, 4, 3, 1 ], [ 3, 2, 4, 1 ], [ 1, 4, 3, 2 ], [ 4, 1, 3, 2 ], [ 2, 1, 3, 4 ],
[ 3, 1, 4, 2 ], [ 1, 3, 4, 2 ], [ 4, 3, 1, 2 ], [ 2, 3, 1, 4 ], [ 3, 4, 1, 2 ], [ 1, 2, 4, 3 ], [ 4, 2, 1, 3 ],
[ 2, 4, 1, 3 ], [ 3, 2, 1, 4 ], [ 1, 4, 2, 3 ], [ 4, 1, 2, 3 ], [ 2, 1, 4, 3 ], [ 3, 1, 2, 4 ], [ 1, 3, 2, 4 ],
[ 4, 3, 2, 1 ], [ 2, 3, 4, 1 ], [ 3, 4, 2, 1 ] ] |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Prolog | Prolog | /** <module> Cards
A card is represented by the term "card(Pip, Suit)".
A deck is represented internally as a list of cards.
Usage:
new_deck(D0), deck_shuffle(D0, D1), deck_deal(D1, C, D2).
*/
:- module(cards, [ new_deck/1, % -Deck
deck_shuffle/2, % +Deck, -NewDeck
deck_deal/3, % +Deck, -Card, -NewDeck
print_deck/1 % +Deck
]).
%% new_deck(-Deck)
new_deck(Deck) :-
Suits = [clubs, hearts, spades, diamonds],
Pips = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace],
setof(card(Pip, Suit), (member(Suit, Suits), member(Pip, Pips)), Deck).
%% deck_shuffle(+Deck, -NewDeck)
deck_shuffle(Deck, NewDeck) :-
length(Deck, NumCards),
findall(X, (between(1, NumCards, _I), X is random(1000)), Ord),
pairs_keys_values(Pairs, Ord, Deck),
keysort(Pairs, OrdPairs),
pairs_values(OrdPairs, NewDeck).
%% deck_deal(+Deck, -Card, -NewDeck)
deck_deal([Card|Cards], Card, Cards).
%% print_deck(+Deck)
print_deck(Deck) :-
maplist(print_card, Deck).
% print_card(+Card)
print_card(card(Pip, Suit)) :-
format('~a of ~a~n', [Pip, Suit]).
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Phix | Phix | with javascript_semantics
integer a=10000,b,c=8400,d,e=0,g sequence f=repeat(floor(a/5),c+1) while c>0 do g=2*c d=0
b=c while b>0 do d+=f[b]*a g-=1 f[b]=remainder(d, g) d=floor(d/g) g-=1 b-=1 if b!=0 then
d*=b end if end while printf(1,"%04d",e+floor(d/a)) c-=14 e = remainder(d,a) end while
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const set of integer: primes is {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61};
const func integer: popcount (in integer: number) is
return card(bitset(number));
const proc: main is func
local
var integer: num is 0;
var integer: count is 0;
begin
for num range 0 to integer.last until count >= 25 do
if popcount(num) in primes then
write(num <& " ");
incr(count);
end if;
end for;
writeln;
for num range 888888877 to 888888888 do
if popcount(num) in primes then
write(num <& " ");
end if;
end for;
writeln;
end func; |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Haskell | Haskell | perfect n =
n == sum [i | i <- [1..n-1], n `mod` i == 0] |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #HicEst | HicEst | DO i = 1, 1E4
IF( perfect(i) ) WRITE() i
ENDDO
END ! end of "main"
FUNCTION perfect(n)
sum = 1
DO i = 2, n^0.5
sum = sum + (MOD(n, i) == 0) * (i + INT(n/i))
ENDDO
perfect = sum == n
END |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Glee | Glee | $$ n !! k dyadic: Permutations for k out of n elements (in this case k = n)
$$ #s monadic: number of elements in s
$$ ,, monadic: expose with space-lf separators
$$ s[n] index n of s
'Hello' 123 7.9 '•'=>s;
s[s# !! (s#)],, |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #PureBasic | PureBasic | #MaxCards = 52 ;Max Cards in a deck
Structure card
pip.s
suit.s
EndStructure
Structure _membersDeckClass
*vtable.i
size.i ;zero based count of cards present
cards.card[#MaxCards] ;deck content
EndStructure
Interface deckObject
Init()
shuffle()
deal.s(isAbbr = #True)
show(isAbbr = #True)
EndInterface
Procedure.s _formatCardInfo(*card.card, isAbbr = #True)
;isAbbr determines if the card information is abbrieviated to 2 characters
Static pips.s = "2 3 4 5 6 7 8 9 10 Jack Queen King Ace"
Static suits.s = "Diamonds Clubs Hearts Spades"
Protected c.s
If isAbbr
c = *card\pip + *card\suit
Else
c = StringField(pips,FindString("23456789TJQKA", *card\pip, 1), " ") + " of "
c + StringField(suits,FindString("DCHS", *card\suit, 1)," ")
EndIf
ProcedureReturn c
EndProcedure
Procedure setInitialValues(*this._membersDeckClass)
Protected i, c.s
Restore cardDat
For i = 0 To #MaxCards - 1
Read.s c
*this\cards[i]\pip = Left(c, 1)
*this\cards[i]\suit = Right(c, 1)
Next
EndProcedure
Procedure.s dealCard(*this._membersDeckClass, isAbbr)
;isAbbr is #True if the card dealt is abbrieviated to 2 characters
Protected c.card
If *this\size < 0
;deck is empty
ProcedureReturn ""
Else
c = *this\cards[*this\size]
*this\size - 1
ProcedureReturn _formatCardInfo(@c, isAbbr)
EndIf
EndProcedure
Procedure showDeck(*this._membersDeckClass, isAbbr)
;isAbbr determines if cards are shown with 2 character abbrieviations
Protected i
For i = 0 To *this\size
Print(_formatCardInfo(@*this\cards[i], isAbbr))
If i <> *this\size: Print(", "): EndIf
Next
PrintN("")
EndProcedure
Procedure shuffle(*this._membersDeckClass)
;works with decks of any size
Protected w, i
Dim shuffled.card(*this\size)
For i = *this\size To 0 Step -1
w = Random(i)
shuffled(i) = *this\cards[w]
If w <> i
*this\cards[w] = *this\cards[i]
EndIf
Next
For i = 0 To *this\size
*this\cards[i] = shuffled(i)
Next
EndProcedure
Procedure newDeck()
Protected *newDeck._membersDeckClass = AllocateMemory(SizeOf(_membersDeckClass))
If *newDeck
*newDeck\vtable = ?vTable_deckClass
*newDeck\size = #MaxCards - 1
setInitialValues(*newDeck)
EndIf
ProcedureReturn *newDeck
EndProcedure
DataSection
vTable_deckClass:
Data.i @setInitialValues()
Data.i @shuffle()
Data.i @dealCard()
Data.i @showDeck()
cardDat:
Data.s "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AD"
Data.s "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AC"
Data.s "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH", "AH"
Data.s "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS", "AS"
EndDataSection
If OpenConsole()
Define deck.deckObject = newDeck()
Define deck2.deckObject = newDeck()
If deck = 0 Or deck2 = 0
PrintN("Unable to create decks")
End
EndIf
deck\shuffle()
PrintN("Dealt: " + deck\deal(#False))
PrintN("Dealt: " + deck\deal(#False))
PrintN("Dealt: " + deck\deal(#False))
PrintN("Dealt: " + deck\deal(#False))
deck\show()
deck2\show()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Picat | Picat | go =>
pi2(1,0,1,1,3,3,0),
nl.
pi2(Q,R,T,K,N,L,C) =>
if C == 50 then
nl,
pi2(Q,R,T,K,N,L,0)
else
if (4*Q + R-T) < (N*T) then
print(N),
P := 10*(R-N*T),
pi2(Q*10, P, T, K, ((10*(3*Q+R)) div T)-10*N, L,C+1)
else
P := (2*Q+R)*L,
M := (Q*(7*K)+2+(R*L)) div (T*L),
H := L+2,
J := K+ 1,
pi2(Q*K, P, T*L, J, M, H, C)
end
end,
nl. |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Sidef | Sidef | func is_pernicious(n) {
n.sumdigits(2).is_prime
}
say is_pernicious.first(25).join(' ')
say is_pernicious.grep(888_888_877..888_888_888).join(' ') |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
limit := \arglist[1] | 100000
write("Perfect numbers from 1 to ",limit,":")
every write(isperfect(1 to limit))
write("Done.")
end
procedure isperfect(n) #: returns n if n is perfect
local sum,i
every (sum := 0) +:= (n ~= divisors(n))
if sum = n then return n
end
link factors |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #GNU_make | GNU make |
#delimiter should not occur inside elements
delimiter=;
#convert list to delimiter separated string
implode=$(subst $() $(),$(delimiter),$(strip $1))
#convert delimiter separated string to list
explode=$(strip $(subst $(delimiter), ,$1))
#enumerate all permutations and subpermutations
permutations0=$(if $1,$(foreach x,$1,$x $(addprefix $x$(delimiter),$(call permutations0,$(filter-out $x,$1)))),)
#remove subpermutations from permutations0 output
permutations=$(strip $(foreach x,$(call permutations0,$1),$(if $(filter $(words $1),$(words $(call explode,$x))),$(call implode,$(call explode,$x)),)))
delimiter_separated_output=$(call permutations,a b c d)
$(info $(delimiter_separated_output))
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Python | Python | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class Deck(object):
def __init__(self):
self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]
def __str__(self):
return "[%s]"%", ".join( (str(card) for card in self.deck))
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.shuffle() # Can't tell what is next from self.deck
return self.deck.pop(0) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de piDigit ()
(job '((Q . 1) (R . 0) (S . 1) (K . 1) (N . 3) (L . 3))
(while (>= (- (+ R (* 4 Q)) S) (* N S))
(mapc set '(Q R S K N L)
(list
(* Q K)
(* L (+ R (* 2 Q)))
(* S L)
(inc K)
(/ (+ (* Q (+ 2 (* 7 K))) (* R L)) (* S L))
(+ 2 L) ) ) )
(prog1 N
(let M (- (/ (* 10 (+ R (* 3 Q))) S) (* 10 N))
(setq Q (* 10 Q) R (* 10 (- R (* N S))) N M) ) ) ) )
(prin (piDigit) ".")
(loop
(prin (piDigit))
(flush) ) |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
return true
}
}
public func populationCount(n: Int) -> Int {
guard n >= 0 else {
return 0
}
return String(n, radix: 2).lazy.filter({ $0 == "1" }).count
}
let first25 = (1...).lazy.filter({ populationCount(n: $0).isPrime }).prefix(25)
let rng = (888_888_877...888_888_888).lazy.filter({ populationCount(n: $0).isPrime })
print("First 25 Pernicious numbers: \(Array(first25))")
print("Pernicious numbers between 888_888_877...888_888_888: \(Array(rng))") |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Symsyn | Symsyn |
primes : 0b0010100000100000100010100010000010100000100010100010100010101100
| the first 25 pernicious numbers
$T | clear string
num_pn | set to zero
2 n | start at 2
5 hi_bit
if num_pn LT 25
call popcount | count ones
if primes bit pop_cnt | if pop_cnt bit of bit vector primes is one
+ num_pn | inc number of pernicious numbers
~ n $S | convert to decimal string
+ ' ' $S | pad a space
+ $S $T | add to string $T
endif
+ pop_cnt | next number (odd) has one more bit than previous (even)
+ n | next number
if primes bit pop_cnt
+ num_pn
~ n $S
+ ' ' $S
+ $S $T
endif
+ n
goif | go back to if
endif
$T [] | display numbers
| pernicious numbers in range 888888877 .. 888888888
$T | clear string
num_pn | set to zero
888888876 n | start at 888888876
29 hi_bit
if n LE 888888888
call popcount | count ones
if primes bit pop_cnt | if pop_cnt bit of bit vector primes is one
+ num_pn | inc number of pernicious numbers
~ n $S | convert to decimal string
+ ' ' $S | pad a space
+ $S $T | add to string $T
endif
+ pop_cnt | next number (odd) has one more bit than previous (even)
+ n | next number
if primes bit pop_cnt
+ num_pn
~ n $S
+ ' ' $S
+ $S $T
endif
+ n
goif | go back to if
endif
$T [] | display numbers
stop
popcount | count ones in bit field
pop_cnt | pop_cnt to zero
1 bit_num | only count even numbers so skip bit 0
if bit_num LE hi_bit
if n bit bit_num
+ pop_cnt
endif
+ bit_num
goif
endif
return
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #J | J | is_perfect=: +: = >:@#.~/.~&.q:@(6>.<.) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Java | Java | public static boolean perf(int n){
int sum= 0;
for(int i= 1;i < n;i++){
if(n % i == 0){
sum+= i;
}
}
return sum == n;
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Go | Go | package main
import "fmt"
func main() {
demoPerm(3)
}
func demoPerm(n int) {
// create a set to permute. for demo, use the integers 1..n.
s := make([]int, n)
for i := range s {
s[i] = i + 1
}
// permute them, calling a function for each permutation.
// for demo, function just prints the permutation.
permute(s, func(p []int) { fmt.Println(p) })
}
// permute function. takes a set to permute and a function
// to call for each generated permutation.
func permute(s []int, emit func([]int)) {
if len(s) == 0 {
emit(s)
return
}
// Steinhaus, implemented with a recursive closure.
// arg is number of positions left to permute.
// pass in len(s) to start generation.
// on each call, weave element at pp through the elements 0..np-2,
// then restore array to the way it was.
var rc func(int)
rc = func(np int) {
if np == 1 {
emit(s)
return
}
np1 := np - 1
pp := len(s) - np1
// weave
rc(np1)
for i := pp; i > 0; i-- {
s[i], s[i-1] = s[i-1], s[i]
rc(np1)
}
// restore
w := s[0]
copy(s, s[1:pp+1])
s[pp] = w
}
rc(len(s))
} |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Quackery | Quackery | /O> newpack +jokers 3 riffles 4 players 7 deal
... say "The player's hands..." cr cr
... witheach [ echohand cr ]
... say "Cards left in the pack (the talon)..." cr cr
... echohand
...
The player's hands...
eight of hearts
seven of clubs
nine of hearts
two of diamonds
three of diamonds
three of hearts
seven of spades
low joker
ace of hearts
ace of clubs
queen of diamonds
nine of clubs
six of spades
six of diamonds
ten of diamonds
five of spades
jack of diamonds
two of hearts
two of clubs
five of diamonds
ten of clubs
ace of diamonds
ace of spades
eight of clubs
king of diamonds
four of diamonds
ten of hearts
three of clubs
Cards left in the pack (the talon)...
eight of spades
four of hearts
jack of hearts
four of clubs
nine of spades
ten of spades
two of spades
five of hearts
seven of diamonds
five of clubs
jack of clubs
eight of diamonds
six of hearts
queen of hearts
three of spades
nine of diamonds
six of clubs
queen of clubs
four of spades
seven of hearts
jack of spades
queen of spades
king of hearts
king of spades
king of clubs
high joker
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #PL.2FI | PL/I | /* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
/* for the Digits of Pi". */
(subrg, fofl, size):
Pi_Spigot: procedure options (main); /* 21 January 2012. */
declare (n, len) fixed binary;
n = 1000;
len = 10*n / 3;
begin;
declare ( i, j, k, q, nines, predigit ) fixed binary;
declare x fixed binary (31);
declare a(len) fixed binary (31);
a = 2; /* Start with 2s */
nines, predigit = 0; /* First predigit is a 0 */
do j = 1 to n;
q = 0;
do i = len to 1 by -1; /* Work backwards */
x = 10*a(i) + q*i;
a(i) = mod (x, (2*i-1));
q = x / (2*i-1);
end;
a(1) = mod(q, 10); q = q / 10;
if q = 9 then nines = nines + 1;
else if q = 10 then
do;
put edit(predigit+1) (f(1));
do k = 1 to nines;
put edit ('0')(a(1)); /* zeros */
end;
predigit, nines = 0;
end;
else
do;
put edit(predigit) (f(1)); predigit = q;
do k = 1 to nines; put edit ('9')(a(1)); end;
nines = 0;
end;
end;
put edit(predigit) (f(1));
end; /* of begin block */
end Pi_Spigot; |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Tcl | Tcl | package require math::numtheory
proc pernicious {n} {
::math::numtheory::isprime [tcl::mathop::+ {*}[split [format %b $n] ""]]
}
for {set n 0;set p {}} {[llength $p] < 25} {incr n} {
if {[pernicious $n]} {lappend p $n}
}
puts [join $p ","]
for {set n 888888877; set p {}} {$n <= 888888888} {incr n} {
if {[pernicious $n]} {lappend p $n}
}
puts [join $p ","] |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #JavaScript | JavaScript | function is_perfect(n)
{
var sum = 1, i, sqrt=Math.floor(Math.sqrt(n));
for (i = sqrt-1; i>1; i--)
{
if (n % i == 0) {
sum += i + n/i;
}
}
if(n % sqrt == 0)
sum += sqrt + (sqrt*sqrt == n ? 0 : n/sqrt);
return sum === n;
}
var i;
for (i = 1; i < 10000; i++)
{
if (is_perfect(i))
print(i);
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Groovy | Groovy | def makePermutations = { l -> l.permutations() } |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #R | R | pips <- c("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
suit <- c("Clubs", "Diamonds", "Hearts", "Spades")
# Create a deck
deck <- data.frame(pips=rep(pips, 4), suit=rep(suit, each=13))
shuffle <- function(deck)
{
n <- nrow(deck)
ord <- sample(seq_len(n), size=n)
deck[ord,]
}
deal <- function(deck, fromtop=TRUE)
{
index <- ifelse(fromtop, 1, nrow(deck))
print(paste("Dealt the", deck[index, "pips"], "of", deck[index, "suit"]))
deck[-index,]
}
# Usage
deck <- shuffle(deck)
deck
deck <- deal(deck)
# While no-one is looking, sneakily deal a card from the bottom of the pack
deck <- deal(deck, FALSE) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Powershell | Powershell |
Function Get-Pi ( $Digits )
{
$Big = [bigint[]](0..10)
$ndigits = 0
$Output = ""
$q = $t = $k = $Big[1]
$r = $Big[0]
$l = $n = $Big[3]
# Calculate first digit
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
$Output += [string]$n + '.'
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
While ( $ndigits -lt $Digits )
{
While ( $ndigits % 100 -ne 0 -or -not $Output )
{
If ( $Big[4] * $q + $r - $t -lt $n * $t )
{
$Output += [string]$n
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
}
Else
{
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
}
}
$Output
$Output = ""
}
}
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #VBA | VBA | Private Function population_count(ByVal number As Long) As Integer
Dim result As Integer
Dim digit As Integer
Do While number > 0
If number Mod 2 = 1 Then
result = result + 1
End If
number = number \ 2
Loop
population_count = result
End Function
Function is_prime(n As Integer) As Boolean
If n < 2 Then
is_prime = False
Exit Function
End If
For i = 2 To Sqr(n)
If n Mod i = 0 Then
is_prime = False
Exit Function
End If
Next i
is_prime = True
End Function
Function pernicious(n As Long)
Dim tmp As Integer
tmp = population_count(n)
pernicious = is_prime(tmp)
End Function
Public Sub main()
Dim count As Integer
Dim n As Long: n = 1
Do While count < 25
If pernicious(n) Then
Debug.Print n;
count = count + 1
End If
n = n + 1
Loop
Debug.Print
For n = 888888877 To 888888888
If pernicious(n) Then
Debug.Print n;
End If
Next n
End Sub |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #jq | jq |
def is_perfect:
. as $in
| $in == reduce range(1;$in) as $i
(0; if ($in % $i) == 0 then $i + . else . end);
# Example:
range(1;10001) | select( is_perfect ) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Haskell | Haskell | import Data.List (permutations)
main = mapM_ print (permutations [1,2,3]) |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Racket | Racket | #lang racket
;; suits:
(define suits '(club heart diamond spade))
;; ranks
(define ranks '(1 2 3 4 5 6 7 8 9 10 jack queen king))
;; cards
(define cards
(for*/list ([suit suits] [rank ranks])
(list suit rank)))
;; a deck is a box containing a list of cards.
(define (new-deck)
(box cards))
;; shuffle the cards in a deck
(define (deck-shuffle deck)
(set-box! deck (shuffle (unbox deck))))
;; deal a card from tA 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit he deck:
(define (deck-deal deck)
(begin0 (first (unbox deck))
(set-box! deck (rest (unbox deck)))))
;; TRY IT OUT:
(define my-deck (new-deck))
(deck-shuffle my-deck)
(deck-deal my-deck)
(deck-deal my-deck)
(length (unbox my-deck)) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Prolog | Prolog |
pi_spigot :-
pi(X),
forall(member(Y, X), write(Y)).
pi(OUT) :-
pi(1, 180, 60, 2, OUT).
pi(Q, R, T, I, OUT) :-
freeze(OUT,
( OUT = [Digit | OUT_]
-> U is 3 * (3 * I + 1) * (3 * I + 2),
Y is (Q * (27 * I - 12) + 5 * R) // (5 * T),
Digit is Y,
Q2 is 10 * Q * I * (2 * I - 1),
R2 is 10 * U * (Q * (5 * I - 2) + R - Y * T),
T2 is T * U,
I2 is I + 1,
pi(Q2, R2, T2, I2, OUT_)
; true)). |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #VBScript | VBScript | 'check if the number is pernicious
Function IsPernicious(n)
IsPernicious = False
bin_num = Dec2Bin(n)
sum = 0
For h = 1 To Len(bin_num)
sum = sum + CInt(Mid(bin_num,h,1))
Next
If IsPrime(sum) Then
IsPernicious = True
End If
End Function
'prime number validation
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
'decimal to binary converter
Function Dec2Bin(n)
q = n
Dec2Bin = ""
Do Until q = 0
Dec2Bin = CStr(q Mod 2) & Dec2Bin
q = Int(q / 2)
Loop
End Function
'display the first 25 pernicious numbers
c = 0
WScript.StdOut.Write "First 25 Pernicious Numbers:"
WScript.StdOut.WriteLine
For k = 1 To 100
If IsPernicious(k) Then
WScript.StdOut.Write k & ", "
c = c + 1
End If
If c = 25 Then
Exit For
End If
Next
WScript.StdOut.WriteBlankLines(2)
'display the pernicious numbers between 888,888,877 to 888,888,888 (inclusive)
WScript.StdOut.Write "Pernicious Numbers between 888,888,877 to 888,888,888 (inclusive):"
WScript.StdOut.WriteLine
For l = 888888877 To 888888888
If IsPernicious(l) Then
WScript.StdOut.Write l & ", "
End If
Next
WScript.StdOut.WriteLine |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Julia | Julia | isperfect(n::Integer) = n == sum([n % i == 0 ? i : 0 for i = 1:(n - 1)])
perfects(n::Integer) = filter(isperfect, 1:n)
@show perfects(10000) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every p := permute(A) do every writes((!p||" ")|"\n")
end
procedure permute(A)
if *A <= 1 then return A
suspend [(A[1]<->A[i := 1 to *A])] ||| permute(A[2:0])
end |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Raku | Raku | enum Pip <A 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit <♦ ♣ ♥ ♠>;
class Card {
has Pip $.pip;
has Suit $.suit;
method Str { $!pip ~ $!suit }
}
class Deck {
has Card @.cards = pick *,
map { Card.new(:$^pip, :$^suit) }, flat (Pip.pick(*) X Suit.pick(*));
method shuffle { @!cards .= pick: * }
method deal { shift @!cards }
method Str { ~@!cards }
method gist { ~@!cards }
}
my Deck $d = Deck.new;
say "Deck: $d";
my $top = $d.deal;
say "Top card: $top";
$d.shuffle;
say "Deck, re-shuffled: ", $d; |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #PureBasic | PureBasic | #SCALE = 10000
#ARRINT= 2000
Procedure Pi(Digits)
Protected First=#True, Text$
Protected Carry, i, j, sum
Dim Arr(Digits)
For i=0 To Digits
Arr(i)=#ARRINT
Next
i=Digits
While i>0
sum=0
j=i
While j>0
sum*j+#SCALE*arr(j)
Arr(j)=sum%(j*2-1)
sum/(j*2-1)
j-1
Wend
Text$ = RSet(Str(Carry+sum/#SCALE),4,"0")
If First
Text$ = ReplaceString(Text$,"3","3.")
First = #False
EndIf
Print(Text$)
Carry=sum%#SCALE
i-14
Wend
EndProcedure
If OpenConsole()
SetConsoleCtrlHandler_(?Ctrl,#True)
Pi(24*1024*1024)
EndIf
End
Ctrl:
PrintN(#CRLF$+"Ctrl-C was pressed")
End |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function PopulationCount(n As Long) As Integer
Dim cnt = 0
Do
If (n Mod 2) <> 0 Then
cnt += 1
End If
n >>= 1
Loop While n > 0
Return cnt
End Function
Function IsPrime(x As Integer) As Boolean
If x <= 2 OrElse (x Mod 2) = 0 Then
Return x = 2
End If
Dim limit = Math.Sqrt(x)
For i = 3 To limit Step 2
If x Mod i = 0 Then
Return False
End If
Next
Return True
End Function
Function Pernicious(start As Integer, count As Integer, take As Integer) As IEnumerable(Of Integer)
Return Enumerable.Range(start, count).Where(Function(n) IsPrime(PopulationCount(n))).Take(take)
End Function
Sub Main()
For Each n In Pernicious(0, Integer.MaxValue, 25)
Console.Write("{0} ", n)
Next
Console.WriteLine()
For Each n In Pernicious(888888877, 11, 11)
Console.Write("{0} ", n)
Next
Console.WriteLine()
End Sub
End Module |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #K | K | perfect:{(x>2)&x=+/-1_{d:&~x!'!1+_sqrt x;d,_ x%|d}x}
perfect 33550336
1
a@&perfect'a:!10000
6 28 496 8128
m:3 10#!30
(0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29)
perfect'/: m
(0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Permutat.bas"
110 LET N=4 ! Number of elements
120 NUMERIC T(1 TO N)
130 FOR I=1 TO N
140 LET T(I)=I
150 NEXT
160 LET S=0
170 CALL PERM(N)
180 PRINT "Number of permutations:";S
190 END
200 DEF PERM(I)
210 NUMERIC J,X
220 IF I=1 THEN
230 FOR X=1 TO N
240 PRINT T(X);
250 NEXT
260 PRINT :LET S=S+1
270 ELSE
280 CALL PERM(I-1)
290 FOR J=1 TO I-1
300 LET C=T(J):LET T(J)=T(I):LET T(I)=C
310 CALL PERM(I-1)
320 LET C=T(J):LET T(J)=T(I):LET T(I)=C
330 NEXT
340 END IF
350 END DEF |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Red | Red |
Red [Title: "Playing Cards"]
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"]
suit: ["♣" "♦" "♥" "♠"]
make-deck: function [] [
new-deck: make block! 52
foreach s suit [foreach p pip [append/only new-deck reduce [p s]]]
return new-deck
]
shuffle: function [deck [block!]] [deck: random deck]
deal: function [other-deck [block!] deck [block!]] [unless empty? deck [append/only other-deck take deck]]
contents: function [deck [block!]] [
line: 0
repeat i length? deck [
prin [trim/all form deck/:i " "]
if (to-integer i / 13) > line [line: line + 1 print ""]
]]
deck: shuffle make-deck
print "40 cards from a deck:"
loop 5 [ print "" loop 8 [prin [trim/all form take deck " "]]]
prin "^/^/remaining: "
contents deck
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Python | Python | def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0 |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Wortel | Wortel | :ispernum ^(@isPrime \@count \=1 @arr &\`![.toString 2]) |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Wren | Wren | var pernicious = Fn.new { |w|
var ff = 2.pow(32) - 1
var mask1 = (ff / 3).floor
var mask3 = (ff / 5).floor
var maskf = (ff / 17).floor
var maskp = (ff / 255).floor
w = w - (w >> 1 & mask1)
w = (w & mask3) + (w >>2 & mask3)
w = (w + (w >> 4)) & maskf
return 0xa08a28ac >> (w*maskp >> 24) & 1 != 0
}
var i = 0
var n = 1
while (i < 25) {
if (pernicious.call(n)) {
System.write("%(n) ")
i = i + 1
}
n = n + 1
}
System.print()
for (n in 888888877..888888888) {
if (pernicious.call(n)) System.write("%(n) ")
}
System.print() |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Kotlin | Kotlin | // version 1.0.6
fun isPerfect(n: Int): Boolean = when {
n < 2 -> false
n % 2 == 1 -> false // there are no known odd perfect numbers
else -> {
var tot = 1
var q: Int
for (i in 2 .. Math.sqrt(n.toDouble()).toInt()) {
if (n % i == 0) {
tot += i
q = n / i
if (q > i) tot += q
}
}
n == tot
}
}
fun main(args: Array<String>) {
// expect a run time of about 6 minutes on a typical laptop
println("The first five perfect numbers are:")
for (i in 2 .. 33550336) if (isPerfect(i)) print("$i ")
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #J | J | perms=: A.&i.~ ! |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #REXX | REXX | /* REXX ***************************************************************
* 1) Build ordered Card deck
* 2) Create shuffled stack
* 3) Deal 5 cards to 4 players each
* 4) show what cards have been dealt and what's left on the stack
* 05.07.2012 Walter Pachl
**********************************************************************/
colors='S H C D'
ranks ='A 2 3 4 5 6 7 8 9 T J Q K'
i=0
cards=''
ss=''
Do c=1 To 4
Do r=1 To 13
i=i+1
card.i=word(colors,c)word(ranks,r)
cards=cards card.i
End
End
n=52 /* number of cards on deck */
Do si=1 To 51 /* pick 51 cards */
x=random(0,n-1)+1 /* take card x (in 1...n) */
s.si=card.x /* card on shuffled stack */
ss=ss s.si /* string of shuffled stack */
card.x=card.n /* replace card taken */
n=n-1 /* decrement nr of cards */
End
s.52=card.1 /* pick the last card left */
ss=ss s.52 /* add it to the string */
Say 'Ordered deck:'
Say ' 'subword(cards,1,26)
Say ' 'subword(cards,27,52)
Say 'Shuffled stack:'
Say ' 'subword(ss,1,26)
Say ' 'subword(ss,27,52)
si=52
deck.=''
Do ci=1 To 5 /* 5 cards each */
Do pli=1 To 4 /* 4 players */
deck.pli.ci=s.si /* take top of shuffled deck */
si=si-1 /* decrement number */
deck.pli=deck.pli deck.pli.ci /* pli's cards as string */
End
End
Do pli=1 To 4 /* show the 4 dealt ... */
Say pli':' deck.pli
End
Say 'Left on shuffled stack:'
Say ' 'subword(ss,1,26) /* and what's left on stack */
Say ' 'subword(ss,27,6) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Quackery | Quackery | [ immovable
]this[ share ]done[ ] is value ( --> x )
[ ]'[ replace ] is to ( x --> )
[ value 1 ] is Q ( --> x )
[ value 0 ] is R ( --> x )
[ value 1 ] is T ( --> x )
[ value 1 ] is K ( --> x )
[ value 3 ] is N ( --> x )
[ value 3 ] is L ( --> x )
[ value 0 ] is chcount ( --> x )
[ echo
chcount dup 79 =
if cr
1+ 80 mod to chcount ] is printch
[ 4 Q * R + T - N T * < iff
[ N printch
R N T * - 10 *
3 Q * R + 10 * T / N 10 * - to N to R
Q 10 * to Q ]
else
[ 2 Q * R + L *
7 K * Q * 2 + R L * + T L * / to N to R
K Q * to Q
T L * to T
L 2 + to L
K 1+ to K ]
chcount again ] |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #zkl | zkl | primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41);
N:=0; foreach n in ([2..]){
if(n.num1s : primes.holds(_)){
print(n," ");
if((N+=1)==25) break;
}
}
foreach n in ([0d888888877..888888888]){
if (n.num1s : primes.holds(_)) "%,d; ".fmt(n).print();
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #LabVIEW | LabVIEW | #!/usr/bin/lasso9
define isPerfect(n::integer) => {
#n < 2 ? return false
return #n == (
with i in generateSeries(1, math_floor(math_sqrt(#n)) + 1)
where #n % #i == 0
let q = #n / #i
sum (#q > #i ? (#i == 1 ? 1 | #q + #i) | 0)
)
}
with x in generateSeries(1, 10000)
where isPerfect(#x)
select #x |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Lasso | Lasso | #!/usr/bin/lasso9
define isPerfect(n::integer) => {
#n < 2 ? return false
return #n == (
with i in generateSeries(1, math_floor(math_sqrt(#n)) + 1)
where #n % #i == 0
let q = #n / #i
sum (#q > #i ? (#i == 1 ? 1 | #q + #i) | 0)
)
}
with x in generateSeries(1, 10000)
where isPerfect(#x)
select #x |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Java | Java | public class PermutationGenerator {
private int[] array;
private int firstNum;
private boolean firstReady = false;
public PermutationGenerator(int n, int firstNum_) {
if (n < 1) {
throw new IllegalArgumentException("The n must be min. 1");
}
firstNum = firstNum_;
array = new int[n];
reset();
}
public void reset() {
for (int i = 0; i < array.length; i++) {
array[i] = i + firstNum;
}
firstReady = false;
}
public boolean hasMore() {
boolean end = firstReady;
for (int i = 1; i < array.length; i++) {
end = end && array[i] < array[i-1];
}
return !end;
}
public int[] getNext() {
if (!firstReady) {
firstReady = true;
return array;
}
int temp;
int j = array.length - 2;
int k = array.length - 1;
// Find largest index j with a[j] < a[j+1]
for (;array[j] > array[j+1]; j--);
// Find index k such that a[k] is smallest integer
// greater than a[j] to the right of a[j]
for (;array[j] > array[k]; k--);
// Interchange a[j] and a[k]
temp = array[k];
array[k] = array[j];
array[j] = temp;
// Put tail end of permutation after jth position in increasing order
int r = array.length - 1;
int s = j + 1;
while (r > s) {
temp = array[s];
array[s++] = array[r];
array[r--] = temp;
}
return array;
} // getNext()
// For testing of the PermutationGenerator class
public static void main(String[] args) {
PermutationGenerator pg = new PermutationGenerator(3, 1);
while (pg.hasMore()) {
int[] temp = pg.getNext();
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i] + " ");
}
System.out.println();
}
}
} // class |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Ring | Ring |
Load "guilib.ring"
nScale = 1
app1 = new qApp
mypic = new QPixmap("cards.jpg")
mypic2 = mypic.copy(0,(124*4)+1,79,124)
Player1EatPic = mypic.copy(80,(124*4)+1,79,124)
Player2EatPic= mypic.copy(160,(124*4)+1,79,124)
aMyCards = []
aMyValues = []
for x1 = 0 to 3
for y1 = 0 to 12
temppic = mypic.copy((79*y1)+1,(124*x1)+1,79,124)
aMyCards + temppic
aMyValues + (y1+1)
next
next
nPlayer1Score = 0 nPlayer2Score=0
do
Page1 = new Game
Page1.Start()
again Page1.lnewgame
mypic.delete()
mypic2.delete()
Player1EatPic.delete()
Player2EatPic.delete()
for t in aMyCards
t.delete()
next
func gui_setbtnpixmap pBtn,pPixmap
pBtn {
setIcon(new qicon(pPixmap.scaled(width(),height(),0,0)))
setIconSize(new QSize(width(),height()))
}
Class Game
nCardsCount = 10
win1 layout1 label1 label2 layout2 layout3 aBtns aBtns2
aCards nRole=1 aStatus = list(nCardsCount) aStatus2 = aStatus
aValues aStatusValues = aStatus aStatusValues2 = aStatus
Player1EatPic Player2EatPic
lnewgame = false
nDelayEat = 0.5
nDelayNewGame = 1
func start
win1 = new qWidget() {
setwindowtitle("Five")
setstylesheet("background-color: White")
showfullscreen()
}
layout1 = new qvboxlayout()
label1 = new qlabel(win1) {
settext("Player (1) - Score : " + nPlayer1Score)
setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
setstylesheet("color: White; background-color: Purple;
font-size:20pt")
setfixedheight(200)
}
closebtn = new qpushbutton(win1) {
settext("Close Application")
setstylesheet("font-size: 18px ; color : white ;
background-color: black ;")
setclickevent("Page1.win1.close()")
}
aCards = aMyCards
aValues = aMyValues
layout2 = new qhboxlayout()
aBtns = []
for x = 1 to nCardsCount
aBtns + new qpushbutton(win1)
aBtns[x].setfixedwidth(79*nScale)
aBtns[x].setfixedheight(124*nScale)
gui_setbtnpixmap(aBtns[x],mypic2)
layout2.addwidget(aBtns[x])
aBtns[x].setclickevent("Page1.Player1click("+x+")")
next
layout1.addwidget(label1)
layout1.addlayout(layout2)
label2 = new qlabel(win1) {
settext("Player (2) - Score : " + nPlayer2Score)
setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
setstylesheet("color: white; background-color: red;
font-size:20pt")
setfixedheight(200)
}
layout3 = new qhboxlayout()
aBtns2 = []
for x = 1 to nCardsCount
aBtns2 + new qpushbutton(win1)
aBtns2[x].setfixedwidth(79*nScale)
aBtns2[x].setfixedheight(124*nScale)
gui_setbtnpixmap(aBtns2[x],mypic2)
layout3.addwidget(aBtns2[x])
aBtns2[x].setclickevent("Page1.Player2click("+x+")")
next
layout1.addwidget(label2)
layout1.addlayout(layout3)
layout1.addwidget(closebtn)
win1.setlayout(layout1)
app1.exec()
Func Player1Click x
if nRole = 1 and aStatus[x] = 0
nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
gui_setbtnpixmap(aBtns[x],aCards[nPos])
del(aCards,nPos)
nRole = 2
aStatus[x] = 1
aStatusValues[x] = aValues[nPos]
del(aValues,nPos)
Player1Eat(x,aStatusValues[x])
checknewgame()
ok
Func Player2Click x
if nRole = 2 and aStatus2[x] = 0
nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
gui_setbtnpixmap(aBtns2[x],aCards[nPos])
del(aCards,nPos)
nRole = 1
aStatus2[x] = 1
aStatusValues2[x] = aValues[nPos]
del(aValues,nPos)
Player2Eat(x,aStatusValues2[x])
checknewgame()
ok
Func Player1Eat nPos,nValue
app1.processEvents()
delay(nDelayEat)
lEat = false
for x = 1 to nCardsCount
if aStatus2[x] = 1 and (aStatusValues2[x] = nValue or nValue=5)
aStatus2[x] = 2
gui_setbtnpixmap(aBtns2[x],Player1EatPic)
lEat = True
nPlayer1Score++
ok
if (x != nPos) and (aStatus[x] = 1) and
(aStatusValues[x] = nValue or nValue=5)
aStatus[x] = 2
gui_setbtnpixmap(aBtns[x],Player1EatPic)
lEat = True
nPlayer1Score++
ok
next
if lEat
nPlayer1Score++
gui_setbtnpixmap(aBtns[nPos],Player1EatPic)
aStatus[nPos] = 2
label1.settext("Player (1) - Score : " + nPlayer1Score)
ok
Func Player2Eat nPos,nValue
app1.processEvents()
delay(nDelayEat)
lEat = false
for x = 1 to nCardsCount
if aStatus[x] = 1 and (aStatusValues[x] = nValue or nValue = 5)
aStatus[x] = 2
gui_setbtnpixmap(aBtns[x],Player2EatPic)
lEat = True
nPlayer2Score++
ok
if (x != nPos) and (aStatus2[x] = 1) and
(aStatusValues2[x] = nValue or nValue=5 )
aStatus2[x] = 2
gui_setbtnpixmap(aBtns2[x],Player2EatPic)
lEat = True
nPlayer2Score++
ok
next
if lEat
nPlayer2Score++
gui_setbtnpixmap(aBtns2[nPos],Player2EatPic)
aStatus2[nPos] = 2
label2.settext("Player (2) - Score : " + nPlayer2Score)
ok
Func checknewgame
if isnewgame()
lnewgame = true
if nPlayer1Score > nPlayer2Score
label1.settext("Player (1) Wins!!!")
ok
if nPlayer2Score > nPlayer1Score
label2.settext("Player (2) Wins!!!")
ok
app1.processEvents()
delay(nDelayNewGame)
win1.delete()
app1.quit()
ok
Func isnewgame
for t in aStatus
if t = 0
return false
ok
next
for t in aStatus2
if t = 0
return false
ok
next
return true
Func delay x
nTime = x * 1000
oTest = new qTest
oTest.qsleep(nTime)
|
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #R | R |
suppressMessages(library(gmp))
ONE <- as.bigz("1")
TWO <- as.bigz("2")
THREE <- as.bigz("3")
FOUR <- as.bigz("4")
SEVEN <- as.bigz("7")
TEN <- as.bigz("10")
q <- as.bigz("1")
r <- as.bigz("0")
t <- as.bigz("1")
k <- as.bigz("1")
n <- as.bigz("3")
l <- as.bigz("3")
char_printed <- 0
how_many <- 1000
first <- TRUE
while (how_many > 0) {
if ((FOUR * q + r - t) < (n * t)) {
if (char_printed == 80) {
cat("\n")
char_printed <- 0
}
how_many <- how_many - 1
char_printed <- char_printed + 1
cat(as.integer(n))
if (first) {
cat(".")
first <- FALSE
char_printed <- char_printed + 1
}
nr <- as.bigz(TEN * (r - n * t))
n <- as.bigz(((TEN * (THREE * q + r)) %/% t) - (TEN * n))
q <- as.bigz(q * TEN)
r <- as.bigz(nr)
} else {
nr <- as.bigz((TWO * q + r) * l)
nn <- as.bigz((q * (SEVEN * k + TWO) + r * l) %/% (t * l))
q <- as.bigz(q * k)
t <- as.bigz(t * l)
l <- as.bigz(l + TWO)
k <- as.bigz(k + ONE)
n <- as.bigz(nn)
r <- as.bigz(nr)
}
}
cat("\n")
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Liberty_BASIC | Liberty BASIC | for n =1 to 10000
if perfect( n) =1 then print n; " is perfect."
next n
end
function perfect( n)
sum =0
for i =1 TO n /2
if n mod i =0 then
sum =sum +i
end if
next i
if sum =n then
perfect= 1
else
perfect =0
end if
end function |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #JavaScript | JavaScript | <html><head><title>Permutations</title></head>
<body><pre id="result"></pre>
<script type="text/javascript">
var d = document.getElementById('result');
function perm(list, ret)
{
if (list.length == 0) {
var row = document.createTextNode(ret.join(' ') + '\n');
d.appendChild(row);
return;
}
for (var i = 0; i < list.length; i++) {
var x = list.splice(i, 1);
ret.push(x);
perm(list, ret);
ret.pop();
list.splice(i, 0, x);
}
}
perm([1, 2, 'A', 4], []);
</script></body></html> |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Ruby | Ruby | class Card
# class constants
SUITS = %i[ Clubs Hearts Spades Diamonds ]
PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ]
# class variables (private)
@@suit_value = Hash[ SUITS.each_with_index.to_a ]
@@pip_value = Hash[ PIPS.each_with_index.to_a ]
attr_reader :pip, :suit
def initialize(pip,suit)
@pip = pip
@suit = suit
end
def to_s
"#{@pip} #{@suit}"
end
# allow sorting an array of Cards: first by suit, then by value
def <=>(other)
(@@suit_value[@suit] <=> @@suit_value[other.suit]).nonzero? or
@@pip_value[@pip] <=> @@pip_value[other.pip]
end
end
class Deck
def initialize
@deck = Card::SUITS.product(Card::PIPS).map{|suit,pip| Card.new(pip,suit)}
end
def to_s
@deck.inspect
end
def shuffle!
@deck.shuffle!
self
end
def deal(*args)
@deck.shift(*args)
end
end
deck = Deck.new.shuffle!
puts card = deck.deal
hand = deck.deal(5)
puts hand.join(", ")
puts hand.sort.join(", ") |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Racket | Racket |
#lang racket
(require racket/generator)
(define pidig
(generator ()
(let loop ([q 1] [r 0] [t 1] [k 1] [n 3] [l 3])
(if (< (- (+ r (* 4 q)) t) (* n t))
(begin (yield n)
(loop (* q 10) (* 10 (- r (* n t))) t k
(- (quotient (* 10 (+ (* 3 q) r)) t) (* 10 n))
l))
(loop (* q k) (* (+ (* 2 q) r) l) (* t l) (+ 1 k)
(quotient (+ (* (+ 2 (* 7 k)) q) (* r l)) (* t l))
(+ l 2))))))
(for ([i (in-naturals)])
(display (pidig))
(when (zero? i) (display "." ))
(when (zero? (modulo i 80)) (newline)))
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Lingo | Lingo | on isPercect (n)
sum = 1
cnt = n/2
repeat with i = 2 to cnt
if n mod i = 0 then sum = sum + i
end repeat
return sum=n
end |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Logo | Logo | to perfect? :n
output equal? :n apply "sum filter [equal? 0 modulo :n ?] iseq 1 :n/2
end |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #jq | jq | def permutations:
if length == 0 then []
else
range(0;length) as $i
| [.[$i]] + (del(.[$i])|permutations)
end ;
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Run_BASIC | Run BASIC | suite$ = "C,D,H,S" ' Club, Diamond, Heart, Spade
card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King
dim n(55) ' make ordered deck
for i = 1 to 52 ' of 52 cards
n(i) = i
next i
for i = 1 to 52 * 3 ' shuffle deck 3 times
i1 = int(rnd(1)*52) + 1
i2 = int(rnd(1)*52) + 1
h2 = n(i1)
n(i1) = n(i2)
n(i2) = h2
next i
for hand = 1 to 4 ' 4 hands
for deal = 1 to 13 ' deal each 13 cards
card = card + 1 ' next card in deck
s = (n(card) mod 4) + 1 ' determine suite
c = (n(card) mod 13) + 1 ' determine card
print word$(card$,c,",");word$(suite$,s,",");" "; ' show the card
next deal
print
next hand |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Raku | Raku | # based on http://www.mathpropress.com/stan/bibliography/spigot.pdf
sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
gather loop {
$z = safe($z, my $y = next($z)) ??
prod($z, take $y) !!
cons($z, @x[$++])
}
}
sub extr([$q, $r, $s, $t], $x) {
($q * $x + $r) div ($s * $x + $t)
}
sub comp([$q,$r,$s,$t], [$u,$v,$w,$x]) {
[$q * $u + $r * $w,
$q * $v + $r * $x,
$s * $u + $t * $w,
$s * $v + $t * $x]
}
my $pi :=
stream -> $z { extr($z, 3) },
-> $z, $n { $n == extr($z, 4) },
-> $z, $n { comp([10, -10*$n, 0, 1], $z) },
&comp,
<1 0 0 1>,
(1..*).map: { [$_, 4 * $_ + 2, 0, 2 * $_ + 1] }
for ^Inf -> $i {
print $pi[$i];
once print '.'
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Lua | Lua | function isPerfect(x)
local sum = 0
for i = 1, x-1 do
sum = (x % i) == 0 and sum + i or sum
end
return sum == x
end |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #M2000_Interpreter | M2000 Interpreter |
Module PerfectNumbers {
Function Is_Perfect(n as decimal) {
s=1 : sN=Sqrt(n)
last= n=sN*sN
t=n
If n mod 2=0 then s+=2+n div 2
i=3 : sN--
While i<sN {
if n mod i=0 then t=n div i :i=max.data(n div t, i): s+=t+ i
i++
}
=n=s
}
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop}
}
\\ Check a perfect and a non perfect number
p=2 : n=3 : n1=2
Document Doc$
IsPerfect( 0, 28)
IsPerfect( 0, 1544)
While p<32 { ' max 32
if isprime(2^p-1@) then {
perf=(2^p-1@)*2@^(p-1@)
Rem Print perf
\\ decompose pretty fast the Perferct Numbers
\\ all have a series of 2 and last a prime equal to perf/2^(p-1)
inventory queue factors
For i=1 to p-1 {
Append factors, 2@
}
Append factors, perf/2^(p-1)
\\ end decompose
Rem Print factors
IsPerfect(factors, Perf)
}
p++
}
Clipboard Doc$
\\ exit here. No need for Exit statement
Sub IsPerfect(factors, n)
s=false
if n<10000 or type$(factors)<>"Inventory" then {
s=Is_Perfect(n)
} else {
local mm=each(factors, 1, -2), f =true
while mm {if eval(mm)<>2 then f=false
}
if f then if n/2@**(len(mm)-1)= factors(len(factors)-1!) then s=true
}
Local a$=format$("{0} is {1}perfect number", n, If$(s->"", "not "))
Doc$=a$+{
}
Print a$
End Sub
}
PerfectNumbers
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Julia | Julia |
julia> perms(l) = isempty(l) ? [l] : [[x; y] for x in l for y in perms(setdiff(l, x))]
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Rust | Rust | extern crate rand;
use std::fmt;
use rand::Rng;
use Pip::*;
use Suit::*;
#[derive(Copy, Clone, Debug)]
enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }
#[derive(Copy, Clone, Debug)]
enum Suit { Spades, Hearts, Diamonds, Clubs }
struct Card {
pip: Pip,
suit: Suit
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?} of {:?}", self.pip, self.suit)
}
}
struct Deck(Vec<Card>);
impl Deck {
fn new() -> Deck {
let mut cards:Vec<Card> = Vec::with_capacity(52);
for &suit in &[Spades, Hearts, Diamonds, Clubs] {
for &pip in &[Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King] {
cards.push( Card{pip: pip, suit: suit} );
}
}
Deck(cards)
}
fn deal(&mut self) -> Option<Card> {
self.0.pop()
}
fn shuffle(&mut self) {
rand::thread_rng().shuffle(&mut self.0)
}
}
impl fmt::Display for Deck {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for card in self.0.iter() {
writeln!(f, "{}", card);
}
write!(f, "")
}
}
fn main() {
let mut deck = Deck::new();
deck.shuffle();
//println!("{}", deck);
for _ in 0..5 {
println!("{}", deck.deal().unwrap());
}
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #REXX | REXX | ┌─ ─┐ ┌─ ─┐
π │ 1 │ │ 1 │ John
─── = 4 ∙ arctan│ ─── │ - arctan│ ───── │ Machin's
4 │ 5 │ │ 239 │ formula
└─ ─┘ └─ ─┘
which expands into:
┌─ ─┐
│ 1 1 1 1 1 1 │
4 ∙ │ ─── - ────── + ────── - ────── + ────── - ──────── + ... │
│ 1 3 5 7 9 11 │
│ 1∙5 3∙5 5∙5 7∙5 9∙5 11∙5 │
└─ ─┘
┌─ ─┐
│ 1 1 1 1 1 1 │
- │ ─── - ────── + ────── - ────── + ────── - ──────── + ... │
│ 1 3 5 7 9 11 │
│ 1∙239 3∙239 5∙239 7∙239 9∙239 11∙239 │
└─ ─┘
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #M4 | M4 | define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')dnl
define(`ispart',
`ifelse(eval($2*$2<=$1),1,
`ifelse(eval($1%$2==0),1,
`ifelse(eval($2*$2==$1),1,
`ispart($1,incr($2),eval($3+$2))',
`ispart($1,incr($2),eval($3+$2+$1/$2))')',
`ispart($1,incr($2),$3)')',
$3)')
define(`isperfect',
`eval(ispart($1,2,1)==$1)')
for(`x',`2',`33550336',
`ifelse(isperfect(x),1,`x
')') |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #MAD | MAD | NORMAL MODE IS INTEGER
R FUNCTION THAT CHECKS IF NUMBER IS PERFECT
INTERNAL FUNCTION(N)
ENTRY TO PERFCT.
DSUM = 0
THROUGH SUMMAT, FOR CAND=1, 1, CAND.GE.N
SUMMAT WHENEVER N/CAND*CAND.E.N, DSUM = DSUM+CAND
FUNCTION RETURN DSUM.E.N
END OF FUNCTION
R PRINT PERFECT NUMBERS UP TO 10,000
THROUGH SHOW, FOR I=1, 1, I.G.10000
SHOW WHENEVER PERFCT.(I), PRINT FORMAT FMT,I
VECTOR VALUES FMT = $I5*$
PRINT COMMENT $ $
END OF PROGRAM
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #K | K | perm:{:[1<x;,/(>:'(x,x)#1,x#0)[;0,'1+_f x-1];,!x]}
perm 2
(0 1
1 0)
`0:{1_,/" ",/:x}'r@perm@#r:("some";"random";"text")
some random text
some text random
random some text
random text some
text some random
text random some |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Scala | Scala | import scala.annotation.tailrec
import scala.util.Random
object Pip extends Enumeration {
type Pip = Value
val Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace = Value
}
object Suit extends Enumeration {
type Suit = Value
val Diamonds, Spades, Hearts, Clubs = Value
}
import Suit._
import Pip._
case class Card(suit:Suit, value:Pip){
override def toString():String=value + " of " + suit
}
class Deck private(val cards:List[Card]) {
def this()=this(for {s <- Suit.values.toList; v <- Pip.values} yield Card(s,v))
def shuffle:Deck=new Deck(Random.shuffle(cards))
def deal(n:Int=1):(Seq[Card], Deck)={
@tailrec def loop(count:Int, c:Seq[Card], d:Deck):(Seq[Card], Deck)={
if(count==0 || d.cards==Nil) (c,d)
else {
val card :: deck = d.cards
loop(count-1, c :+ card, new Deck(deck))
}
}
loop(n, Seq(), this)
}
override def toString():String="Deck: " + (cards mkString ", ")
} |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Ruby | Ruby | pi_digits = Enumerator.new do |y|
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
loop do
if 4*q+r-t < n*t
y << n
nr = 10*(r-n*t)
n = ((10*(3*q+r)) / t) - 10*n
q *= 10
r = nr
else
nr = (2*q+r) * l
nn = (q*(7*k+2)+r*l) / (t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end
end
end
print pi_digits.next, "."
loop { print pi_digits.next } |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Maple | Maple | isperfect := proc(n) return evalb(NumberTheory:-SumOfDivisors(n) = 2*n); end proc:
isperfect(6);
true |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | PerfectQ[i_Integer] := Total[Divisors[i]] == 2 i |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Kotlin | Kotlin | // version 1.1.2
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun main(args: Array<String>) {
val input = listOf('a', 'b', 'c', 'd')
val perms = permute(input)
println("There are ${perms.size} permutations of $input, namely:\n")
for (perm in perms) println(perm)
} |
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.