code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
null
421Power set
11kotlin
db8nz
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
411Proper divisors
3python
76arm
import java.math.BigInteger; public class PopCount { public static void main(String[] args) { {
424Population count
9java
sgpq0
require 'matrix' def regress x, y, degree x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_r } } mx = Matrix[*x_data] my = Matrix.column_vector(y) ((mx.t * mx).inv * mx.t * my).transpose.to_a[0].map(&:to_f) end
417Polynomial regression
14ruby
6xy3t
use std::collections::BinaryHeap; use std::cmp::Ordering; use std::borrow::Cow; #[derive(Eq, PartialEq)] struct Item<'a> { priority: usize, task: Cow<'a, str>,
408Priority queue
15rust
dplny
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
422Plot coordinate pairs
3python
j657p
{ package Point; use Class::Spiffy -base; use Clone qw(clone); sub _print { my %self = %{shift()}; while (my ($k,$v) = each %self) { print "$k: $v\n"; } } sub members { no strict; grep { 1 == length and defined *$_{CODE} } keys %{*{__PACKAGE__."\::"}}; } sub new { my $class = shift; my %param = @_; $param{$_} = 0 for grep {!defined $param{$_}} members; bless \%param, $class; } sub copy_constructor { clone shift; } sub copy_assignment { my $self = shift; my $from = shift; $self->$_($from->$_) for $from->members; } field 'x'; field 'y'; } { package Circle; use base qw(Point); field 'r'; } { package main; $_->_print, print "\n" for ( Point->new, Point->new(x => 2), Point->new(y => 3), Point->new(x => 8, y => -5), ); my $p1 = Point->new(x => 8, y => -5); my $p2 = $p1->copy_constructor; print "we are really different objects, not just references ". "to the same instance\n" unless \$p1 eq \$p2; $p1->x(1); $p1->y(2); print $p1->x, "\n"; print $p1->y, "\n"; $p2->copy_assignment($p1); print $p2->x, "\n"; print $p2->y, "\n"; print "we now have the same values, but we are still ". "different objects\n" unless \$p1 eq \$p2; $_->_print, print "\n" for ( Circle->new, Circle->new(x => 1), Circle->new(y => 2), Circle->new(r => 3), Circle->new(x => 4, y => 5), Circle->new(x => 6, r => 7), Circle->new(y => 8, r => 9), Circle->new(x => 1, y => 2, r => 3), ); my $c = Circle->new(r => 4); print $c->r, "\n"; }
420Polymorphism
2perl
2o9lf
(() => { 'use strict';
424Population count
10javascript
nkxiy
object PolynomialRegression extends App { private def xy = Seq(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321).zipWithIndex.map(_.swap) private def polyRegression(xy: Seq[(Int, Int)]): Unit = { val r = xy.indices def average[U](ts: Iterable[U])(implicit num: Numeric[U]) = num.toDouble(ts.sum) / ts.size def x3m: Double = average(r.map(a => a * a * a)) def x4m: Double = average(r.map(a => a * a * a * a)) def x2ym = xy.reduce((a, x) => (a._1 + x._1 * x._1 * x._2, 0))._1.toDouble / xy.size def xym = xy.reduce((a, x) => (a._1 + x._1 * x._2, 0))._1.toDouble / xy.size val x2m: Double = average(r.map(a => a * a)) val (xm, ym) = (average(xy.map(_._1)), average(xy.map(_._2))) val (sxx, sxy) = (x2m - xm * xm, xym - xm * ym) val sxx2: Double = x3m - xm * x2m val sx2x2: Double = x4m - x2m * x2m val sx2y: Double = x2ym - x2m * ym val c: Double = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) val b: Double = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) val a: Double = ym - b * xm - c * x2m def abc(xx: Int) = a + b * xx + c * xx * xx println(s"y = $a + ${b}x + ${c}x^2") println(" Input Approximation") println(" x y y1") xy.foreach {el => println(f"${el._1}%2d ${el._2}%3d ${abc(el._1)}%5.1f")} } polyRegression(xy) }
417Polynomial regression
16scala
c8l93
require(numbers); V <- sapply(1:20000, Sigma, k = 0, proper = TRUE); ind <- which(V==max(V)); cat(" *** max number of divisors:", max(V), "\n"," *** for the following indices:",ind, "\n");
411Proper divisors
13r
5fkuy
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) y <- c(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0)
422Plot coordinate pairs
13r
4fl5y
null
421Power set
1lua
fpodp
my @table = map [ /([\d\.]+)/g ], split "\n", <<'TBL'; >= 0.00 < 0.06 := 0.10 >= 0.06 < 0.11 := 0.18 >= 0.11 < 0.16 := 0.26 >= 0.16 < 0.21 := 0.32 >= 0.21 < 0.26 := 0.38 >= 0.26 < 0.31 := 0.44 >= 0.31 < 0.36 := 0.50 >= 0.36 < 0.41 := 0.54 >= 0.41 < 0.46 := 0.58 >= 0.46 < 0.51 := 0.62 >= 0.51 < 0.56 := 0.66 >= 0.56 < 0.61 := 0.70 >= 0.61 < 0.66 := 0.74 >= 0.66 < 0.71 := 0.78 >= 0.71 < 0.76 := 0.82 >= 0.76 < 0.81 := 0.86 >= 0.81 < 0.86 := 0.90 >= 0.86 < 0.91 := 0.94 >= 0.91 < 0.96 := 0.98 >= 0.96 < 1.01 := 1.00 TBL sub convert { my $money = shift; for (@table) { return $_->[2] if $_->[0] <= $money and $_->[1] > $money } die "Can't find currency conversion for $money. Counterfeit?" } for (1 .. 10) { my $m = rand(1); printf "%.3f ->%g\n", $m, convert($m); }
415Price fraction
2perl
pleb0
import scala.collection.mutable.PriorityQueue case class Task(prio:Int, text:String) extends Ordered[Task] { def compare(that: Task)=that.prio compare this.prio }
408Priority queue
16scala
zeutr
function PrimeDecomposition( n ) local f = {} if IsPrime( n ) then f[1] = n return f end local i = 2 repeat while n % i == 0 do f[#f+1] = i n = n / i end repeat i = i + 1 until IsPrime( i ) until n == 1 return f end
418Prime decomposition
1lua
ikiot
class Point { protected $_x; protected $_y; public function __construct() { switch( func_num_args() ) { case 1: $point = func_get_arg( 0 ); $this->setFromPoint( $point ); break; case 2: $x = func_get_arg( 0 ); $y = func_get_arg( 1 ); $this->setX( $x ); $this->setY( $y ); break; default: throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' ); } } public function setFromPoint( Point $point ) { $this->setX( $point->getX() ); $this->setY( $point->getY() ); } public function getX() { return $this->_x; } public function setX( $x ) { if( !is_numeric( $x ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_x = (float) $x; } public function getY() { return $this->_y; } public function setY( $y ) { if( !is_numeric( $y ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_y = (float) $y; } public function output() { echo $this->__toString(); } public function __toString() { return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']'; } }
420Polymorphism
12php
sgwqs
null
424Population count
11kotlin
a2713
let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] func average(_ input: [Int]) -> Int { return input.reduce(0, +) / input.count } func polyRegression(x: [Int], y: [Int]) { let xm = average(x) let ym = average(y) let x2m = average(x.map { $0 * $0 }) let x3m = average(x.map { $0 * $0 * $0 }) let x4m = average(x.map { $0 * $0 * $0 * $0 }) let xym = average(zip(x,y).map { $0 * $1 }) let x2ym = average(zip(x,y).map { $0 * $0 * $1 }) let sxx = x2m - xm * xm let sxy = xym - xm * ym let sxx2 = x3m - xm * x2m let sx2x2 = x4m - x2m * x2m let sx2y = x2ym - x2m * ym let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) let a = ym - b * xm - c * x2m func abc(xx: Int) -> Int { return (a + b * xx) + (c * xx * xx) } print("y = \(a) + \(b)x + \(c)x^2\n") print(" Input Approximation") print(" x y y1") for i in 0 ..< x.count { let result = Double(abc(xx: i)) print(String(format: "%2d%3d %5.1f", x[i], y[i], result)) } } polyRegression(x: x, y: y)
417Polynomial regression
17swift
3w6z2
require 'gnuplot' x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] Gnuplot.open do |gp| Gnuplot::Plot.new( gp ) do |plot| plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds| ds.with = ds.notitle end end end
422Plot coordinate pairs
14ruby
kmghg
null
424Population count
1lua
evjac
import scala.swing.Swing.pair2Dimension import scala.swing.{ MainFrame, Panel, Rectangle } import java.awt.{ Color, Graphics2D, geom } object PlotCoordPairs extends scala.swing.SimpleSwingApplication {
422Plot coordinate pairs
16scala
a2h1n
require class Integer def proper_divisors return [] if self == 1 primes = prime_division.flat_map{|prime, freq| [prime] * freq} (1...primes.size).each_with_object([1]) do |n, res| primes.combination(n).map{|combi| res << combi.inject(:*)} end.flatten.uniq end end (1..10).map{|n| puts } size, select = (1..20_000).group_by{|n| n.proper_divisors.size}.max select.each do |n| puts end
411Proper divisors
14ruby
hmwjx
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x:%f y:%f>'% (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x:%f y:%f radius:%f>'% ( id(self), self.center.x, self.center.y, self.radius)
420Polymorphism
3python
vic29
trait ProperDivisors { fn proper_divisors(&self) -> Option<Vec<u64>>; } impl ProperDivisors for u64 { fn proper_divisors(&self) -> Option<Vec<u64>> { if self.le(&1) { return None; } let mut divisors: Vec<u64> = Vec::new(); for i in 1..*self { if *self% i == 0 { divisors.push(i); } } Option::from(divisors) } } fn main() { for i in 1..11 { println!("Proper divisors of {:2}: {:?}", i, i.proper_divisors().unwrap_or(vec![])); } let mut most_idx: u64 = 0; let mut most_divisors: Vec<u64> = Vec::new(); for i in 1..20_001 { let divs = i.proper_divisors().unwrap_or(vec![]); if divs.len() > most_divisors.len() { most_divisors = divs; most_idx = i; } } println!("In 1 to 20000, {} has the most proper divisors at {}", most_idx, most_divisors.len()); }
411Proper divisors
15rust
k9xh5
class Task: Comparable, CustomStringConvertible { var priority: Int var name: String init(priority: Int, name: String) { self.priority = priority self.name = name } var description: String { return "\(priority), \(name)" } } func ==(t1: Task, t2: Task) -> Bool { return t1.priority == t2.priority } func <(t1: Task, t2: Task) -> Bool { return t1.priority < t2.priority } struct TaskPriorityQueue { let heap: CFBinaryHeapRef = { var callBacks = CFBinaryHeapCallBacks(version: 0, retain: { UnsafePointer(Unmanaged<Task>.fromOpaque(COpaquePointer($1)).retain().toOpaque()) }, release: { Unmanaged<Task>.fromOpaque(COpaquePointer($1)).release() }, copyDescription: nil, compare: { (ptr1, ptr2, _) in let t1: Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr1)).takeUnretainedValue() let t2: Task = Unmanaged<Task>.fromOpaque(COpaquePointer(ptr2)).takeUnretainedValue() return t1 == t2? CFComparisonResult.CompareEqualTo: t1 < t2? CFComparisonResult.CompareLessThan: CFComparisonResult.CompareGreaterThan }) return CFBinaryHeapCreate(nil, 0, &callBacks, nil) }() var count: Int { return CFBinaryHeapGetCount(heap) } mutating func push(t: Task) { CFBinaryHeapAddValue(heap, UnsafePointer(Unmanaged.passUnretained(t).toOpaque())) } func peek() -> Task { return Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue() } mutating func pop() -> Task { let result = Unmanaged<Task>.fromOpaque(COpaquePointer(CFBinaryHeapGetMinimum(heap))).takeUnretainedValue() CFBinaryHeapRemoveMinimumValue(heap) return result } } var pq = TaskPriorityQueue() pq.push(Task(priority: 3, name: "Clear drains")) pq.push(Task(priority: 4, name: "Feed cat")) pq.push(Task(priority: 5, name: "Make tea")) pq.push(Task(priority: 1, name: "Solve RC tasks")) pq.push(Task(priority: 2, name: "Tax return")) while pq.count!= 0 { print(pq.pop()) }
408Priority queue
17swift
ik9o0
setClass("point", representation( x="numeric", y="numeric"), prototype( x=0, y=0)) p1 <- new("point", x=3) p1@x setMethod("print", signature("point"), function(x, ...) { cat("This is a point, with location, (", x@x, ",", x@y, ").\n") }) print(p1) setClass("circle", representation( centre="point", r="numeric"), prototype( centre=new("point"), r=1)) circS4 <- new("circle", r=5.5) circS4@r circS4@centre@x setMethod("print", signature("circle"), function(x, ...) { cat("This is a circle, with radius", x@r, "and centre (", x@centre@x, ",", x@centre@y, ").\n") }) print(circS4)
420Polymorphism
13r
9s6mg
>>> import bisect >>> _cin = [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01] >>> _cout = [.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00] >>> def pricerounder(pricein): return _cout[ bisect.bisect_right(_cin, pricein) ]
415Price fraction
3python
12wpc
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}" println(f" n cnt PROPER DIVISORS") val (count, list) = (1 to 20000).foldLeft( (0, List[Int]()) ) { (max, i) => val divisors = properDivisors(i) if (i <= 10 || i == 100) println( format(i, divisors) ) if (max._1 < divisors.length) (divisors.length, List(i)) else if (max._1 == divisors.length) (divisors.length, max._2 ::: List(i)) else max } list.foreach( number => println(f"$number%5d ${properDivisors(number).length}") )
411Proper divisors
16scala
120pf
class Point attr_accessor :x,:y def initialize(x=0, y=0) self.x = x self.y = y end def to_s end end class Circle < Point attr_accessor :r def initialize(x=0, y=0, r=0) self.x = x self.y = y self.r = r end def to_s end end
420Polymorphism
14ruby
5d2uj
price_fraction <- function(x) { stopifnot(all(x >= 0 & x <= 1)) breaks <- seq(0.06, 1.01, 0.05) values <- c(.1, .18, .26, .32, .38, .44, .5, .54, .58, .62, .66, .7, .74, .78, .82, .86, .9, .94, .98, 1) indices <- sapply(x, function(x) which(x < breaks)[1]) values[indices] } price_fraction(c(0, .01, 0.06, 0.25, 1))
415Price fraction
13r
hmpjj
object PointCircle extends App { class Point(x: Int = 0, y: Int = 0) { def copy(x: Int = this.x, y: Int = this.y): Point = new Point(x, y) override def toString = s"Point x: $x, y: $y" } object Point { def apply(x: Int = 0, y: Int = 0): Point = new Point(x, y) } case class Circle(x: Int = 0, y: Int = 0, r: Int = 0) extends Point(x, y) { def copy(r: Int): Circle = Circle(x, y, r) override def toString = s"Circle x: $x, y: $y, r: $r" } val p = Point() val c = Circle() println("Instantiated ", p) println("Instantiated ", c) val q = Point(5, 6) println("Instantiated ", q) val r = q.copy(y = 7)
420Polymorphism
16scala
734r9
use Algorithm::Combinatorics "subsets"; my @S = ("a","b","c"); my @PS; my $iter = subsets(\@S); while (my $p = $iter->next) { push @PS, "[@$p]" } say join(" ",@PS);
421Power set
2perl
j647f
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
425Primality by trial division
0go
nkwi1
func properDivs1(n: Int) -> [Int] { return filter (1 ..< n) { n% $0 == 0 } }
411Proper divisors
17swift
jye74
use strict; use warnings; use feature 'say'; sub evil { my $i = 0; sub { $i++ while population_count($i) % 2; $i++ } } sub odious { my $i = 0; sub { $i++ until population_count($i) % 2; $i++ } } sub population_count { my $n = shift; my $c; for ($c = 0; $n; $n >>= 1) { $c += $n & 1 } $c } say join ' ', map { population_count 3**$_ } 0 .. 30 - 1; my (@evil, @odious); my ($evil, $odious) = (evil, odious); push( @evil, $evil->() ), push @odious, $odious->() for 1 .. 30; say "Evil @evil"; say "Odious @odious";
424Population count
2perl
9sfmn
<?php function get_subset($binary, $arr) { $subset = array(); foreach (range(0, count($arr)-1) as $i) { if ($binary[$i]) { $subset[] = $arr[count($arr) - $i - 1]; } } return $subset; } function print_array($arr) { if (count($arr) > 0) { echo join(, $arr); } else { echo ; } echo '<br>'; } function print_power_sets($arr) { echo . join(, $arr) . ; foreach (power_set($arr) as $subset) { print_array($subset); } } function power_set($arr) { $binary = array(); foreach (range(1, count($arr)) as $i) { $binary[] = false; } $n = count($arr); $powerset = array(); while (count($binary) <= count($arr)) { $powerset[] = get_subset($binary, $arr); $i = 0; while (true) { if ($binary[$i]) { $binary[$i] = false; $i += 1; } else { $binary[$i] = true; break; } } $binary[$i] = true; } return $powerset; } print_power_sets(array()); print_power_sets(array('singleton')); print_power_sets(array('dog', 'c', 'b', 'a')); ?>
421Power set
12php
t1if1
def isPrime = { it == 2 || it > 1 && (2..Math.max(2, (int) Math.sqrt(it))).every{ k -> it % k != 0 } } (0..20).grep(isPrime)
425Primality by trial division
7groovy
sgbq1
def rescale_price_fraction(value) raise ArgumentError, if value < 0 || value >= 1.01 if value < 0.06 then 0.10 elsif value < 0.11 then 0.18 elsif value < 0.16 then 0.26 elsif value < 0.21 then 0.32 elsif value < 0.26 then 0.38 elsif value < 0.31 then 0.44 elsif value < 0.36 then 0.50 elsif value < 0.41 then 0.54 elsif value < 0.46 then 0.58 elsif value < 0.51 then 0.62 elsif value < 0.56 then 0.66 elsif value < 0.61 then 0.70 elsif value < 0.66 then 0.74 elsif value < 0.71 then 0.78 elsif value < 0.76 then 0.82 elsif value < 0.81 then 0.86 elsif value < 0.86 then 0.90 elsif value < 0.91 then 0.94 elsif value < 0.96 then 0.98 elsif value < 1.01 then 1.00 end end
415Price fraction
14ruby
euqax
isPrime n = n==2 || n>2 && all ((> 0).rem n) (2:[3,5..floor.sqrt.fromIntegral $ n+1])
425Primality by trial division
8haskell
un6v2
fn fix_price(num: f64) -> f64 { match num { 0.96...1.00 => 1.00, 0.91...0.96 => 0.98, 0.86...0.91 => 0.94, 0.81...0.86 => 0.90, 0.76...0.81 => 0.86, 0.71...0.76 => 0.82, 0.66...0.71 => 0.78, 0.61...0.66 => 0.74, 0.56...0.61 => 0.70, 0.51...0.56 => 0.66, 0.46...0.51 => 0.62, 0.41...0.46 => 0.58, 0.36...0.41 => 0.54, 0.31...0.36 => 0.50, 0.26...0.31 => 0.44, 0.21...0.26 => 0.38, 0.16...0.21 => 0.32, 0.11...0.16 => 0.26, 0.06...0.11 => 0.18, 0.00...0.06 => 0.10,
415Price fraction
15rust
w5se4
class RCPoint: Printable { var x: Int var y: Int init(x: Int = 0, y: Int = 0) { self.x = x self.y = y } convenience init(p: RCPoint) { self.init(x:p.x, y:p.y) } var description: String { return "<RCPoint x: \(self.x) y: \(self.y)>" } } class RCCircle: RCPoint { var r: Int init(p: RCPoint, r: Int = 0) { self.r = r super.init(x:p.x, y:p.y) } init(x: Int = 0, y: Int = 0, r: Int = 0) { self.r = r super.init(x:x, y:y) } convenience init(c: RCCircle) { self.init(x:c.x, y:c.y, r:c.r) } override var description: String { return "<RCCircle x: \(x) y: \(y) r: \(r)>" } } println(RCPoint()) println(RCPoint(x:3)) println(RCPoint(x:3, y:4)) println(RCCircle()) println(RCCircle(x:3)) println(RCCircle(x:3, y:4)) println(RCCircle(x:3, y:4, r:7)) let p = RCPoint(x:1, y:2) println(RCCircle(p:p)) println(RCCircle(p:p, r:7)) println(p.x)
420Polymorphism
17swift
unlvg
function convertToBinary($integer) { $binary = ; do { $quotient = (int) ($integer / 2); $binary .= $integer % 2; $integer = $quotient; } while ($quotient > 0); return $binary; } function getPopCount($integer) { $binary = convertToBinary($integer); $offset = 0; $popCount = 0; do { $pos = strpos($binary, , $offset); if($pos !== FALSE) $popCount++; $offset = $pos + 1; } while ($pos !== FALSE); return $popCount; } function print3PowPopCounts() { for ($p = 0; $p < 30; $p++) { echo . getPopCount(3 ** $p); } } function printFirst30Evil() { $counter = 0; $pops = 0; while ($pops < 30) { $popCount = getPopCount($counter); if ($popCount % 2 == 0) { echo . $counter; $pops++; } $counter++; } } function printFirst30Odious() { $counter = 1; $pops = 0; while ($pops < 30) { $popCount = getPopCount($counter); if ($popCount % 2 != 0) { echo . $counter; $pops++; } $counter++; } } echo ; print3PowPopCounts(); echo ; printFirst30Evil(); echo ; printFirst30Odious();
424Population count
12php
wuhep
def priceFraction(x:Double)=x match { case n if n>=0 && n<0.06 => 0.10 case n if n<0.11 => 0.18 case n if n<0.36 => ((((n*100).toInt-11)/5)*6+26)/100.toDouble case n if n<0.96 => ((((n*100).toInt-31)/5)*4+50)/100.toDouble case _ => 1.00 } def testPriceFraction()= for(n <- 0.00 to (1.00, 0.01)) println("%.2f %.2f".format(n, priceFraction(n)))
415Price fraction
16scala
sroqo
sub prime_factors { my ($n, $d, @out) = (shift, 1); while ($n > 1 && $d++) { $n /= $d, push @out, $d until $n % $d; } @out } print "@{[prime_factors(1001)]}\n";
418Prime decomposition
2perl
gzg4e
def list_powerset(lst): result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result def list_powerset2(lst): return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]]) def powerset(s): return frozenset(map(frozenset, list_powerset(list(s))))
421Power set
3python
hygjw
public static boolean prime(long a){ if(a == 2){ return true; }else if(a <= 1 || a % 2 == 0){ return false; } long max = (long)Math.sqrt(a); for(long n= 3; n <= max; n+= 2){ if(a % n == 0){ return false; } } return true; }
425Primality by trial division
9java
mqnym
let ranges = [ (0.00..<0.06, 0.10), (0.06..<0.11, 0.18), (0.11..<0.16, 0.26), (0.16..<0.21, 0.32), (0.21..<0.26, 0.38), (0.26..<0.31, 0.44), (0.31..<0.36, 0.50), (0.36..<0.41, 0.54), (0.41..<0.46, 0.58), (0.46..<0.51, 0.62), (0.51..<0.56, 0.66), (0.56..<0.61, 0.70), (0.61..<0.66, 0.74), (0.66..<0.71, 0.78), (0.71..<0.76, 0.82), (0.76..<0.81, 0.86), (0.81..<0.86, 0.90), (0.86..<0.91, 0.94), (0.91..<0.96, 0.98), (0.96..<1.01, 1.00) ] func adjustDouble(_ val: Double, accordingTo ranges: [(Range<Double>, Double)]) -> Double? { return ranges.first(where: { $0.0.contains(val) })?.1 } for val in stride(from: 0.0, through: 1, by: 0.01) { let strFmt = { String(format: "%.2f", $0) } print("\(strFmt(val)) -> \(strFmt(adjustDouble(val, accordingTo: ranges)?? val))") }
415Price fraction
17swift
avx1i
function isPrime(n) { if (n == 2 || n == 3 || n == 5 || n == 7) { return true; } else if ((n < 2) || (n % 2 == 0)) { return false; } else { for (var i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } }
425Primality by trial division
10javascript
vi325
>>> def popcount(n): return bin(n).count() ... >>> [popcount(3**i) for i in range(30)] [1, 2, 2, 4, 3, 6, 6, 5, 6, 8, 9, 13, 10, 11, 14, 15, 11, 14, 14, 17, 17, 20, 19, 22, 16, 18, 24, 30, 25, 25] >>> evil, odious, i = [], [], 0 >>> while len(evil) < 30 or len(odious) < 30: ... p = popcount(i) ... if p% 2: odious.append(i) ... else: evil.append(i) ... i += 1 ... >>> evil[:30] [0, 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, 23, 24, 27, 29, 30, 33, 34, 36, 39, 40, 43, 45, 46, 48, 51, 53, 54, 57, 58] >>> odious[:30] [1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59] >>>
424Population count
3python
c0t9q
for each element in the set: for each subset constructed so far: new subset = (subset + element)
421Power set
13r
gtv47
library(bit64) popCount <- function(x) sum(as.numeric(strsplit(as.bitstring(as.integer64(x)), "")[[1]])) finder <- function() { odious <- evil <- integer(0) x <- odiousLength <- evilLength <- 0 while(evilLength + odiousLength != 60) { if(popCount(x) %% 2 == 0) evil[evilLength + 1] <- x else odious[odiousLength + 1] <- x x <- x + 1 evilLength <- length(evil) odiousLength <- length(odious) } cat("The pop count of the 1st 30 powers of 3 are:", sapply(3^(0:29), popCount), "\n") cat("The first 30 evil numbers are:", evil, "\n") cat("The first 30 odious numbers are:", odious) } finder()
424Population count
13r
6wi3e
class Array def power_set inject([[]]) do |acc, you| ret = [] acc.each do |i| ret << i ret << i + [you] end ret end end def func_power_set inject([[]]) { |ps,item| ps + ps.map { |e| e + [item] } } end end require 'set' class Set def powerset inject(Set[Set[]]) do |ps, item| ps.union ps.map {|e| e.union (Set.new [item])} end end end p [1,2,3,4].power_set p %w(one two three).func_power_set p Set[1,2,3].powerset
421Power set
14ruby
b97kq
null
425Primality by trial division
11kotlin
t1sf0
from __future__ import print_function import sys from itertools import islice, cycle, count try: from itertools import compress except ImportError: def compress(data, selectors): return (d for d, s in zip(data, selectors) if s) def is_prime(n): return list(zip((True, False), decompose(n)))[-1][0] class IsPrimeCached(dict): def __missing__(self, n): r = is_prime(n) self[n] = r return r is_prime_cached = IsPrimeCached() def croft(): for p in (2, 3, 5): yield p roots = {9: 3, 25: 5} primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29)) selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0) for q in compress( islice(count(7), 0, None, 2), cycle(selectors) ): if q in roots: p = roots[q] del roots[q] x = q + 2*p while x in roots or (x% 30) not in primeroots: x += 2*p roots[x] = p else: roots[q*q] = q yield q primes = croft def decompose(n): for p in primes(): if p*p > n: break while n% p == 0: yield p n if n > 1: yield n if __name__ == '__main__': import time for m in primes(): p = 2 ** m - 1 print( .format(m, p) ) start = time.time() for factor in decompose(p): print(factor, end=' ') sys.stdout.flush() print( .format( time.time()-start ) ) if m >= 59: break
418Prime decomposition
3python
r3rgq
use std::collections::BTreeSet; fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> { if set.is_empty() { let mut powerset = BTreeSet::new(); powerset.insert(set); return powerset; }
421Power set
15rust
pcjbu
import scala.compat.Platform.currentTime object Powerset extends App { def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)} assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4), Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4))) println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") }
421Power set
16scala
evbab
findfactors <- function(num) { x <- NULL firstprime<- 2; secondprime <- 3; everyprime <- num while( everyprime!= 1 ) { while( everyprime%%firstprime == 0 ) { x <- c(x, firstprime) everyprime <- floor(everyprime/ firstprime) } firstprime <- secondprime secondprime <- secondprime + 2 } x } print(findfactors(1027*4))
418Prime decomposition
13r
uduvx
class Integer def popcount digits(2).count(1) end def evil? self >= 0 && popcount.even? end end puts , (0...30).map{|n| (3**n).popcount}.join(' ') puts , 0.step.lazy.select(&:evil?).first(30).join(' ') puts , 0.step.lazy.reject(&:evil?).first(30).join(' ')
424Population count
14ruby
2o3lw
fn main() { let mut num = 1u64; let mut vec = Vec::new(); for _ in 0..30 { vec.push(num.count_ones()); num *= 3; } println!("pop count of 3^0, 3^1 ... 3^29:\n{:?}",vec); let mut even = Vec::new(); let mut odd = Vec::new(); num = 1; while even.len() < 30 || odd.len() < 30 { match 0 == num.count_ones()%2 { true if even.len() < 30 => even.push(num), false if odd.len() < 30 => odd.push(num), _ => {} } num += 1; } println!("\nFirst 30 even pop count:\n{:?}",even); println!("\nFirst 30 odd pop count:\n{:?}",odd); }
424Population count
15rust
vi62t
import java.lang.Long.bitCount object PopCount extends App { val nNumber = 30 def powersThree(start: Long): LazyList[Long] = start #:: powersThree(start * 3L) println("Population count of 3:") println(powersThree(1L).map(bitCount).take(nNumber).mkString(", ")) def series(start: Long): LazyList[Long] = start #:: series(start + 1L) println("Evil numbers:") println(series(0L).filter(bitCount(_) % 2 == 0).take(nNumber).mkString(", ")) println("Odious numbers:") println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", ")) }
424Population count
16scala
4f950
function IsPrime( n ) if n <= 1 or ( n ~= 2 and n % 2 == 0 ) then return false end for i = 3, math.sqrt(n), 2 do if n % i == 0 then return false end end return true end
425Primality by trial division
1lua
za0ty
irb(main):001:0> require 'prime' => true irb(main):003:0> 2543821448263974486045199.prime_division => [[701, 1], [1123, 2], [2411, 1], [1092461, 2]]
418Prime decomposition
14ruby
jyj7x
func populationCount(n: Int) -> Int { guard n >= 0 else { fatalError() } return String(n, radix: 2).filter({ $0 == "1" }).count } let pows = (0...) .lazy .map({ Int(pow(3, Double($0))) }) .map(populationCount) .prefix(30) let evils = (0...) .lazy .filter({ populationCount(n: $0) & 1 == 0 }) .prefix(30) let odious = (0...) .lazy .filter({ populationCount(n: $0) & 1 == 1 }) .prefix(30) print("Powers:", Array(pows)) print("Evils:", Array(evils)) print("Odious:", Array(odious))
424Population count
17swift
l8zc2
func powersetFrom<T>(_ elements: Set<T>) -> Set<Set<T>> { guard elements.count > 0 else { return [[]] } var powerset: Set<Set<T>> = [[]] for element in elements { for subset in powerset { powerset.insert(subset.union([element])) } } return powerset }
421Power set
17swift
kmrhx
[package] name = "prime_decomposition" version = "0.1.1" edition = "2018" [dependencies] num-bigint = "0.3.0" num-traits = "0.2.12"
418Prime decomposition
15rust
hmhj2
import annotation.tailrec import collection.parallel.mutable.ParSeq object PrimeFactors extends App { def factorize(n: Long): List[Long] = { @tailrec def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = { tuple match { case (1, _, acc, _) => acc case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt)) case (n, k, acc, sqr) if (k < sqr) => factors(n, k + 1, acc, sqr) case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0)) } } factors((n, 2, List[Long](), Math.sqrt(n).toInt)) } def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1 def sieve(nums: Stream[Int]): Stream[Int] = Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
418Prime decomposition
16scala
plpbj
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [2]string{ "FFFFFF",
426Pinstripe/Printer
0go
5d6ul
package main import ( "log" "os" "os/exec" ) func main() { args := []string{ "-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav", "-d", "trim", "4", "6", "repeat", "5", } cmd := exec.Command("sox", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
427Play recorded sounds
0go
vit2m
func primeDecomposition<T: BinaryInteger>(of n: T) -> [T] { guard n > 2 else { return [] } func step(_ x: T) -> T { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = T(Double(n).squareRoot()) var d: T = 1 var q: T = n% 2 == 0? 2: 3 while q <= maxQ && n% q!= 0 { q = step(d) d += 1 } return q <= maxQ? [q] + primeDecomposition(of: n / q): [n] } for prime in Eratosthenes(upTo: 60) { let m = Int(pow(2, Double(prime))) - 1 let decom = primeDecomposition(of: m) print("2^\(prime) - 1 = \(m) => \(decom)") }
418Prime decomposition
17swift
767rq
package main import "fmt" func gcd(a, b uint) uint { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b uint) uint { return a / gcd(a, b) * b } func ipow(x, p uint) uint { prod := uint(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod }
428Pisano period
0go
4f352
import time from pygame import mixer mixer.init(frequency=16000) s1 = mixer.Sound('test.wav') s2 = mixer.Sound('test2.wav') s1.play(-1) time.sleep(0.5) s2.play() time.sleep(2) s2.play(2) time.sleep(10) s1.set_volume(0.1) time.sleep(5) s1.set_volume(1) time.sleep(5) s1.stop() s2.stop() mixer.quit()
427Play recorded sounds
3python
nkaiz
import qualified Data.Text as T main = do putStrLn "PisanoPrime(p,2) for prime p lower than 15" putStrLn . see 15 . map (`pisanoPrime` 2) . filter isPrime $ [1 .. 15] putStrLn "PisanoPrime(p,1) for prime p lower than 180" putStrLn . see 15 . map (`pisanoPrime` 1) . filter isPrime $ [1 .. 180] let ns = [1 .. 180] :: [Int] let xs = map pisanoPeriod ns let ys = map pisano ns let zs = map pisanoConjecture ns putStrLn "Pisano(m) for m from 1 to 180" putStrLn . see 15 $ map pisano [1 .. 180] putStrLn $ "map pisanoPeriod [1..180] == map pisano [1..180] = " ++ show (xs == ys) putStrLn $ "map pisanoPeriod [1..180] == map pisanoConjecture [1..180] = " ++ show (ys == zs) bagOf :: Int -> [a] -> [[a]] bagOf _ [] = [] bagOf n xs = let (us, vs) = splitAt n xs in us: bagOf n vs see :: Show a => Int -> [a] -> String see n = unlines . map unwords . bagOf n . map (T.unpack . T.justifyRight 3 ' ' . T.pack . show) fibMod :: Integral a => a -> [a] fibMod 1 = repeat 0 fibMod n = fib where fib = 0: 1: zipWith (\x y -> rem (x + y) n) fib (tail fib) pisanoPeriod :: Integral a => a -> a pisanoPeriod m | m <= 0 = 0 pisanoPeriod 1 = 1 pisanoPeriod m = go 1 (tail $ fibMod m) where go t (0:1:_) = t go t (_:xs) = go (succ t) xs powMod :: Integral a => a -> a -> a -> a powMod _ _ k | k < 0 = error "negative power" powMod m _ _ | 1 == abs m = 0 powMod m p k | 1 == abs p = mod v m where v | 1 == p || even k = 1 | otherwise = p powMod m p k = go p k where to x y = mod (x * y) m go _ 0 = 1 go u 1 = mod u m go u i | even i = to w w | otherwise = to u (to w w) where w = go u (quot i 2) probablyPrime :: Integral a => a -> Bool probablyPrime p | p < 2 || even p = 2 == p | otherwise = 1 == powMod p 2 (p - 1) primes :: Integral a => [a] primes = 2: 3: 5: 7: [ p | p <- [11,13 ..] , isPrime p ] limitDivisor :: Integral a => a -> a limitDivisor = floor . (+ 0.05) . sqrt . fromIntegral isPrime :: Integral a => a -> Bool isPrime p | not $ probablyPrime p = False isPrime p = go primes where stop = limitDivisor p go (n:_) | stop < n = True go (n:ns) = (0 /= rem p n) && go ns go [] = True factor :: Integral a => a -> [(a, a)] factor n | n <= 1 = [] factor n = go n primes where fun x d c | 0 /= rem x d = (x, c) | otherwise = fun (quot x d) d (succ c) go 1 _ = [] go _ [] = [] go x (d:ds) | 0 /= rem x d = go x $ dropWhile ((0 /=) . rem x) ds go x (d:ds) = let (u, c) = fun (quot x d) d 1 in (d, c): go u ds pisanoPrime :: Integral a => a -> a -> a pisanoPrime p k | p <= 0 || k < 0 = 0 pisanoPrime p k = pisanoPeriod $ p ^ k pisano :: Integral a => a -> a pisano m | m < 1 = 0 pisano 1 = 1 pisano m = foldl1 lcm . map (uncurry pisanoPrime) $ factor m pisanoConjecture :: Integral a => a -> a pisanoConjecture m | m < 1 = 0 pisanoConjecture 1 = 1 pisanoConjecture m = foldl1 lcm . map (uncurry pisanoPrime') $ factor m where pisanoPrime' p k = (p ^ (k - 1)) * pisanoPeriod p
428Pisano period
8haskell
q47x9
library(sound) media_dir <- file.path(Sys.getenv("SYSTEMROOT"), "Media") chimes <- loadSample(file.path(media_dir, "chimes.wav")) chord <- loadSample(file.path(media_dir, "chord.wav")) play(appendSample(chimes, chord)) play(chimes + chord) play(cutSample(chimes, 0, 0.2)) for(i in 1:3) play(chimes) three_chimes <- lapply(vector(3, mode = "list"), function(x) chimes) play(do.call(appendSample, three_chimes)) play(3 * chimes) play(stereo(chimes, chord))
427Play recorded sounds
13r
0rksg
require 'win32/sound' include Win32 sound1 = ENV['WINDIR'] + '\Media\Windows XP Startup.wav' sound2 = ENV['WINDIR'] + '\Media\Windows XP Shutdown.wav' puts [sound1, sound2].each do |s| t1 = Time.now Sound.play(s) puts end puts [sound1, sound2].each {|s| Sound.play(s, Sound::ASYNC)} puts <<END the above only plays the second sound2 because the library only appears to be able to play one sound at a time. END puts puts Time.now Sound.play(sound1, Sound::ASYNC + Sound::LOOP) sleep 10 Sound.stop puts Time.now puts vol_left, vol_right = Sound.wave_volume Sound.play(sound1, Sound::ASYNC) sleep 1 puts Sound.set_wave_volume(vol_left, 0) sleep 1 puts Sound.set_wave_volume(0, vol_right) sleep 1 puts Sound.set_wave_volume(vol_left, vol_right) sleep 1 puts
427Play recorded sounds
14ruby
fpwdr
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class PisanoPeriod { public static void main(String[] args) { System.out.printf("Print pisano(p^2) for every prime p lower than 15%n"); for ( long i = 2 ; i < 15 ; i++ ) { if ( isPrime(i) ) { long n = i*i; System.out.printf("pisano(%d) =%d%n", n, pisano(n)); } } System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n"); for ( long n = 2 ; n < 180 ; n++ ) { if ( isPrime(n) ) { System.out.printf("pisano(%d) =%d%n", n, pisano(n)); } } System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n"); for ( long n = 1 ; n <= 180 ; n++ ) { System.out.printf("%3d ", pisano(n)); if ( n % 10 == 0 ) { System.out.printf("%n"); } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static Map<Long,Long> PERIOD_MEMO = new HashMap<>(); static { PERIOD_MEMO.put(2L, 3L); PERIOD_MEMO.put(3L, 8L); PERIOD_MEMO.put(5L, 20L); }
428Pisano period
9java
pcvb3
import AVFoundation
427Play recorded sounds
17swift
dbenh
use strict; use warnings; use feature 'say'; use ntheory qw(primes factor_exp lcm); sub pisano_period_pp { my($a, $b, $n, $k) = (0, 1, $_[0]**$_[1]); while (++$k) { ($a, $b) = ($b, ($a+$b) % $n); return $k if $a == 0 and $b == 1; } } sub pisano_period { (lcm map { pisano_period_pp($$_[0],$$_[1]) } factor_exp($_[0])) or 1; } sub display { (sprintf "@{['%5d' x @_]}", @_) =~ s/(.{75})/$1\n/gr } say "Pisano periods for squares of primes p <= 50:\n", display( map { pisano_period_pp($_, 2) } @{primes(1, 50)} ), "\nPisano periods for primes p <= 180:\n", display( map { pisano_period_pp($_, 1) } @{primes(1, 180)} ), "\n\nPisano periods for integers n from 1 to 180:\n", display( map { pisano_period ($_ ) } 1..180 );
428Pisano period
2perl
fped7
from sympy import isprime, lcm, factorint, primerange from functools import reduce def pisano1(m): if m < 2: return 1 lastn, n = 0, 1 for i in range(m ** 2): lastn, n = n, (lastn + n)% m if lastn == 0 and n == 1: return i + 1 return 1 def pisanoprime(p, k): assert isprime(p) and k > 0 return p ** (k - 1) * pisano1(p) def pisano_mult(m, n): return lcm(pisano1(m), pisano1(n)) def pisano2(m): return reduce(lcm, (pisanoprime(prime, mult) for prime, mult in factorint(m).items()), 1) if __name__ == '__main__': for n in range(1, 181): assert pisano1(n) == pisano2(n), print(, [pisanoprime(prime, 2) for prime in primerange(1, 50)]) print(, [pisanoprime(prime, 1) for prime in primerange(1, 180)]) print() for i in range(1, 181): print(% pisano2(i), end= if i% 10 else )
428Pisano period
3python
t1wfw
int main() { int d=DETECT,m,maxX,maxY,x,y,increment=1; initgraph(&d,&m,); maxX = getmaxx(); maxY = getmaxy(); for(y=0;y<maxY;y+=maxY/sections) { for(x=0;x<maxX;x+=increment) { setfillstyle(SOLID_FILL,(x/increment)%2==0?BLACK:WHITE); bar(x,y,x+increment,y+maxY/sections); } increment++; } getch(); closegraph(); return 0; }
429Pinstripe/Display
5c
1lvpj
sub prime { my $n = shift || $_; $n % $_ or return for 2 .. sqrt $n; $n > 1 } print join(', ' => grep prime, 1..100), "\n";
425Primality by trial division
2perl
kmuhc
int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system(); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf(,219); } getchar(); return 0; }
430Plasma effect
5c
t1af4
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo ; ?>
425Primality by trial division
12php
3e8zq
$ convert plasma.gif -coalesce plasma2.gif $ eog plasma2.gif
430Plasma effect
0go
hymjq
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() {
431Playfair cipher
0go
q44xz
package main import "github.com/fogleman/gg" var palette = [2]string{ "FFFFFF",
429Pinstripe/Display
0go
yxs64
import Control.Monad (guard) import Data.Array (Array, assocs, elems, listArray, (!)) import Data.Char (toUpper) import Data.List (nub, (\\)) import Data.List.Split (chunksOf) import Data.Maybe (listToMaybe) import Data.String.Utils (replace) type Square a = Array (Int, Int) a array2D :: (Int, Int) -> [e] -> Square e array2D maxCoord = listArray ((1, 1), maxCoord) makeTable :: String -> String makeTable k = nub key ++ (alpha \\ key) where alpha = ['A' .. 'Z'] \\ "J" key = map toUpper =<< words k makeSquare :: [a] -> Square a makeSquare = array2D (5, 5) showSquare :: Square Char -> String showSquare d = unlines $ chunksOf 5 (elems d) getIndex':: (Eq a) => a -> [((Int, Int), a)] -> Maybe (Int, Int) getIndex' el = fmap fst . listToMaybe . filter ((== el) . snd) encodePair, decodePair :: Eq a => Square a -> (a, a) -> Maybe (a, a) encodePair = pairHelper (\x -> if x == 5 then 1 else x + 1) decodePair = pairHelper (\x -> if x == 1 then 5 else x - 1) pairHelper :: (Eq t) => (Int -> Int) -> Square t -> (t, t) -> Maybe (t, t) pairHelper adjust sqr (c1, c2) = do let ps = assocs sqr (x1, y1) <- getIndex' c1 ps (x2, y2) <- getIndex' c2 ps guard $ c1 /= c2 let get x = sqr ! x Just $ case () of () | y1 == y2 -> (get (adjust x1, y1), get (adjust x2, y2)) | x1 == x2 -> (get (x1, adjust y1), get (x2, adjust y2)) | otherwise -> (get (x1, y2), get (x2, y1)) parsePair :: String -> [(Char, Char)] parsePair = fmap (\[x, y] -> (x, y)) . words . fmap toUpper unparsePair :: [(Char, Char)] -> String unparsePair = unwords . fmap (\(x, y) -> [x, y]) codeHelper :: (Square Char -> (Char, Char) -> Maybe (Char, Char)) -> String -> String -> Maybe String codeHelper subs key = fmap unparsePair . mapM (subs (makeSquare $ makeTable key)) . parsePair playfair, unplayfair :: String -> String -> Maybe String playfair key = codeHelper encodePair key . formatEncode unplayfair = codeHelper decodePair formatEncode :: String -> String formatEncode = map toUpper . unwords . map (\[x, y] -> if x == y then [x, 'x'] else [x, y]) . chunksOf 2 . replace "j" "i" . concatMap adjustLength . words . filter (\n -> n `elem` (['A'..'Z'] ++ ['a'..'z'])) where adjustLength str | odd (length str) = str ++ "x" | otherwise = str
431Playfair cipher
8haskell
mqqyf
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width);
430Plasma effect
9java
x54wy
import java.awt.*; import javax.swing.*; public class PinstripeDisplay extends JPanel { final int bands = 4; public PinstripeDisplay() { setPreferredSize(new Dimension(900, 600)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int h = getHeight(); for (int b = 1; b <= bands; b++) { for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) { g.setColor(colIndex % 2 == 0 ? Color.white : Color.black); g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands)); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("PinstripeDisplay"); f.add(new PinstripeDisplay(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } }); } }
429Pinstripe/Display
9java
5dtuf
<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <style> canvas { position: absolute; top: 50%; left: 50%; width: 700px; height: 500px; margin: -250px 0 0 -350px; } body { background-color: navy; } </style> </head> <body> <canvas></canvas> <script> 'use strict'; var canvas = document.querySelector('canvas'); canvas.width = 700; canvas.height = 500; var g = canvas.getContext('2d'); var plasma = createPlasma(canvas.width, canvas.height); var hueShift = 0; function createPlasma(w, h) { var buffer = new Array(h); for (var y = 0; y < h; y++) { buffer[y] = new Array(w); for (var x = 0; x < w; x++) { var value = Math.sin(x / 16.0); value += Math.sin(y / 8.0); value += Math.sin((x + y) / 16.0); value += Math.sin(Math.sqrt(x * x + y * y) / 8.0); value += 4;
430Plasma effect
10javascript
ojh86
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message:%n%s%n", enc); System.out.printf("%nDecoded message:%n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
431Playfair cipher
9java
fppdv
null
429Pinstripe/Display
11kotlin
c0o98
null
430Plasma effect
11kotlin
pclb6
_ = love.graphics p1, p2, points = {}, {}, {} function hypotenuse( a, b ) return a * a + b * b end function love.load() size = _.getWidth() currentTime, doub, half = 0, size * 2, size / 2 local b1, b2 for j = 0, size * 2 do for i = 0, size * 2 do b1 = math.floor( 128 + 127 * ( math.cos( math.sqrt( hypotenuse( size - j , size - i ) ) / 64 ) ) ) b2 = math.floor( ( math.sin( ( math.sqrt( 128.0 + hypotenuse( size - i, size - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90 ) table.insert( p1, b1 ); table.insert( p2, b2 ) end end end function love.draw() local a, c1, c2, c3, s1, s2, s3 currentTime = currentTime + math.random( 2 ) * 3 local x1 = math.floor( half + ( half - 2 ) * math.sin( currentTime / 47 ) ) local x2 = math.floor( half + ( half / 7 ) * math.sin( -currentTime / 149 ) ) local x3 = math.floor( half + ( half - 3 ) * math.sin( -currentTime / 157 ) ) local y1 = math.floor( half + ( half / 11 ) * math.cos( currentTime / 71 ) ) local y2 = math.floor( half + ( half - 5 ) * math.cos( -currentTime / 181 ) ) local y3 = math.floor( half + ( half / 23 ) * math.cos( -currentTime / 137 ) ) s1 = y1 * doub + x1; s2 = y2 * doub + x2; s3 = y3 * doub + x3 for j = 0, size do for i = 0, size do a = p2[s1] + p1[s2] + p2[s3] c1 = a * 2; c2 = a * 4; c3 = a * 8 table.insert( points, { i, j, c1, c2, c3, 255 } ) s1 = s1 + 1; s2 = s2 + 1; s3 = s3 + 1; end s1 = s1 + size; s2 = s2 + size; s3 = s3 + size end _.points( points ) end
430Plasma effect
1lua
1l2po
null
431Playfair cipher
11kotlin
8770q
function love.load() WIDTH = love.graphics.getWidth() ROW_HEIGHT = math.floor(love.graphics.getHeight()/4) love.graphics.setBackgroundColor({0,0,0}) love.graphics.setLineWidth(1) love.graphics.setLineStyle("rough") end function love.draw() for j = 0, 3 do for i = 0, WIDTH, (j+1)*2 do love.graphics.setColor({255,255,255}) for h = 0, j do love.graphics.line(i+h, j*ROW_HEIGHT, i+h, (j+1)*ROW_HEIGHT) end end end end
429Pinstripe/Display
1lua
l8ick
def prime(a): return not (a < 2 or any(a% x == 0 for x in xrange(2, int(a**0.5) + 1)))
425Primality by trial division
3python
b95kr
use Imager; my($xsize,$ysize) = (640,400); $img = Imager->new(xsize => $xsize, ysize => $ysize); my $eps = 10**-14; my $height = int $ysize / 4; for my $width (1..4) { $stripes = int((1-$eps) + $xsize / $width / 2); @row = ((0) x $width, (1) x $width) x $stripes; for $x (0..$ for $y (0..$height) { my $offset = $height*($width-1); $img->setpixel(x => $x, y => $y+$offset, color => $row[$x] ? 'black' : 'white') } } } $img->write(file => 'pinstripes-bw.png');
429Pinstripe/Display
2perl
x5gw8
use Imager; sub plasma { my ($w, $h) = @_; my $img = Imager->new(xsize => $w, ysize => $h); for my $x (0 .. $w-1) { for my $y (0 .. $h-1) { my $hue = 4 + sin($x/19) + sin($y/9) + sin(($x+$y)/25) + sin(sqrt($x**2 + $y**2)/8); $img->setpixel(x => $x, y => $y, color => {hsv => [360 * $hue / 8, 1, 1]}); } } return $img; } my $img = plasma(400, 400); $img->write(file => 'plasma-perl.png');
430Plasma effect
2perl
yxq6u
is.prime <- function(n) n == 2 || n > 2 && n %% 2 == 1 && (n < 9 || all(n %% seq(3, floor(sqrt(n)), 2) > 0)) which(sapply(1:100, is.prime))
425Primality by trial division
13r
73lry
import math import colorsys from PIL import Image def plasma (w, h): out = Image.new(, (w, h)) pix = out.load() for x in range (w): for y in range(h): hue = 4.0 + math.sin(x / 19.0) + math.sin(y / 9.0) \ + math.sin((x + y) / 25.0) + math.sin(math.sqrt(x**2.0 + y**2.0) / 8.0) hsv = colorsys.hsv_to_rgb(hue/8.0, 1, 1) pix[x, y] = tuple([int(round(c * 255.0)) for c in hsv]) return out if __name__==: im = plasma(400, 400) im.show()
430Plasma effect
3python
mqsyh