code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 442Permutations by swapping
| 17swift
| yxr6e |
user=> (require 'clojure.contrib.combinatorics)
nil
user=> (clojure.contrib.combinatorics/permutations [1 2 3])
((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)) | 456Permutations
| 6clojure
| vo92f |
public func totient(n: Int) -> Int {
var n = n
var i = 2
var tot = n
while i * i <= n {
if n% i == 0 {
while n% i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
public struct PerfectTotients: Sequence, IteratorProtocol {
private var m = 1
public init() { }
public mutating func next() -> Int? {
while true {
defer {
m += 1
}
var tot = m
var sum = 0
while tot!= 1 {
tot = totient(n: tot)
sum += tot
}
if sum == m {
return m
}
}
}
}
print("The first 20 perfect totient numbers are:")
print(Array(PerfectTotients().prefix(20))) | 450Perfect totient numbers
| 17swift
| 6w93j |
null | 443Pi
| 11kotlin
| 2okli |
use Image::Imlib2;
my $img1 = Image::Imlib2->load('Lenna50.jpg') || die;
my $img2 = Image::Imlib2->load('Lenna100.jpg') || die;
my $w = $img1->width;
my $h = $img1->height;
my $sum = 0;
for my $x (0..$w-1) {
for my $y (0..$h-1) {
my ($r1, $g1, $b1) = $img1->query_pixel($x, $y);
my ($r2, $g2, $b2) = $img2->query_pixel($x, $y);
$sum += abs($r1-$r2) + abs($g1-$g2) + abs($b1-$b2);
}
}
printf "%% difference =%.4f\n", 100 * $sum / ($w * $h * 3 * 255); | 453Percentage difference between images
| 2perl
| t1tfg |
import Foundation
struct Perlin {
private static let permutation = [
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
]
private static let p = (0..<512).map({i -> Int in
if i < 256 {
return permutation[i]
} else {
return permutation[i - 256]
}
})
private static func fade(_ t: Double) -> Double { t * t * t * (t * (t * 6 - 15) + 10) }
private static func lerp(_ t: Double, _ a: Double, _ b: Double) -> Double { a + t * (b - a) }
private static func grad(_ hash: Int, _ x: Double, _ y: Double, _ z: Double) -> Double {
let h = hash & 15
let u = h < 8? x: y
let v = h < 4? y: h == 12 || h == 14? x: z
return (h & 1 == 0? u: -u) + (h & 2 == 0? v: -v)
}
static func noise(x: Double, y: Double, z: Double) -> Double {
let xi = Int(x) & 255
let yi = Int(y) & 255
let zi = Int(z) & 255
let xx = x - floor(x)
let yy = y - floor(y)
let zz = z - floor(z)
let u = fade(xx)
let v = fade(yy)
let w = fade(zz)
let a = p[xi] + yi
let aa = p[a] + zi
let b = p[xi + 1] + yi
let ba = p[b] + zi
let ab = p[a + 1] + zi
let bb = p[b + 1] + zi
return lerp(w, lerp(v, lerp(u, grad(p[aa], xx, yy, zz),
grad(p[ba], xx - 1, yy, zz)),
lerp(u, grad(p[ab], xx, yy - 1, zz),
grad(p[bb], xx - 1, yy - 1, zz))),
lerp(v, lerp(u, grad(p[aa + 1], xx, yy, zz - 1),
grad(p[ba + 1], xx - 1, yy, zz - 1)),
lerp(u, grad(p[ab + 1], xx, yy - 1, zz - 1),
grad(p[bb + 1], xx - 1, yy - 1, zz - 1))))
}
}
print(Perlin.noise(x: 3.14, y: 42, z: 7)) | 445Perlin noise
| 17swift
| vih2r |
suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"} | 438Playing cards
| 1lua
| 8720e |
use rand::prelude::*;
fn main() {
println!("Beginning game of Pig...");
let mut players = vec![
Player::new(String::from("PLAYER (1) ONE")),
Player::new(String::from("PLAYER (2) TWO")),
];
'game: loop {
for player in players.iter_mut() {
if player.cont() {
println!("\n# {} has {:?} Score", player.name, player.score);
player.resolve();
} else {
println!("\n{} wins!", player.name);
break 'game;
}
}
}
println!("Thanks for playing!");
}
type DiceRoll = u32;
type Score = u32;
type Name = String;
enum Action {
Roll,
Hold,
}
#[derive(PartialEq)]
enum TurnStatus {
Continue,
End,
}
struct Player {
name: Name,
score: Score,
status: TurnStatus,
}
impl Player {
fn new(name: Name) -> Player {
Player {
name,
score: 0,
status: TurnStatus::Continue,
}
}
fn roll() -> DiceRoll { | 434Pig the dice game
| 15rust
| rzdg5 |
from itertools import permutations
import math
def derangements(n):
'All deranged permutations of the integers 0..n-1 inclusive'
return ( perm for perm in permutations(range(n))
if all(indx != p for indx, p in enumerate(perm)) )
def subfact(n):
if n == 2 or n == 0:
return 1
elif n == 1:
return 0
elif 1 <= n <=18:
return round(math.factorial(n) / math.e)
elif n.imag == 0 and n.real == int(n.real) and n > 0:
return (n-1) * ( subfact(n - 1) + subfact(n - 2) )
else:
raise ValueError()
def _iterlen(iter):
'length of an iterator without taking much memory'
l = 0
for x in iter:
l += 1
return l
if __name__ == '__main__':
n = 4
print(% (tuple(range(n)),))
for d in derangements(n):
print(% (d,))
print()
for n in range(10):
print(%
(n, _iterlen(derangements(n)), subfact(n)))
n = 20
print(% (n, subfact(n))) | 444Permutations/Derangements
| 3python
| ojy81 |
object PigDice extends App {
private val (maxScore, nPlayers) = (100, 2)
private val rnd = util.Random
private case class Game(gameOver: Boolean, idPlayer: Int, score: Int, stickedScores: Vector[Int])
@scala.annotation.tailrec
private def loop(play: Game): Unit =
play match {
case Game(true, _, _, _) =>
case Game(false, gPlayer, gScore, gStickedVals) =>
val safe = gStickedVals(gPlayer)
val stickScore = safe + gScore
val gameOver = stickScore >= maxScore
def nextPlayer = (gPlayer + 1) % nPlayers
def gamble: Game = play match {
case Game(_: Boolean, lPlayer: Int, lScore: Int, lStickedVals: Vector[Int]) =>
val rolled: Int = rnd.nextInt(6) + 1
println(s" Rolled $rolled")
if (rolled == 1) {
println(s" Bust! You lose $lScore but keep ${lStickedVals(lPlayer)}\n")
play.copy(idPlayer = nextPlayer, score = 0)
} else play.copy(score = lScore + rolled)
}
def stand: Game = play match {
case Game(_, lPlayer, _, lStickedVals) =>
println(
(if (gameOver) s"\n\nPlayer $lPlayer wins with a score of" else " Sticking with")
+ s" $stickScore.\n")
Game(gameOver, nextPlayer, 0, lStickedVals.updated(lPlayer, stickScore))
}
if (!gameOver && Seq("y", "").contains(
io.StdIn.readLine(f" Player $gPlayer%d: ($safe%d, $gScore%d) Rolling? ([y]/n): ").toLowerCase)
) loop(gamble )else loop(stand)
}
loop(Game(gameOver = false, 0, 0, Array.ofDim[Int](nPlayers).toVector))
} | 434Pig the dice game
| 16scala
| hyzja |
str =
puts str.reverse
puts str.split.map(&:reverse).join()
puts str.split.reverse.join() | 437Phrase reversals
| 14ruby
| vix2n |
fn reverse_string(string: &str) -> String {
string.chars().rev().collect::<String>()
}
fn reverse_words(string: &str) -> String {
string
.split_whitespace()
.map(|x| x.chars().rev().collect::<String>())
.collect::<Vec<String>>()
.join(" ")
}
fn reverse_word_order(string: &str) -> String {
string
.split_whitespace()
.rev()
.collect::<Vec<&str>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reverse_string() {
let string = "rosetta code phrase reversal";
assert_eq!(
reverse_string(string.clone()),
"lasrever esarhp edoc attesor"
);
}
#[test]
fn test_reverse_words() {
let string = "rosetta code phrase reversal";
assert_eq!(
reverse_words(string.clone()),
"attesor edoc esarhp lasrever"
);
}
#[test]
fn test_reverse_word_order() {
let string = "rosetta code phrase reversal";
assert_eq!(
reverse_word_order(string.clone()),
"reversal phrase code rosetta"
);
}
} | 437Phrase reversals
| 15rust
| unqvj |
bool isPerfect(int n){ | 455Perfect numbers
| 18dart
| tpnfa |
use List::Util qw(all);
sub perfect_shuffle {
my $mid = @_ / 2;
map { @_[$_, $_ + $mid] } 0..($mid - 1);
}
for my $size (8, 24, 52, 100, 1020, 1024, 10000) {
my @shuffled = my @deck = 1 .. $size;
my $n = 0;
do { $n++; @shuffled = perfect_shuffle(@shuffled) }
until all { $shuffled[$_] == $deck[$_] } 0..$
printf "%5d cards:%4d\n", $size, $n;
} | 452Perfect shuffle
| 2perl
| q4sx6 |
a = {}
n = 1000
len = math.modf( 10 * n / 3 )
for j = 1, len do
a[j] = 2
end
nines = 0
predigit = 0
for j = 1, n do
q = 0
for i = len, 1, -1 do
x = 10 * a[i] + q * i
a[i] = math.fmod( x, 2 * i - 1 )
q = math.modf( x / ( 2 * i - 1 ) )
end
a[1] = math.fmod( q, 10 )
q = math.modf( q / 10 )
if q == 9 then
nines = nines + 1
else
if q == 10 then
io.write( predigit + 1 )
for k = 1, nines do
io.write(0)
end
predigit = 0
nines = 0
else
io.write( predigit )
predigit = q
if nines ~= 0 then
for k = 1, nines do
io.write( 9 )
end
nines = 0
end
end
end
end
print( predigit ) | 443Pi
| 1lua
| vib2x |
>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz' | 436Pick random element
| 3python
| 9samf |
object PhraseReversals extends App {
val phrase = scala.io.StdIn.readLine
println(phrase.reverse)
println(phrase.split(' ').map(_.reverse).mkString(" "))
println(phrase.split(' ').reverse.mkString(" "))
} | 437Phrase reversals
| 16scala
| gt84i |
from PIL import Image
i1 = Image.open()
i2 = Image.open()
assert i1.mode == i2.mode,
assert i1.size == i2.size,
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print (, (dif / 255.0 * 100) / ncomponents) | 453Percentage difference between images
| 3python
| zaztt |
sub is_pernicious {
my $n = shift;
my $c = 2693408940;
while ($n) { $c >>= 1; $n &= ($n - 1); }
$c & 1;
}
my ($i, @p) = 0;
while (@p < 25) {
push @p, $i if is_pernicious($i);
$i++;
}
print join ' ', @p;
print "\n";
($i, @p) = (888888877,);
while ($i < 888888888) {
push @p, $i if is_pernicious($i);
$i++;
}
print join ' ', @p; | 441Pernicious numbers
| 2perl
| nk2iw |
letters
sample(letters, 1)
paste(sample(letters, 10, rep=T), collapse="") | 436Pick random element
| 13r
| 3ekzt |
import doctest
import random
def flatten(lst):
return [i for sublst in lst for i in sublst]
def magic_shuffle(deck):
half = len(deck)
return flatten(zip(deck[:half], deck[half:]))
def after_how_many_is_equal(shuffle_type,start,end):
start = shuffle_type(start)
counter = 1
while start != end:
start = shuffle_type(start)
counter += 1
return counter
def main():
doctest.testmod()
print()
for length in (8, 24, 52, 100, 1020, 1024, 10000):
deck = list(range(length))
shuffles_needed = after_how_many_is_equal(magic_shuffle,deck,deck)
print(.format(length,shuffles_needed))
if __name__ == :
main() | 452Perfect shuffle
| 3python
| sg0q9 |
func reverseString(s:String)->String{
var temp = [Character]()
for i in s.characters{
temp.append(i)
}
var j=s.characters.count-1
for i in s.characters{
temp[j]=i
j-=1
}
return String(temp)
}
func reverseWord(s:String)->String{
var temp = [Character]()
var result:String=""
for i in s.characters{
if i==" "{
result += "\(reverseString(s:String(temp))) "
temp=[Character]()
}
else {
temp.append(i)
}
if i==s[s.index(before: s.endIndex)]{
result += (reverseString(s:String(temp)))
}
}
return result
}
func flipString(s:String)->String{
return reverseWord(s:reverseString(s:s))
}
print(str)
print(reverseString(s:str))
print(reverseWord(s:str))
print(flipString(s:str)) | 437Phrase reversals
| 17swift
| 2owlj |
wave.shuffle <- function(n) {
deck <- 1:n
new.deck <- c(matrix(data = deck, ncol = 2, byrow = TRUE))
counter <- 1
while (!identical(deck, new.deck)) {
new.deck <- c(matrix(data = new.deck, ncol = 2, byrow = TRUE))
counter <- counter + 1
}
return(counter)
}
test.values <- c(8, 24, 52, 100, 1020, 1024, 10000)
test <- sapply(test.values, wave.shuffle)
names(test) <- test.values
test | 452Perfect shuffle
| 13r
| evwad |
def derangements(n)
ary = (1 .. n).to_a
ary.permutation.select do |perm|
ary.zip(perm).all? {|a,b| a!= b}
end
end
def subfact(n)
case n
when 0 then 1
when 1 then 0
else (n-1)*(subfact(n-1) + subfact(n-2))
end
end
puts
derangements(4).each{|d|p d}
puts
(0..9).each do |n|
puts % [n, derangements(n).size, subfact(n)]
end
puts
(10..20).each do |n|
puts
end | 444Permutations/Derangements
| 14ruby
| nk9it |
require 'raster_graphics'
class RGBColour
def -(a_colour)
(@red - a_colour.red).abs +
(@green - a_colour.green).abs +
(@blue - a_colour.blue).abs
end
end
class Pixmap
def -(a_pixmap)
if @width!= a_pixmap.width or @height!= a_pixmap.height
raise ArgumentError,
end
sum = 0
each_pixel {|x,y| sum += self[x,y] - a_pixmap[x,y]}
Float(sum) / (@width * @height * 255 * 3)
end
end
lenna50 = Pixmap.open_from_jpeg('Lenna50.jpg')
lenna100 = Pixmap.open_from_jpeg('Lenna100.jpg')
puts % (100.0 * (lenna50 - lenna100)) | 453Percentage difference between images
| 14ruby
| 6w63t |
%w(north east south west).sample
(1..100).to_a.sample(2) | 436Pick random element
| 14ruby
| l8wcl |
def derangements(n: Int) =
(1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})
def subfactorial(n: Long): Long = n match {
case 0 => 1
case 1 => 0
case _ => (n - 1) * (subfactorial(n - 1) + subfactorial(n - 2))
}
println(s"Derangements for n = 4")
println(derangements(4) mkString "\n")
println("\n%2s%10s%10s".format("n", "derange", "subfact"))
(0 to 9).foreach(n => println("%2d%10d%10d".format(n, derangements(n).size, subfactorial(n))))
(10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d")) | 444Permutations/Derangements
| 16scala
| zavtr |
extern crate image;
use image::{GenericImageView, Rgba};
fn diff_rgba3(rgba1: Rgba<u8>, rgba2: Rgba<u8>) -> i32 {
(rgba1[0] as i32 - rgba2[0] as i32).abs()
+ (rgba1[1] as i32 - rgba2[1] as i32).abs()
+ (rgba1[2] as i32 - rgba2[2] as i32).abs()
}
fn main() {
let img1 = image::open("Lenna100.jpg").unwrap();
let img2 = image::open("Lenna50.jpg").unwrap();
let mut accum = 0;
let zipper = img1.pixels().zip(img2.pixels());
for (pixel1, pixel2) in zipper {
accum += diff_rgba3(pixel1.2, pixel2.2);
}
println!("Percent difference {}", accum as f64 * 100.0/ (255.0 * 3.0 * (img1.width() * img1.height()) as f64));
} | 453Percentage difference between images
| 15rust
| yxy68 |
extern crate rand;
use rand::Rng;
fn main() {
let array = [5,1,2,5,6,7,8,1,2,4,5];
let mut rng = rand::thread_rng();
println!("{}", rng.choose(&array).unwrap());
} | 436Pick random element
| 15rust
| 2oxlt |
func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]?
{
var width = 0
var height = 0
var pixelValues: [UInt8]?
if let imageRef = imageRef {
width = imageRef.width
height = imageRef.height
let bitsPerComponent = imageRef.bitsPerComponent
let bytesPerRow = imageRef.bytesPerRow
let totalBytes = height * bytesPerRow
let bitmapInfo = imageRef.bitmapInfo
let colorSpace = CGColorSpaceCreateDeviceRGB()
var intensities = [UInt8](repeating: 0, count: totalBytes)
let contextRef = CGContext(data: &intensities,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))
pixelValues = intensities
}
return pixelValues
}
func compareImages(image1: UIImage, image2: UIImage) -> Double? {
guard let data1 = pixelValues(fromCGImage: image1.cgImage),
let data2 = pixelValues(fromCGImage: image2.cgImage),
data1.count == data2.count else {
return nil
}
let width = Double(image1.size.width)
let height = Double(image1.size.height)
return zip(data1, data2)
.enumerated()
.reduce(0.0) {
$1.offset% 4 == 3? $0: $0 + abs(Double($1.element.0) - Double($1.element.1))
}
* 100 / (width * height * 3.0) / 255.0
}
let image1 = UIImage(named: "Lenna50")
let image2 = UIImage(named: "Lenna100")
compareImages(image1: image1, image2: image2) | 453Percentage difference between images
| 17swift
| 3e3z2 |
def perfect_shuffle(deck_size = 52)
deck = (1..deck_size).to_a
original = deck.dup
half = deck_size / 2
1.step do |i|
deck = deck.first(half).zip(deck.last(half)).flatten
return i if deck == original
end
end
[8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts } | 452Perfect shuffle
| 14ruby
| 87o01 |
extern crate itertools;
fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> {
let index = deck.len() / 2;
let right_half = deck.split_off(index);
itertools::interleave(deck, right_half).collect()
}
fn main() {
for &size in &[8, 24, 52, 100, 1020, 1024, 10_000] {
let original_deck: Vec<_> = (0..size).collect();
let mut deck = original_deck.clone();
let mut iterations = 0;
loop {
deck = shuffle(deck);
iterations += 1;
if deck == original_deck {
break;
}
}
println!("{: >5}: {: >4}", size, iterations);
}
} | 452Perfect shuffle
| 15rust
| oji83 |
val a = (1 to 10).toList
println(scala.util.Random.shuffle(a).head) | 436Pick random element
| 16scala
| 5d0ut |
object PerfectShuffle extends App {
private def sizes = Seq(8, 24, 52, 100, 1020, 1024, 10000)
private def perfectShuffle(size: Int): Int = {
require(size % 2 == 0, "Card deck must be even")
val (half, a) = (size / 2, Array.range(0, size))
val original = a.clone
var count = 1
while (true) {
val aa = a.clone
for (i <- 0 until half) {
a(2 * i) = aa(i)
a(2 * i + 1) = aa(i + half)
}
if (a.deep == original.deep) return count
count += 1
}
0
}
for (size <- sizes) println(f"$size%5d: ${perfectShuffle(size)}%5d")
} | 452Perfect shuffle
| 16scala
| dbfng |
>>> def popcount(n): return bin(n).count()
>>> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61}
>>> p, i = [], 0
>>> while len(p) < 25:
if popcount(i) in primes: p.append(i)
i += 1
>>> p
[3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 31, 33, 34, 35, 36]
>>> p, i = [], 888888877
>>> while i <= 888888888:
if popcount(i) in primes: p.append(i)
i += 1
>>> p
[888888877, 888888878, 888888880, 888888883, 888888885, 888888886]
>>> | 441Pernicious numbers
| 3python
| dbvn1 |
func perfectShuffle<T>(_ arr: [T]) -> [T]? {
guard arr.count & 1 == 0 else {
return nil
}
let half = arr.count / 2
var res = [T]()
for i in 0..<half {
res.append(arr[i])
res.append(arr[i + half])
}
return res
}
let decks = [
Array(1...8),
Array(1...24),
Array(1...52),
Array(1...100),
Array(1...1020),
Array(1...1024),
Array(1...10000)
]
for deck in decks {
var shuffled = deck
var shuffles = 0
repeat {
shuffled = perfectShuffle(shuffled)!
shuffles += 1
} while shuffled!= deck
print("Deck of \(shuffled.count) took \(shuffles) shuffles to get back to original order")
} | 452Perfect shuffle
| 17swift
| 0r8s6 |
package Playing_Card_Deck;
use strict;
@Playing_Card_Deck::suits = qw
[Diamonds Clubs Hearts Spades];
@Playing_Card_Deck::pips = qw
[Two Three Four Five Six Seven Eight Nine Ten
Jack King Queen Ace];
sub new
{my $invocant = shift;
my $class = ref($invocant) || $invocant;
my @cards = ();
foreach my $suit (@Playing_Card_Deck::suits)
{foreach my $pip (@Playing_Card_Deck::pips)
{push(@cards, {suit => $suit, pip => $pip});}}
return bless([@cards], $class);}
sub deal
{return %{ shift( @{shift(@_)} ) };}
sub shuffle
{our @deck; local *deck = shift;
for (my $n = $
{my $k = int rand($n + 1);
@deck[$k, $n] = @deck[$n, $k] if $k != $n;}}
sub print_cards
{print "$_->{pip} of $_->{suit}\n" foreach @{shift(@_)};} | 438Playing cards
| 2perl
| 5dqu2 |
import Darwin
let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))]) | 436Pick random element
| 17swift
| c0e9t |
class Card
{
protected static $suits = array( '', '', '', '' );
protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
protected $suit;
protected $suitOrder;
protected $pip;
protected $pipOrder;
protected $order;
public function __construct( $suit, $pip )
{
if( !in_array( $suit, self::$suits ) )
{
throw new InvalidArgumentException( 'Invalid suit' );
}
if( !in_array( $pip, self::$pips ) )
{
throw new InvalidArgumentException( 'Invalid pip' );
}
$this->suit = $suit;
$this->pip = $pip;
}
public function getSuit()
{
return $this->suit;
}
public function getPip()
{
return $this->pip;
}
public function getSuitOrder()
{
if( !isset( $this->suitOrder ) )
{
$this->suitOrder = array_search( $this->suit, self::$suits );
}
return $this->suitOrder;
}
public function getPipOrder()
{
if( !isset( $this->pipOrder ) )
{
$this->pipOrder = array_search( $this->pip, self::$pips );
}
return $this->pipOrder;
}
public function getOrder()
{
if( !isset( $this->order ) )
{
$suitOrder = $this->getSuitOrder();
$pipOrder = $this->getPipOrder();
$this->order = $pipOrder * count( self::$suits ) + $suitOrder;
}
return $this->order;
}
public function compareSuit( Card $other )
{
return $this->getSuitOrder() - $other->getSuitOrder();
}
public function comparePip( Card $other )
{
return $this->getPipOrder() - $other->getPipOrder();
}
public function compare( Card $other )
{
return $this->getOrder() - $other->getOrder();
}
public function __toString()
{
return $this->suit . $this->pip;
}
public static function getSuits()
{
return self::$suits;
}
public static function getPips()
{
return self::$pips;
}
}
class CardCollection
implements Countable, Iterator
{
protected $cards = array();
protected function __construct( array $cards = array() )
{
foreach( $cards as $card )
{
$this->addCard( $card );
}
}
public function count()
{
return count( $this->cards );
}
public function key()
{
return key( $this->cards );
}
public function valid()
{
return null !== $this->key();
}
public function next()
{
next( $this->cards );
}
public function current()
{
return current( $this->cards );
}
public function rewind()
{
reset( $this->cards );
}
public function sort( $comparer = null )
{
$comparer = $comparer?: function( $a, $b ) {
return $a->compare( $b );
};
if( !is_callable( $comparer ) )
{
throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );
}
usort( $this->cards, $comparer );
return $this;
}
public function toString()
{
return implode( ' ', $this->cards );
}
public function __toString()
{
return $this->toString();
}
protected function addCard( Card $card )
{
if( in_array( $card, $this->cards ) )
{
throw new DomainException( 'Card is already present in this collection' );
}
$this->cards[] = $card;
}
}
class Deck
extends CardCollection
{
public function __construct( $shuffled = false )
{
foreach( Card::getSuits() as $suit )
{
foreach( Card::getPips() as $pip )
{
$this->addCard( new Card( $suit, $pip ) );
}
}
if( $shuffled )
{
$this->shuffle();
}
}
public function deal( $amount = 1, CardCollection $cardCollection = null )
{
if( !is_int( $amount ) || $amount < 1 )
{
throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );
}
if( $amount > count( $this->cards ) )
{
throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );
}
$cards = array_splice( $this->cards, 0, $amount );
$cardCollection = $cardCollection?: new CardCollection;
foreach( $cards as $card )
{
$cardCollection->addCard( $card );
}
return $cardCollection;
}
public function shuffle()
{
shuffle( $this->cards );
}
}
class Hand
extends CardCollection
{
public function __construct() {}
public function play( $position )
{
if( !isset( $this->cards[ $position ] ) )
{
throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
}
$result = array_splice( $this->cards, $position, 1 );
return $result[ 0 ];
}
} | 438Playing cards
| 12php
| ojv85 |
null | 443Pi
| 17swift
| 87y0v |
require
class Integer
def popcount
to_s(2).count()
end
def pernicious?
popcount.prime?
end
end
p 1.step.lazy.select(&:pernicious?).take(25).to_a
p ( 888888877..888888888).select(&:pernicious?) | 441Pernicious numbers
| 14ruby
| t15f2 |
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())
} | 441Pernicious numbers
| 15rust
| za4to |
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
} | 455Perfect numbers
| 0go
| e2pa6 |
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;
}
print join "", @out[$i-15+4 .. $digits-2], "\n";
} | 443Pi
| 2perl
| sg3q3 |
def isPernicious( v:Long ) : Boolean = BigInt(v.toBinaryString.toList.filter( _ == '1' ).length).isProbablePrime(16) | 441Pernicious numbers
| 16scala
| yx763 |
def isPerfect = { n ->
n > 4 && (n == (2..Math.sqrt(n)).findAll { n % it == 0 }.inject(1) { factorSum, i -> factorSum += i + n/i })
} | 455Perfect numbers
| 7groovy
| ky7h7 |
perfect n =
n == sum [i | i <- [1..n-1], n `mod` i == 0] | 455Perfect numbers
| 8haskell
| 3afzj |
import random
class Card(object):
suits = (,,,)
pips = (,,,,,,,,,,,,)
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return %(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 %.join( (str(card) for card in self.deck))
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.shuffle()
return self.deck.pop(0) | 438Playing cards
| 3python
| 4fs5k |
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))") | 441Pernicious numbers
| 17swift
| fpudk |
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;
} | 455Perfect numbers
| 9java
| ij0os |
package main
import "fmt"
func main() {
demoPerm(3)
}
func demoPerm(n int) { | 456Permutations
| 0go
| alk1f |
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);
} | 455Perfect numbers
| 10javascript
| z1dt2 |
def makePermutations = { l -> l.permutations() } | 456Permutations
| 7groovy
| h6gj9 |
pips <- c("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
suit <- c("Clubs", "Diamonds", "Hearts", "Spades")
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,]
}
deck <- shuffle(deck)
deck
deck <- deal(deck)
deck <- deal(deck, FALSE) | 438Playing cards
| 13r
| 2oelg |
import Data.List (permutations)
main = mapM_ print (permutations [1,2,3]) | 456Permutations
| 8haskell
| z1nt0 |
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))
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*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 | 443Pi
| 3python
| 0r6sq |
null | 455Perfect numbers
| 11kotlin
| q5ex1 |
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; | 456Permutations
| 9java
| o7q8d |
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") | 443Pi
| 13r
| wufe5 |
<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> | 456Permutations
| 10javascript
| tpifm |
class Card
SUITS = %i[ Clubs Hearts Spades Diamonds ]
PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ]
@@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
end
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() | 438Playing cards
| 14ruby
| rz8gs |
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 | 455Perfect numbers
| 1lua
| s4wq8 |
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(); | 438Playing cards
| 15rust
| 73orc |
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 ", ")
} | 438Playing cards
| 16scala
| kmdhk |
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 } | 443Pi
| 14ruby
| ojm8v |
null | 456Permutations
| 11kotlin
| xu1ws |
use num_bigint::BigInt;
fn main() {
calc_pi();
}
fn calc_pi() {
let mut q = BigInt::from(1);
let mut r = BigInt::from(0);
let mut t = BigInt::from(1);
let mut k = BigInt::from(1);
let mut n = BigInt::from(3);
let mut l = BigInt::from(3);
let mut first = true;
loop {
if &q * 4 + &r - &t < &n * &t {
print!("{}", n);
if first {
print!(".");
first = false;
}
let nr = (&r - &n * &t) * 10;
n = (&q * 3 + &r) * 10 / &t - &n * 10;
q *= 10;
r = nr;
} else {
let nr = (&q * 2 + &r) * &l;
let nn = (&q * &k * 7 + 2 + &r * &l) / (&t * &l);
q *= &k;
t *= &l;
l += 2;
k += 1;
n = nn;
r = nr;
}
}
} | 443Pi
| 15rust
| ih9od |
object Pi {
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
var q, t, k: BigInt = 1
var n, l: BigInt = 3
def iterator: Iterator[BigInt] = new Iterator[BigInt] {
def hasNext = true
def next(): BigInt = {
while ((4 * q + r - t) >= (n * t)) {
val nr = (2 * q + r) * l
val nn = (q * (7 * k) + 2 + (r * l)) / (t * l)
q = q * k
t = t * l
l = l + 2
k = k + 1
n = nn
r = nr
}
val ret = n
val nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) / t) - (10 * n)
q = q * 10
r = nr
ret
}
}
}
def main(args: Array[String]): Unit = {
val it = new PiIterator
println("" + (it.head) + "." + (it.take(300).mkString))
}
} | 443Pi
| 16scala
| fp2d4 |
import Foundation | 438Playing cards
| 17swift
| gt049 |
local function permutation(a, n, cb)
if n == 0 then
cb(a)
else
for i = 1, n do
a[i], a[n] = a[n], a[i]
permutation(a, n - 1, cb)
a[i], a[n] = a[n], a[i]
end
end
end | 456Permutations
| 1lua
| q5ax0 |
type AnyWriteableObject={write:((textToOutput:string)=>any)};
function calcPi(pipe:AnyWriteableObject) {
let q = 1n, r=0n, t=1n, k=1n, n=3n, l=3n;
while (true) {
if (q * 4n + r - t < n* t) {
pipe.write(n.toString());
let nr = (r - n * t) * 10n;
n = (q * 3n + r) * 10n / t - n * 10n ;
q = q * 10n;
r = nr;
} else {
let nr = (q * 2n + r) * l;
let nn = (q * k * 7n + 2n + r * l) / (t * l);
q = q * k;
t = t * l;
l = l + 2n;
k = k + 1n;
n = nn;
r = nr;
}
}
}
calcPi(process.stdout); | 443Pi
| 20typescript
| l8hc8 |
sub perf {
my $n = shift;
my $sum = 0;
foreach my $i (1..$n-1) {
if ($n % $i == 0) {
$sum += $i;
}
}
return $sum == $n;
} | 455Perfect numbers
| 2perl
| voc20 |
function is_perfect($number)
{
$sum = 0;
for($i = 1; $i < $number; $i++)
{
if($number % $i == 0)
$sum += $i;
}
return $sum == $number;
}
echo . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
if(is_perfect($num))
echo $num . PHP_EOL;
} | 455Perfect numbers
| 12php
| 0gxsp |
def perf1(n):
sum = 0
for i in range(1, n):
if n% i == 0:
sum += i
return sum == n | 455Perfect numbers
| 3python
| uilvd |
is.perf <- function(n){
if (n==0|n==1) return(FALSE)
s <- seq (1,n-1)
x <- n%% s
m <- data.frame(s,x)
out <- with(m, s[x==0])
return(sum(out)==n)
}
is.perf(28)
sapply(c(6,28,496,8128,33550336),is.perf) | 455Perfect numbers
| 13r
| csy95 |
int main(){
char colourNames[][14] = { , , , , , , , , ,
, , , , , , };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf();
scanf(,&coreSide);
printf();
scanf(,&armLength);
printf();
for(i=0;i<16;i++){
printf(,i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf();
}
}
while(stroke==fill && fill==back){
printf();
scanf(,&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,);
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
} | 457Pentagram
| 5c
| 4dl5t |
def perf(n)
sum = 0
for i in 1...n
sum += i if n % i == 0
end
sum == n
end | 455Perfect numbers
| 14ruby
| 4dv5p |
package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1) | 457Pentagram
| 0go
| o7x8q |
fn main ( ) {
fn factor_sum(n: i32) -> i32 {
let mut v = Vec::new(); | 455Perfect numbers
| 15rust
| gfu4o |
pentagram -w 400 -o pentagram_hs.svg | 457Pentagram
| 8haskell
| 28yll |
import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill(p);
g.setColor(stroke);
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pentagram");
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 457Pentagram
| 9java
| 6ed3z |
def perfectInt(input: Int) = ((2 to sqrt(input).toInt).collect {case x if input % x == 0 => x + input / x}).sum == input - 1 | 455Perfect numbers
| 16scala
| j3g7i |
null | 457Pentagram
| 11kotlin
| dk0nz |
struct Pair {
uint64_t v1, v2;
};
struct Pair makePair(uint64_t a, uint64_t b) {
struct Pair r;
r.v1 = a;
r.v2 = b;
return r;
}
struct Pair solvePell(int n) {
int x = (int) sqrt(n);
if (x * x == n) {
return makePair(1, 0);
} else {
int y = x;
int z = 1;
int r = 2 * x;
struct Pair e = makePair(1, 0);
struct Pair f = makePair(0, 1);
uint64_t a = 0;
uint64_t b = 0;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
e = makePair(e.v2, r * e.v2 + e.v1);
f = makePair(f.v2, r * f.v2 + f.v1);
a = e.v2 + x * f.v2;
b = f.v2;
if (a * a - n * b * b == 1) {
break;
}
}
return makePair(a, b);
}
}
void test(int n) {
struct Pair r = solvePell(n);
printf(, n, r.v1, r.v2);
}
int main() {
test(61);
test(109);
test(181);
test(277);
return 0;
} | 458Pell's equation
| 5c
| 5n9uk |
local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:pentagram(x, y, radius, rotation, outlcolor, fillcolor)
local function pxy(i) return x+radius*cos(i*pi*2/5+rotation), y+radius*sin(i*pi*2/5+rotation) end
local x1, y1 = pxy(0)
for i = 1, 5 do
local x2, y2 = pxy(i*2) | 457Pentagram
| 1lua
| fb8dp |
sub permutation {
my ($perm,@set) = @_;
print "$perm\n" || return unless (@set);
permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$
}
my @input = (qw/a b c d/);
permutation('',@input); | 456Permutations
| 2perl
| 28mlf |
func perfect(n:Int) -> Bool {
var sum = 0
for i in 1..<n {
if n% i == 0 {
sum += i
}
}
return sum == n
}
for i in 1..<10000 {
if perfect(i) {
println(i)
}
} | 455Perfect numbers
| 17swift
| 5n2u8 |
use SVG;
my $tau = 2 * 4*atan2(1, 1);
my $dim = 200;
my $sides = 5;
for $v (0, 2, 4, 1, 3, 0) {
push @vx, 0.9 * $dim * cos($tau * $v / $sides);
push @vy, 0.9 * $dim * sin($tau * $v / $sides);
}
my $svg= SVG->new( width => 2*$dim, height => 2*$dim);
my $points = $svg->get_path(
x => \@vx,
y => \@vy,
-type => 'polyline',
);
$svg->rect (
width => "100%",
height => "100%",
style => {
'fill' => 'bisque'
}
);
$svg->polyline (
%$points,
style => {
'fill' => 'seashell',
'stroke' => 'blue',
'stroke-width' => 3,
},
transform => "translate($dim,$dim) rotate(-18)"
);
open $fh, '>', 'pentagram.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; | 457Pentagram
| 2perl
| j357f |
package main
import (
"fmt"
"math/big"
)
var big1 = new(big.Int).SetUint64(1)
func solvePell(nn uint64) (*big.Int, *big.Int) {
n := new(big.Int).SetUint64(nn)
x := new(big.Int).Set(n)
x.Sqrt(x)
y := new(big.Int).Set(x)
z := new(big.Int).SetUint64(1)
r := new(big.Int).Lsh(x, 1)
e1 := new(big.Int).SetUint64(1)
e2 := new(big.Int)
f1 := new(big.Int)
f2 := new(big.Int).SetUint64(1)
t := new(big.Int)
u := new(big.Int)
a := new(big.Int)
b := new(big.Int)
for {
t.Mul(r, z)
y.Sub(t, y)
t.Mul(y, y)
t.Sub(n, t)
z.Quo(t, z)
t.Add(x, y)
r.Quo(t, z)
u.Set(e1)
e1.Set(e2)
t.Mul(r, e2)
e2.Add(t, u)
u.Set(f1)
f1.Set(f2)
t.Mul(r, f2)
f2.Add(t, u)
t.Mul(x, f2)
a.Add(e2, t)
b.Set(f2)
t.Mul(a, a)
u.Mul(n, b)
u.Mul(u, b)
t.Sub(t, u)
if t.Cmp(big1) == 0 {
return a, b
}
}
}
func main() {
ns := []uint64{61, 109, 181, 277}
for _, n := range ns {
x, y := solvePell(n)
fmt.Printf("x^2 -%3d*y^2 = 1 for x =%-21s and y =%s\n", n, x, y)
}
} | 458Pell's equation
| 0go
| 8re0g |
import turtle
turtle.bgcolor()
t = turtle.Turtle()
t.color(, )
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill() | 457Pentagram
| 3python
| h64jw |
pell :: Integer -> (Integer, Integer)
pell n = go (x, 1, x * 2, 1, 0, 0, 1)
where
x = floor $ sqrt $ fromIntegral n
go (y, z, r, e1, e2, f1, f2) =
let y' = r * z - y
z' = (n - y' * y') `div` z
r' = (x + y') `div` z'
(e1', e2') = (e2, e2 * r' + e1)
(f1', f2') = (f2, f2 * r' + f1)
(a, b) = (f2', e2')
(b', a') = (a, a * x + b)
in if a' * a' - n * b' * b' == 1
then (a', b')
else go (y', z', r', e1', e2', f1', f2') | 458Pell's equation
| 8haskell
| l03ch |
p <- cbind(x = c(0, 1, 2,-0.5 , 2.5 ,0),
y = c(0, 1, 0,0.6, 0.6,0))
plot(p)
lines(p) | 457Pentagram
| 13r
| gf247 |
void Peano(int x, int y, int lg, int i1, int i2) {
if (lg == 1) {
lineto(3*x,3*y);
return;
}
lg = lg/3;
Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);
Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);
Peano(x+lg, y+lg, lg, i1, 1-i2);
Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);
Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);
Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);
Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);
Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);
Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);
}
int main(void) {
initwindow(1000,1000,);
Peano(0, 0, 1000, 0, 0);
getch();
cleardevice();
return 0;
} | 459Peano curve
| 5c
| q5bxc |
int getseq(char *s)
{
int r = 0;
int i = 1 << (SEQLEN - 1);
while (*s && i) {
switch (*s++) {
case 'H':
case 'h':
r |= i;
break;
case 'T':
case 't':
break;
default:
return -1;
}
i >>= 1;
}
return r;
}
void printseq(int seq)
{
int i;
for (i = SEQLEN - 1; i >= 0; --i)
printf(, seq & (1 << i) ? 'h' : 't');
}
int getuser(void)
{
int user;
char s[SEQLEN + 1];
printf(, SEQLEN);
while (1) {
if (scanf(, s) != 1) exit(1);
if ((user = getseq(s)) != -1) return user;
printf();
}
}
int getai(int user)
{
int ai;
printf(, SEQLEN);
if (user == -1)
ai = rand() & (1 << SEQLEN) - 1;
else
ai = (user >> 1) | ((~user << 1) & (1 << SEQLEN - 1));
printseq(ai);
printf();
return ai;
}
int rungame(int user, int ai)
{
int last3 = rand() & (1 << SEQLEN) - 1;
printf();
printseq(last3);
while (1) {
if (user == last3) {
printf();
return 1;
}
if (ai == last3) {
printf();
return 0;
}
last3 = ((last3 << 1) & (1 << SEQLEN) - 2) | (rand() & 1);
printf(, last3 & 1 ? 'h' : 't');
}
}
int main(void)
{
srand(time(NULL));
int playerwins = 0;
int totalgames = 0;
while (1) {
int user = -1;
int ai = -1;
printf();
if (rand() & 1) {
ai = getai(user);
user = getuser();
}
else {
user = getuser();
ai = getai(user);
}
playerwins += rungame(user, ai);
totalgames++;
printf(, playerwins, totalgames);
printf();
}
return 0;
} | 460Penney's game
| 5c
| 3a8za |
void firstCase(){
mpf_t a,b,c;
mpf_inits(a,b,c,NULL);
mpf_set_str(a,,10);
mpf_set_str(b,,10);
mpf_add(c,a,b);
gmp_printf(,20,c);
}
void pathologicalSeries(){
int n;
mpf_t v1, v2, vn, a1, a2, a3, t2, t3, prod;
mpf_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);
mpf_set_str(v1,,10);
mpf_set_str(v2,,10);
mpf_set_str(a1,,10);
mpf_set_str(a2,,10);
mpf_set_str(a3,,10);
for(n=3;n<=100;n++){
mpf_div(t2,a2,v2);
mpf_mul(prod,v1,v2);
mpf_div(t3,a3,prod);
mpf_add(vn,a1,t3);
mpf_sub(vn,vn,t2);
if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){
gmp_printf(,n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,vn);
}
mpf_set(v1,v2);
mpf_set(v2,vn);
}
}
void healthySeries(){
int n;
mpf_t num,denom,result;
mpq_t v1, v2, vn, a1, a2, a3, t2, t3, prod;
mpf_inits(num,denom,result,NULL);
mpq_inits(v1,v2,vn, a1, a2, a3, t2, t3, prod,NULL);
mpq_set_str(v1,,10);
mpq_set_str(v2,,10);
mpq_set_str(a1,,10);
mpq_set_str(a2,,10);
mpq_set_str(a3,,10);
for(n=3;n<=100;n++){
mpq_div(t2,a2,v2);
mpq_mul(prod,v1,v2);
mpq_div(t3,a3,prod);
mpq_add(vn,a1,t3);
mpq_sub(vn,vn,t2);
if((n>=3&&n<=8) || n==20 || n==30 || n==50 || n==100){
mpf_set_z(num,mpq_numref(vn));
mpf_set_z(denom,mpq_denref(vn));
mpf_div(result,num,denom);
gmp_printf(,n,(n==3)?1:(n>=4&&n<=7)?6:(n==8)?7:(n==20)?16:(n==30)?24:(n==50)?40:78,result);
}
mpq_set(v1,v2);
mpq_set(v2,vn);
}
}
int main()
{
mpz_t rangeProd;
firstCase();
printf();
pathologicalSeries();
printf();
healthySeries();
return 0;
} | 461Pathological floating point problems
| 5c
| rt9g7 |
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PellsEquation {
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
for ( int n : new int[] {61, 109, 181, 277, 8941} ) {
BigInteger[] pell = pellsEquation(n);
System.out.printf("x^2 -%3d * y^2 = 1 for:%n x =%s%n y =%s%n%n", n, format.format(pell[0]), format.format(pell[1]));
}
}
private static final BigInteger[] pellsEquation(int n) {
int a0 = (int) Math.sqrt(n);
if ( a0*a0 == n ) {
throw new IllegalArgumentException("ERROR 102: Invalid n = " + n);
}
List<Integer> continuedFrac = continuedFraction(n);
int count = 0;
BigInteger ajm2 = BigInteger.ONE;
BigInteger ajm1 = new BigInteger(a0 + "");
BigInteger bjm2 = BigInteger.ZERO;
BigInteger bjm1 = BigInteger.ONE;
boolean stop = (continuedFrac.size() % 2 == 1);
if ( continuedFrac.size() == 2 ) {
stop = true;
}
while ( true ) {
count++;
BigInteger bn = new BigInteger(continuedFrac.get(count) + "");
BigInteger aj = bn.multiply(ajm1).add(ajm2);
BigInteger bj = bn.multiply(bjm1).add(bjm2);
if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) {
return new BigInteger[] {aj, bj};
}
else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) {
stop = true;
}
if ( count == continuedFrac.size()-1 ) {
count = 0;
}
ajm2 = ajm1;
ajm1 = aj;
bjm2 = bjm1;
bjm1 = bj;
}
}
private static final List<Integer> continuedFraction(int n) {
List<Integer> answer = new ArrayList<Integer>();
int a0 = (int) Math.sqrt(n);
answer.add(a0);
int a = -a0;
int aStart = a;
int b = 1;
int bStart = b;
while ( true ) { | 458Pell's equation
| 9java
| 3aizg |
(def converge-to-six ((fn task1 [a b] (lazy-seq (cons a (task1 b (+ (- 111 (/ 1130 b)) (/ 3000 (* b a))))))) 2 -4))
(def values [3 4 5 6 7 8 20 30 50 100])
(pprint (sort (zipmap values (map double (map #(nth converge-to-six (dec %)) values)))))
(pprint (sort (zipmap values (map #(nth converge-to-six (dec %)) values)))) | 461Pathological floating point problems
| 6clojure
| bmukz |
import java.math.BigInteger
import kotlin.math.sqrt
class BIRef(var value: BigInteger) {
operator fun minus(b: BIRef): BIRef {
return BIRef(value - b.value)
}
operator fun times(b: BIRef): BIRef {
return BIRef(value * b.value)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BIRef
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value.hashCode()
}
override fun toString(): String {
return value.toString()
}
}
fun f(a: BIRef, b: BIRef, c: Int) {
val t = a.value
a.value = b.value
b.value = b.value * BigInteger.valueOf(c.toLong()) + t
}
fun solvePell(n: Int, a: BIRef, b: BIRef) {
val x = sqrt(n.toDouble()).toInt()
var y = x
var z = 1
var r = x shl 1
val e1 = BIRef(BigInteger.ONE)
val e2 = BIRef(BigInteger.ZERO)
val f1 = BIRef(BigInteger.ZERO)
val f2 = BIRef(BigInteger.ONE)
while (true) {
y = r * z - y
z = (n - y * y) / z
r = (x + y) / z
f(e1, e2, r)
f(f1, f2, r)
a.value = f2.value
b.value = e2.value
f(b, a, x)
if (a * a - BIRef(n.toBigInteger()) * b * b == BIRef(BigInteger.ONE)) {
return
}
}
}
fun main() {
val x = BIRef(BigInteger.ZERO)
val y = BIRef(BigInteger.ZERO)
intArrayOf(61, 109, 181, 277).forEach {
solvePell(it, x, y)
println("x^2 -%3d * y^2 = 1 for x =%,27d and y =%,25d".format(it, x.value, y.value))
}
} | 458Pell's equation
| 11kotlin
| nhqij |
import java.awt._
import java.awt.geom.Path2D
import javax.swing._
object Pentagram extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Pentagram") {
class Pentagram extends JPanel {
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
final private val degrees144 = Math.toRadians(144)
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawPentagram(g: Graphics2D, x: Int, y: Int, fill: Color): Unit = {
var (_x, _y, angle) = (x, y, 0.0)
val p = new Path2D.Float
p.moveTo(_x, _y)
for (i <- 0 until 5) {
val (x2, y2) = (_x + (Math.cos(angle) * 500).toInt, _y + (Math.sin(-angle) * 500).toInt)
p.lineTo(x2, y2)
_x = x2
_y = y2
angle -= degrees144
}
p.closePath()
g.setColor(fill)
g.fill(p)
g.setColor(Color.darkGray)
g.draw(p)
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER))
drawPentagram(g, 70, 250, new Color(0x6495ED))
}
}
add(new Pentagram, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
)
} | 457Pentagram
| 16scala
| e2kab |
import itertools
for values in itertools.permutations([1,2,3]):
print (values) | 456Permutations
| 3python
| vo929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.