code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import scala.util.Random
object QuickSelect {
def quickSelect[A <% Ordered[A]](seq: Seq[A], n: Int, rand: Random = new Random): A = {
val pivot = rand.nextInt(seq.length);
val (left, right) = seq.partition(_ < seq(pivot))
if (left.length == n) {
seq(pivot)
} else if (left.length < n) {
quickSelect(right, n - left.length, rand)
} else {
quickSelect(left, n, rand)
}
}
def main(args: Array[String]): Unit = {
val v = Array(9, 8, 7, 6, 5, 0, 1, 2, 3, 4)
println((0 until v.length).map(quickSelect(v, _)).mkString(", "))
}
} | 387Quickselect algorithm
| 16scala
| 3wnzy |
set.seed(12345L)
result <- rnorm(1000, mean = 1, sd = 0.5) | 379Random numbers
| 13r
| h91jj |
conn <- file("notes.txt", "r")
while(length(line <- readLines(conn, 1)) > 0) {
cat(line, "\n")
} | 383Read a file line by line
| 13r
| coc95 |
str =
reversed = str.reverse | 366Reverse a string
| 14ruby
| r6igs |
class Queue {
private List buffer
public Queue(List buffer = new LinkedList()) {
assert buffer != null
assert buffer.empty
this.buffer = buffer
}
def push (def item) { buffer << item }
final enqueue = this.&push
def pop() {
if (this.empty) throw new NoSuchElementException('Empty Queue')
buffer.remove(0)
}
final dequeue = this.&pop
def getEmpty() { buffer.empty }
String toString() { "Queue:${buffer}" }
} | 391Queue/Definition
| 7groovy
| msiy5 |
null | 390Quaternion type
| 11kotlin
| r3cgo |
data Fifo a = F [a] [a]
emptyFifo :: Fifo a
emptyFifo = F [] []
push :: Fifo a -> a -> Fifo a
push (F input output) item = F (item:input) output
pop :: Fifo a -> (Maybe a, Fifo a)
pop (F input (item:output)) = (Just item, F input output)
pop (F [] [] ) = (Nothing, F [] [])
pop (F input [] ) = pop (F [] (reverse input))
isEmpty :: Fifo a -> Bool
isEmpty (F [] []) = True
isEmpty _ = False | 391Queue/Definition
| 8haskell
| eurai |
fullname = favouritefruit =
needspeeling = seedsremoved = false
otherfamily = []
IO.foreach() do |line|
line.chomp!
key, value = line.split(nil, 2)
case key
when /^([
when ; fullname = value
when ; favouritefruit = value
when ; needspeeling = true
when ; seedsremoved = true
when ; otherfamily = value.split().map(&:strip)
when /^./; puts
end
end
puts
puts
puts
puts
otherfamily.each_with_index do |name, i|
puts
end | 374Read a configuration file
| 14ruby
| jmx7x |
def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1) + 1)
else:
lst.append(int(r))
return lst
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20')) | 385Range expansion
| 3python
| hmrjw |
let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba"); | 366Reverse a string
| 15rust
| 7ynrc |
Quaternion = {}
function Quaternion.new( a, b, c, d )
local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }
local metatab = {}
setmetatable( q, metatab )
metatab.__add = Quaternion.add
metatab.__sub = Quaternion.sub
metatab.__unm = Quaternion.unm
metatab.__mul = Quaternion.mul
return q
end
function Quaternion.add( p, q )
if type( p ) == "number" then
return Quaternion.new( p+q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a+q, p.b, p.c, p.d )
else
return Quaternion.new( p.a+q.a, p.b+q.b, p.c+q.c, p.d+q.d )
end
end
function Quaternion.sub( p, q )
if type( p ) == "number" then
return Quaternion.new( p-q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a-q, p.b, p.c, p.d )
else
return Quaternion.new( p.a-q.a, p.b-q.b, p.c-q.c, p.d-q.d )
end
end
function Quaternion.unm( p )
return Quaternion.new( -p.a, -p.b, -p.c, -p.d )
end
function Quaternion.mul( p, q )
if type( p ) == "number" then
return Quaternion.new( p*q.a, p*q.b, p*q.c, p*q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a*q, p.b*q, p.c*q, p.d*q )
else
return Quaternion.new( p.a*q.a - p.b*q.b - p.c*q.c - p.d*q.d,
p.a*q.b + p.b*q.a + p.c*q.d - p.d*q.c,
p.a*q.c - p.b*q.d + p.c*q.a + p.d*q.b,
p.a*q.d + p.b*q.c - p.c*q.b + p.d*q.a )
end
end
function Quaternion.conj( p )
return Quaternion.new( p.a, -p.b, -p.c, -p.d )
end
function Quaternion.norm( p )
return math.sqrt( p.a^2 + p.b^2 + p.c^2 + p.d^2 )
end
function Quaternion.print( p )
print( string.format( "%f +%fi +%fj +%fk\n", p.a, p.b, p.c, p.d ) )
end | 390Quaternion type
| 1lua
| 76lru |
func select<T where T: Comparable>(var elements: [T], n: Int) -> T {
var r = indices(elements)
while true {
let pivotIndex = partition(&elements, r)
if n == pivotIndex {
return elements[pivotIndex]
} else if n < pivotIndex {
r.endIndex = pivotIndex
} else {
r.startIndex = pivotIndex+1
}
}
}
for i in 0 ..< 10 {
let a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
print(select(a, i))
if i < 9 { print(", ") }
}
println() | 387Quickselect algorithm
| 17swift
| nbsil |
Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) } | 379Random numbers
| 14ruby
| e5sax |
rangeExpand <- function(text) {
lst <- gsub("(\\d)-", "\\1:", unlist(strsplit(text, ",")))
unlist(sapply(lst, function (x) eval(parse(text=x))), use.names=FALSE)
}
rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20")
[1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 | 385Range expansion
| 13r
| gzu47 |
IO.foreach do |line|
puts line
end | 383Read a file line by line
| 14ruby
| 4z45p |
extern crate rand;
use rand::distributions::{Normal, IndependentSample};
fn main() {
let mut rands = [0.0; 1000];
let normal = Normal::new(1.0, 0.5);
let mut rng = rand::thread_rng();
for num in rands.iter_mut() {
*num = normal.ind_sample(&mut rng);
}
} | 379Random numbers
| 15rust
| w40e4 |
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
let path = String::from("file.conf");
let cfg = config_from_file(path);
println!("{:?}", cfg);
}
fn config_from_file(path: String) -> Config {
let path = Path::new(&path);
let file = File::open(path).expect("File not found or cannot be opened");
let content = BufReader::new(&file);
let mut cfg = Config::new();
for line in content.lines() {
let line = line.expect("Could not read the line"); | 374Read a configuration file
| 15rust
| h9qj2 |
use std::io::{BufReader,BufRead};
use std::fs::File;
fn main() {
let file = File::open("file.txt").unwrap();
for line in BufReader::new(file).lines() {
println!("{}", line.unwrap());
}
} | 383Read a file line by line
| 15rust
| g3g4o |
public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){ | 391Queue/Definition
| 9java
| hm2jm |
val conf = scala.io.Source.fromFile("config.file").
getLines.
toList.
filter(_.trim.size > 0).
filterNot("#;" contains _(0)).
map(_ split(" ", 2) toList).
map(_ :+ "true" take 2).
map {
s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList)
}.toMap | 374Read a configuration file
| 16scala
| p28bj |
import scala.io._
Source.fromFile("foobar.txt").getLines.foreach(println) | 383Read a file line by line
| 16scala
| jmj7i |
var fifo = [];
fifo.push(42); | 391Queue/Definition
| 10javascript
| avg10 |
List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian) | 379Random numbers
| 16scala
| s7iqo |
def range_expand(rng)
rng.split(',').flat_map do |part|
if part =~ /^(-?\d+)-(-?\d+)$/
($1.to_i .. $2.to_i).to_a
else
Integer(part)
end
end
end
p range_expand('-6,-3--1,3-5,7-11,14,15,17-20') | 385Range expansion
| 14ruby
| bcjkq |
"asdf".reverse | 366Reverse a string
| 16scala
| kcthk |
use std::str::FromStr; | 385Range expansion
| 15rust
| plhbu |
def rangex(str: String): Seq[Int] =
str split "," flatMap { (s) =>
val r = """(-?\d+)(?:-(-?\d+))?""".r
val r(a,b) = s
if (b == null) Seq(a.toInt) else a.toInt to b.toInt
} | 385Range expansion
| 16scala
| eupab |
null | 391Queue/Definition
| 11kotlin
| 4ty57 |
Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end | 391Queue/Definition
| 1lua
| gzm4j |
package Quaternion;
use List::Util 'reduce';
use List::MoreUtils 'pairwise';
sub make {
my $cls = shift;
if (@_ == 1) { return bless [ @_, 0, 0, 0 ] }
elsif (@_ == 4) { return bless [ @_ ] }
else { die "Bad number of components: @_" }
}
sub _abs { sqrt reduce { $a + $b * $b } @{ +shift } }
sub _neg { bless [ map(-$_, @{+shift}) ] }
sub _str { "(@{+shift})" }
sub _add {
my ($x, $y) = @_;
$y = [ $y, 0, 0, 0 ] unless ref $y;
bless [ pairwise { $a + $b } @$x, @$y ]
}
sub _sub {
my ($x, $y, $swap) = @_;
$y = [ $y, 0, 0, 0 ] unless ref $y;
my @x = pairwise { $a - $b } @$x, @$y;
if ($swap) { $_ = -$_ for @x }
bless \@x;
}
sub _mul {
my ($x, $y) = @_;
if (!ref $y) { return bless [ map($_ * $y, @$x) ] }
my ($a1, $b1, $c1, $d1) = @$x;
my ($a2, $b2, $c2, $d2) = @$y;
bless [ $a1 * $a2 - $b1 * $b2 - $c1 * $c2 - $d1 * $d2,
$a1 * $b2 + $b1 * $a2 + $c1 * $d2 - $d1 * $c2,
$a1 * $c2 - $b1 * $d2 + $c1 * $a2 + $d1 * $b2,
$a1 * $d2 + $b1 * $c2 - $c1 * $b2 + $d1 * $a2]
}
sub conjugate {
my @a = map { -$_ } @{$_[0]};
$a[0] = $_[0][0];
bless \@a
}
use overload (
'""' => \&_str,
'+' => \&_add,
'-' => \&_sub,
'*' => \&_mul,
'neg' => \&_neg,
'abs' => \&_abs,
);
package main;
my $a = Quaternion->make(1, 2, 3, 4);
my $b = Quaternion->make(1, 1, 1, 1);
print "a = $a\n";
print "b = $b\n";
print "|a| = ", abs($a), "\n";
print "-a = ", -$a, "\n";
print "a + 1 = ", $a + 1, "\n";
print "a + b = ", $a + $b, "\n";
print "a - b = ", $a - $b, "\n";
print "a conjugate is ", $a->conjugate, "\n";
print "a * b = ", $a * $b, "\n";
print "b * a = ", $b * $a, "\n"; | 390Quaternion type
| 2perl
| dpxnw |
sub rangext {
my $str = join ' ', @_;
1 while $str =~ s{([+-]?\d+) ([+-]?\d+)}
{$1.(abs($2 - $1) == 1 ? '~' : ',').$2}eg;
$str =~ s/(\d+)~(?:[+-]?\d+~)+([+-]?\d+)/$1-$2/g;
$str =~ tr/~/,/;
return $str;
}
my @test = qw(0 1 2 4 6 7 8 11 12 14
15 16 17 18 19 20 21 22 23 24
25 27 28 29 30 31 32 33 35 36
37 38 39);
print rangext(@test), "\n"; | 386Range extraction
| 2perl
| 765rh |
func reverseString(s: String) -> String {
return String(s.characters.reverse())
}
print(reverseString("asdf"))
print(reverseString("asdf")) | 366Reverse a string
| 17swift
| g3o49 |
package main
import "fmt"
func main() {
a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta:=%q\n\tfmt.Printf(a, a)\n}\n"
fmt.Printf(a, a)
} | 389Quine
| 0go
| nbxi1 |
from collections import namedtuple
import math
class Q(namedtuple('Quaternion', 'real, i, j, k')):
'Quaternion type: Q(real=0.0, i=0.0, j=0.0, k=0.0)'
__slots__ = ()
def __new__(_cls, real=0.0, i=0.0, j=0.0, k=0.0):
'Defaults all parts of quaternion to zero'
return super().__new__(_cls, float(real), float(i), float(j), float(k))
def conjugate(self):
return Q(self.real, -self.i, -self.j, -self.k)
def _norm2(self):
return sum( x*x for x in self)
def norm(self):
return math.sqrt(self._norm2())
def reciprocal(self):
n2 = self._norm2()
return Q(*(x / n2 for x in self.conjugate()))
def __str__(self):
'Shorter form of Quaternion as string'
return 'Q(%g,%g,%g,%g)'% self
def __neg__(self):
return Q(-self.real, -self.i, -self.j, -self.k)
def __add__(self, other):
if type(other) == Q:
return Q( *(s+o for s,o in zip(self, other)) )
try:
f = float(other)
except:
return NotImplemented
return Q(self.real + f, self.i, self.j, self.k)
def __radd__(self, other):
return Q.__add__(self, other)
def __mul__(self, other):
if type(other) == Q:
a1,b1,c1,d1 = self
a2,b2,c2,d2 = other
return Q(
a1*a2 - b1*b2 - c1*c2 - d1*d2,
a1*b2 + b1*a2 + c1*d2 - d1*c2,
a1*c2 - b1*d2 + c1*a2 + d1*b2,
a1*d2 + b1*c2 - c1*b2 + d1*a2 )
try:
f = float(other)
except:
return NotImplemented
return Q(self.real * f, self.i * f, self.j * f, self.k * f)
def __rmul__(self, other):
return Q.__mul__(self, other)
def __truediv__(self, other):
if type(other) == Q:
return self.__mul__(other.reciprocal())
try:
f = float(other)
except:
return NotImplemented
return Q(self.real / f, self.i / f, self.j / f, self.k / f)
def __rtruediv__(self, other):
return other * self.reciprocal()
__div__, __rdiv__ = __truediv__, __rtruediv__
Quaternion = Q
q = Q(1, 2, 3, 4)
q1 = Q(2, 3, 4, 5)
q2 = Q(3, 4, 5, 6)
r = 7 | 390Quaternion type
| 3python
| f1qde |
s="s=%s;printf s,s.inspect()";printf s,s.inspect() | 389Quine
| 7groovy
| srpq1 |
library(quaternions)
q <- Q(1, 2, 3, 4)
q1 <- Q(2, 3, 4, 5)
q2 <- Q(3, 4, 5, 6)
r <- 7.0
display <- function(x){
e <- deparse(substitute(x))
res <- if(class(x) == "Q") paste(x$r, "+", x$i, "i+", x$j, "j+", x$k, "k", sep = "") else x
cat(noquote(paste(c(e, " = ", res, "\n"), collapse="")))
invisible(res)
}
display(norm(q))
display(-q)
display(Conj(q))
display(r + q)
display(q1 + q2)
display(r*q)
display(q*r)
if(display(q1*q2) == display(q2*q1)) cat("q1*q2 == q2*q1\n") else cat("q1*q2!= q2*q1\n") | 390Quaternion type
| 13r
| oha84 |
use Carp;
sub mypush (\@@) {my($list,@things)=@_; push @$list, @things}
sub mypop (\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty (@) {not @_} | 391Queue/Definition
| 2perl
| ikao3 |
let q s = putStrLn (s ++ show s) in q "let q s = putStrLn (s ++ show s) in q " | 389Quine
| 8haskell
| udyv2 |
def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i'% r) if len(r) == 2 else '%i'% r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst)) | 386Range extraction
| 3python
| jy47p |
extract.range = function(v) {
r <- c(1, which(diff(v) != 1) + 1, length(v) + 1)
paste0(collapse=",",
v[head(r, -1)],
ifelse(diff(r) == 1,
"",
paste0(ifelse(diff(r) == 2, ",", "-"),
v[r[-1] - 1])))
}
print(extract.range(c(
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20)))
print(extract.range(c(
0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39))) | 386Range extraction
| 13r
| 4t25y |
class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
public function isEmpty(){
return empty($this->data);
}
} | 391Queue/Definition
| 12php
| r39ge |
class Quaternion
def initialize(*parts)
raise ArgumentError, unless parts.size == 4
raise ArgumentError, unless parts.all? {|x| x.is_a?(Numeric)}
@parts = parts
end
def to_a; @parts; end
def to_s; end
alias inspect to_s
def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end
def real; @parts.first; end
def imag; @parts[1..3]; end
def conj; Quaternion.new(real, *imag.map(&:-@)); end
def norm; Math.sqrt(to_a.reduce(0){|sum,e| sum + e**2}) end
def ==(other)
case other
when Quaternion; to_a == other.to_a
when Numeric; to_a == [other, 0, 0, 0]
else false
end
end
def -@; Quaternion.new(*to_a.map(&:-@)); end
def -(other); self + -other; end
def +(other)
case other
when Numeric
Quaternion.new(real + other, *imag)
when Quaternion
Quaternion.new(*to_a.zip(other.to_a).map { |x,y| x + y })
end
end
def *(other)
case other
when Numeric
Quaternion.new(*to_a.map { |x| x * other })
when Quaternion
a, b, c, d = *complex_parts, *other.complex_parts
x, y = a*c - d.conj*b, a*d + b*c.conj
Quaternion.new(x.real, x.imag, y.real, y.imag)
end
end
def coerce(other)
case other
when Numeric then [Scalar.new(other), self]
else raise TypeError,
end
end
class Scalar
def initialize(val); @val = val; end
def +(other); other + @val; end
def *(other); other * @val; end
def -(other); Quaternion.new(@val, 0, 0, 0) - other; end
end
end
if __FILE__ == $0
q = Quaternion.new(1,2,3,4)
q1 = Quaternion.new(2,3,4,5)
q2 = Quaternion.new(3,4,5,6)
r = 7
expressions = [, , ,
, , , , ,, ,
, , , , ,
, ]
expressions.each do |exp|
puts % [exp, eval(exp)]
end
end | 390Quaternion type
| 14ruby
| ze0tw |
use std::fmt::{Display, Error, Formatter};
use std::ops::{Add, Mul, Neg};
#[derive(Clone,Copy,Debug)]
struct Quaternion {
a: f64,
b: f64,
c: f64,
d: f64
}
impl Quaternion {
pub fn new(a: f64, b: f64, c: f64, d: f64) -> Quaternion {
Quaternion {
a: a,
b: b,
c: c,
d: d
}
}
pub fn norm(&self) -> f64 {
(self.a.powi(2) + self.b.powi(2) + self.c.powi(2) + self.d.powi(2)).sqrt()
}
pub fn conjugate(&self) -> Quaternion {
Quaternion {
a: self.a,
b: -self.b,
c: -self.c,
d: -self.d
}
}
}
impl Add for Quaternion {
type Output = Quaternion;
#[inline]
fn add(self, other: Quaternion) -> Self::Output {
Quaternion {
a: self.a + other.a,
b: self.b + other.b,
c: self.c + other.c,
d: self.d + other.d
}
}
}
impl Add<f64> for Quaternion {
type Output = Quaternion;
#[inline]
fn add(self, other: f64) -> Self::Output {
Quaternion {
a: self.a + other,
b: self.b,
c: self.c,
d: self.d
}
}
}
impl Add<Quaternion> for f64 {
type Output = Quaternion;
#[inline]
fn add(self, other: Quaternion) -> Self::Output {
Quaternion {
a: other.a + self,
b: other.b,
c: other.c,
d: other.d
}
}
}
impl Display for Quaternion {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "({} + {}i + {}j + {}k)", self.a, self.b, self.c, self.d)
}
}
impl Mul for Quaternion {
type Output = Quaternion;
#[inline]
fn mul(self, rhs: Quaternion) -> Self::Output {
Quaternion {
a: self.a * rhs.a - self.b * rhs.b - self.c * rhs.c - self.d * rhs.d,
b: self.a * rhs.b + self.b * rhs.a + self.c * rhs.d - self.d * rhs.c,
c: self.a * rhs.c - self.b * rhs.d + self.c * rhs.a + self.d * rhs.b,
d: self.a * rhs.d + self.b * rhs.c - self.c * rhs.b + self.d * rhs.a,
}
}
}
impl Mul<f64> for Quaternion {
type Output = Quaternion;
#[inline]
fn mul(self, other: f64) -> Self::Output {
Quaternion {
a: self.a * other,
b: self.b * other,
c: self.c * other,
d: self.d * other
}
}
}
impl Mul<Quaternion> for f64 {
type Output = Quaternion;
#[inline]
fn mul(self, other: Quaternion) -> Self::Output {
Quaternion {
a: other.a * self,
b: other.b * self,
c: other.c * self,
d: other.d * self
}
}
}
impl Neg for Quaternion {
type Output = Quaternion;
#[inline]
fn neg(self) -> Self::Output {
Quaternion {
a: -self.a,
b: -self.b,
c: -self.c,
d: -self.d
}
}
}
fn main() {
let q0 = Quaternion { a: 1., b: 2., c: 3., d: 4. };
let q1 = Quaternion::new(2., 3., 4., 5.);
let q2 = Quaternion::new(3., 4., 5., 6.);
let r: f64 = 7.;
println!("q0 = {}", q0);
println!("q1 = {}", q1);
println!("q2 = {}", q2);
println!("r = {}", r);
println!();
println!("-q0 = {}", -q0);
println!("conjugate of q0 = {}", q0.conjugate());
println!();
println!("r + q0 = {}", r + q0);
println!("q0 + r = {}", q0 + r);
println!();
println!("r * q0 = {}", r * q0);
println!("q0 * r = {}", q0 * r);
println!();
println!("q0 + q1 = {}", q0 + q1);
println!("q0 * q1 = {}", q0 * q1);
println!();
println!("q0 * (conjugate of q0) = {}", q0 * q0.conjugate());
println!();
println!(" q0 + q1 * q2 = {}", q0 + q1 * q2);
println!("(q0 + q1) * q2 = {}", (q0 + q1) * q2);
println!();
println!(" q0 * q1 * q2 = {}", q0 *q1 * q2);
println!("(q0 * q1) * q2 = {}", (q0 * q1) * q2);
println!(" q0 * (q1 * q2) = {}", q0 * (q1 * q2));
println!();
println!("normal of q0 = {}", q0.norm());
} | 390Quaternion type
| 15rust
| 3w8z8 |
case class Quaternion(re: Double = 0.0, i: Double = 0.0, j: Double = 0.0, k: Double = 0.0) {
lazy val im = (i, j, k)
private lazy val norm2 = re*re + i*i + j*j + k*k
lazy val norm = math.sqrt(norm2)
def negative = Quaternion(-re, -i, -j, -k)
def conjugate = Quaternion(re, -i, -j, -k)
def reciprocal = Quaternion(re/norm2, -i/norm2, -j/norm2, -k/norm2)
def +(q: Quaternion) = Quaternion(re+q.re, i+q.i, j+q.j, k+q.k)
def -(q: Quaternion) = Quaternion(re-q.re, i-q.i, j-q.j, k-q.k)
def *(q: Quaternion) = Quaternion(
re*q.re - i*q.i - j*q.j - k*q.k,
re*q.i + i*q.re + j*q.k - k*q.j,
re*q.j - i*q.k + j*q.re + k*q.i,
re*q.k + i*q.j - j*q.i + k*q.re
)
def /(q: Quaternion) = this * q.reciprocal
def unary_- = negative
def unary_~ = conjugate
override def toString = "Q(%.2f,%.2fi,%.2fj,%.2fk)".formatLocal(java.util.Locale.ENGLISH, re, i, j, k)
}
object Quaternion {
import scala.language.implicitConversions
import Numeric.Implicits._
implicit def number2Quaternion[T:Numeric](n: T) = Quaternion(n.toDouble)
} | 390Quaternion type
| 16scala
| msnyc |
def range_extract(l)
sorted, range = l.sort.concat([Float::MAX]), []
canidate_number = sorted.first
sorted.each_cons(2) do |current_number, next_number|
if current_number.succ < next_number
if canidate_number == current_number
range << canidate_number.to_s
else
seperator = canidate_number.succ == current_number? :
range << % [canidate_number, seperator, current_number]
end
canidate_number = next_number
end
end
range.join(',')
end
lst = [
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
]
p rng = range_extract(lst) | 386Range extraction
| 14ruby
| k9rhg |
use std::ops::Add;
struct RangeFinder<'a, T: 'a> {
index: usize,
length: usize,
arr: &'a [T],
}
impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add<i8, Output=T> + Copy {
type Item = (T, Option<T>);
fn next(&mut self) -> Option<Self::Item> {
if self.index == self.length {
return None;
}
let lo = self.index;
while self.index < self.length - 1 && self.arr[self.index + 1] == self.arr[self.index] + 1 {
self.index += 1
}
let hi = self.index;
self.index += 1;
if hi - lo > 1 {
Some((self.arr[lo], Some(self.arr[hi])))
} else {
if hi - lo == 1 {
self.index -= 1
}
Some((self.arr[lo], None))
}
}
}
impl<'a, T> RangeFinder<'a, T> {
fn new(a: &'a [T]) -> Self {
RangeFinder {
index: 0,
arr: a,
length: a.len(),
}
}
}
fn main() {
let input_numbers: &[i8] = &[0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39];
for (i, (lo, hi)) in RangeFinder::new(&input_numbers).enumerate() {
if i > 0 {print!(",")}
print!("{}", lo);
if hi.is_some() {print!("-{}", hi.unwrap())}
}
println!("");
} | 386Range extraction
| 15rust
| bc7kx |
import Foundation
struct Quaternion {
var a, b, c, d: Double
static let i = Quaternion(a: 0, b: 1, c: 0, d: 0)
static let j = Quaternion(a: 0, b: 0, c: 1, d: 0)
static let k = Quaternion(a: 0, b: 0, c: 0, d: 1)
}
extension Quaternion: Equatable {
static func ==(lhs: Quaternion, rhs: Quaternion) -> Bool {
return (lhs.a, lhs.b, lhs.c, lhs.d) == (rhs.a, rhs.b, rhs.c, rhs.d)
}
}
extension Quaternion: ExpressibleByIntegerLiteral {
init(integerLiteral: Double) {
a = integerLiteral
b = 0
c = 0
d = 0
}
}
extension Quaternion: Numeric {
var magnitude: Double {
return norm
}
init?<T>(exactly: T) { | 390Quaternion type
| 17swift
| tasfl |
(function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})() | 389Quine
| 9java
| msdym |
object Range {
def spanRange(ls:List[Int])={
var last=ls.head
ls span {x => val b=x<=last+1; last=x; b}
}
def toRangeList(ls:List[Int]):List[List[Int]]=ls match {
case Nil => List()
case _ => spanRange(ls) match {
case (range, Nil) => List(range)
case (range, rest) => range :: toRangeList(rest)
}
}
def toRangeString(ls:List[List[Int]])=ls map {r=>
if(r.size<3) r mkString ","
else r.head + "-" + r.last
} mkString ","
def main(args: Array[String]): Unit = {
var l=List(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
println(toRangeString(toRangeList(l)))
}
} | 386Range extraction
| 16scala
| avk1n |
(function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})() | 389Quine
| 10javascript
| vn625 |
class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == :
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
f = FIFO(3,2,1)
while not f.empty():
print f(),
f = FIFO(3,2,1)
while f:
print f(),
f = FIFO(3,2,1)
for i in f:
print i, | 391Queue/Definition
| 3python
| nbeiz |
empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
push(3)
push("abc")
push(matrix(1:6, nrow=2))
empty()
pop()
pop()
pop()
pop() | 391Queue/Definition
| 13r
| 07bsg |
null | 389Quine
| 11kotlin
| ta0f0 |
import Darwin
func ranges(from ints:[Int]) -> [(Int, Int)] {
var range: (Int, Int)?
var ranges = [(Int, Int)]()
for this in ints {
if let (start, end) = range {
if this == end + 1 {
range = (start, this)
}
else {
ranges.append(range!)
range = (this, this)
}
}
else { range = (this, this) }
}
ranges.append(range!)
return ranges
}
func description(from ranges:[(Int, Int)]) -> String {
var desc = ""
for (start, end) in ranges {
desc += desc.isEmpty? "": ","
if start == end {
desc += "\(start)"
}
else if end == start + 1 {
desc += "\(start),\(end)"
}
else {
desc += "\(start)-\(end)"
}
}
return desc
}
let ex = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
let longer = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39]
print(description(from: ranges(from: ex)))
print(description(from: ranges(from: longer))) | 386Range extraction
| 17swift
| hmgj0 |
require 'forwardable'
class FIFO
extend Forwardable
def self.[](*objects)
new.push(*objects)
end
def initialize; @ary = []; end
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
def_delegator:@ary, :shift, :pop
alias shift pop
alias dequeue shift
def_delegator:@ary, :empty?
def_delegator:@ary, :size
alias length size
def to_s
end
alias inspect to_s
end | 391Queue/Definition
| 14ruby
| f1xdr |
use std::collections::VecDeque;
fn main() {
let mut stack = VecDeque::new();
stack.push_back("Element1");
stack.push_back("Element2");
stack.push_back("Element3");
assert_eq!(Some(&"Element1"), stack.front());
assert_eq!(Some("Element1"), stack.pop_front());
assert_eq!(Some("Element2"), stack.pop_front());
assert_eq!(Some("Element3"), stack.pop_front());
assert_eq!(None, stack.pop_front());
} | 391Queue/Definition
| 15rust
| taqfd |
class Queue[T] {
private[this] class Node[T](val value:T) {
var next:Option[Node[T]]=None
def append(n:Node[T])=next=Some(n)
}
private[this] var head:Option[Node[T]]=None
private[this] var tail:Option[Node[T]]=None
def isEmpty=head.isEmpty
def enqueue(item:T)={
val n=new Node(item)
if(isEmpty) head=Some(n) else tail.get.append(n)
tail=Some(n)
}
def dequeue:T=head match {
case Some(item) => head=item.next; item.value
case None => throw new java.util.NoSuchElementException()
}
def front:T=head match {
case Some(item) => item.value
case None => throw new java.util.NoSuchElementException()
}
def iterator: Iterator[T]=new Iterator[T]{
private[this] var it=head;
override def hasNext=it.isDefined
override def next:T={val n=it.get; it=n.next; n.value}
}
override def toString()=iterator.mkString("Queue(", ", ", ")")
} | 391Queue/Definition
| 16scala
| 6x831 |
s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s) | 389Quine
| 1lua
| ze8ty |
static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * STATE_MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf();
seed(987654321);
for (i = 0; i < 100000; i++) {
int j = (int)floor(next_float() * 5.0);
counts[j]++;
}
for (i = 0; i < 5; i++) {
printf(, i, counts[i]);
}
return 0;
} | 392Pseudo-random numbers/Xorshift star
| 5c
| ohp80 |
package main
import (
"fmt"
"math"
)
const CONST = 0x2545F4914F6CDD1D
type XorshiftStar struct{ state uint64 }
func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }
func (xor *XorshiftStar) seed(state uint64) { xor.state = state }
func (xor *XorshiftStar) nextInt() uint32 {
x := xor.state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
xor.state = x
return uint32((x * CONST) >> 32)
}
func (xor *XorshiftStar) nextFloat() float64 {
return float64(xor.nextInt()) / (1 << 32)
}
func main() {
randomGen := XorshiftStarNew(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d:%d\n", i, counts[i])
}
} | 392Pseudo-random numbers/Xorshift star
| 0go
| 4t652 |
import Data.Bits
import Data.Word
import System.Random
import Data.List
newtype XorShift = XorShift Word64
instance RandomGen XorShift where
next (XorShift state) = (out newState, XorShift newState)
where
newState = (\z -> z `xor` (z `shiftR` 27)) .
(\z -> z `xor` (z `shiftL` 25)) .
(\z -> z `xor` (z `shiftR` 12)) $ state
out x = fromIntegral $ (x * 0x2545f4914f6cdd1d) `shiftR` 32
split _ = error "XorShift is not splittable"
randoms':: RandomGen g => g -> [Int]
randoms' = unfoldr (pure . next)
toFloat n = fromIntegral n / (2^32 - 1) | 392Pseudo-random numbers/Xorshift star
| 8haskell
| qgjx9 |
public class XorShiftStar {
private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
private long state;
public void seed(long num) {
state = num;
}
public int nextInt() {
long x;
int answer;
x = state;
x = x ^ (x >>> 12);
x = x ^ (x << 25);
x = x ^ (x >>> 27);
state = x;
answer = (int) ((x * MAGIC) >> 32);
return answer;
}
public float nextFloat() {
return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);
}
public static void main(String[] args) {
var rng = new XorShiftStar();
rng.seed(1234567);
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println(Integer.toUnsignedString(rng.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
rng.seed(987654321);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(rng.nextFloat() * 5.0);
counts[j]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.printf("%d:%d\n", i, counts[i]);
}
}
} | 392Pseudo-random numbers/Xorshift star
| 9java
| plub3 |
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf(, pcg32_int());
printf(, pcg32_int());
printf(, pcg32_int());
printf(, pcg32_int());
printf(, pcg32_int());
printf();
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf();
for (i = 0; i < 5; i++) {
printf(, i, counts[i]);
}
return 0;
} | 393Pseudo-random numbers/PCG32
| 5c
| 12upj |
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf(,random());
return 0;
} | 394Pseudo-random numbers/Middle-square method
| 5c
| taef4 |
import kotlin.math.floor
class XorShiftStar {
private var state = 0L
fun seed(num: Long) {
state = num
}
fun nextInt(): Int {
var x = state
x = x xor (x ushr 12)
x = x xor (x shl 25)
x = x xor (x ushr 27)
state = x
return (x * MAGIC shr 32).toInt()
}
fun nextFloat(): Float {
return nextInt().toUInt().toFloat() / (1L shl 32)
}
companion object {
private const val MAGIC = 0x2545F4914F6CDD1D
}
}
fun main() {
val rng = XorShiftStar()
rng.seed(1234567)
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println()
rng.seed(987654321)
val counts = arrayOf(0, 0, 0, 0, 0)
for (i in 1..100000) {
val j = floor(rng.nextFloat() * 5.0).toInt()
counts[j]++
}
for (iv in counts.withIndex()) {
println("${iv.index}: ${iv.value}")
}
} | 392Pseudo-random numbers/Xorshift star
| 11kotlin
| 769r4 |
function create()
local g = {
magic = 0x2545F4914F6CDD1D,
state = 0,
seed = function(self, num)
self.state = num
end,
next_int = function(self)
local x = self.state
x = x ~ (x >> 12)
x = x ~ (x << 25)
x = x ~ (x >> 27)
self.state = x
local answer = (x * self.magic) >> 32
return answer
end,
next_float = function(self)
return self:next_int() / (1 << 32)
end
}
return g
end
local g = create()
g:seed(1234567)
print(g:next_int())
print(g:next_int())
print(g:next_int())
print(g:next_int())
print(g:next_int())
print()
local counts = {[0]=0, [1]=0, [2]=0, [3]=0, [4]=0}
g:seed(987654321)
for i=1,100000 do
local j = math.floor(g:next_float() * 5.0)
counts[j] = counts[j] + 1
end
for i,v in pairs(counts) do
print(i..': '..v)
end | 392Pseudo-random numbers/Xorshift star
| 1lua
| jyc71 |
int main(int argc, char **argv){
int a,b,c,d;
int r[N+1];
memset(r,0,sizeof(r));
for(a=1; a<=N; a++){
for(b=a; b<=N; b++){
int aabb;
if(a&1 && b&1) continue;
aabb=a*a + b*b;
for(c=b; c<=N; c++){
int aabbcc=aabb + c*c;
d=(int)sqrt((float)aabbcc);
if(aabbcc == d*d && d<=N) r[d]=1;
}
}
}
for(a=1; a<=N; a++)
if(!r[a]) printf(,a);
printf();
} | 395Pythagorean quadruples
| 5c
| 2iilo |
use strict;
use warnings;
no warnings 'portable';
use feature 'say';
use Math::AnyNum qw(:overload);
package Xorshift_star {
sub new {
my ($class, %opt) = @_;
bless {state => $opt{seed}}, $class;
}
sub next_int {
my ($self) = @_;
my $state = $self->{state};
$state ^= $state >> 12;
$state ^= $state << 25 & (2**64 - 1);
$state ^= $state >> 27;
$self->{state} = $state;
($state * 0x2545F4914F6CDD1D) >> 32 & (2**32 - 1);
}
sub next_float {
my ($self) = @_;
$self->next_int / 2**32;
}
}
say 'Seed: 1234567, first 5 values:';
my $rng = Xorshift_star->new(seed => 1234567);
say $rng->next_int for 1 .. 5;
my %h;
say "\nSeed: 987654321, values histogram:";
$rng = Xorshift_star->new(seed => 987654321);
$h{int 5 * $rng->next_float}++ for 1 .. 100_000;
say "$_ $h{$_}" for sort keys %h; | 392Pseudo-random numbers/Xorshift star
| 2perl
| f1wd7 |
typedef struct{
double x,y;
}point;
void pythagorasTree(point a,point b,int times){
point c,d,e;
c.x = b.x - (a.y - b.y);
c.y = b.y - (b.x - a.x);
d.x = a.x - (a.y - b.y);
d.y = a.y - (b.x - a.x);
e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;
e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;
if(times>0){
setcolor(rand()%15 + 1);
line(a.x,a.y,b.x,b.y);
line(c.x,c.y,b.x,b.y);
line(c.x,c.y,d.x,d.y);
line(a.x,a.y,d.x,d.y);
pythagorasTree(d,e,times-1);
pythagorasTree(e,c,times-1);
}
}
int main(){
point a,b;
double side;
int iter;
time_t t;
printf();
scanf(,&side);
printf();
scanf(,&iter);
a.x = 6*side/2 - side/2;
a.y = 4*side;
b.x = 6*side/2 + side/2;
b.y = 4*side;
initwindow(6*side,4*side,);
srand((unsigned)time(&t));
pythagorasTree(a,b,iter);
getch();
closegraph();
return 0;
} | 396Pythagoras tree
| 5c
| plcby |
static uint64_t x;
uint64_t next() {
uint64_t z = (x += 0x9e3779b97f4a7c15);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
return z ^ (z >> 31);
}
double next_float() {
return next() / pow(2.0, 64);
}
int main() {
int i, j;
x = 1234567;
for(i = 0; i < 5; ++i)
printf(, next());
x = 987654321;
int vec5[5] = {0, 0, 0, 0, 0};
for(i = 0; i < 100000; ++i) {
j = next_float() * 5.0;
vec5[j] += 1;
}
for(i = 0; i < 5; ++i)
printf(, i, vec5[i]);
} | 397Pseudo-random numbers/Splitmix64
| 5c
| w5vec |
package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
} | 394Pseudo-random numbers/Middle-square method
| 0go
| hm9jq |
findPseudoRandom :: Int -> Int
findPseudoRandom seed =
let square = seed * seed
squarestr = show square
enlarged = replicate ( 12 - length squarestr ) '0' ++ squarestr
in read $ take 6 $ drop 3 enlarged
solution :: [Int]
solution = tail $ take 6 $ iterate findPseudoRandom 675248 | 394Pseudo-random numbers/Middle-square method
| 8haskell
| ikbor |
mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D
class Xorshift_star():
def __init__(self, seed=0):
self.state = seed & mask64
def seed(self, num):
self.state = num & mask64
def next_int(self):
x = self.state
x = (x ^ (x >> 12)) & mask64
x = (x ^ (x << 25)) & mask64
x = (x ^ (x >> 27)) & mask64
self.state = x
answer = (((x * const) & mask64) >> 32) & mask32
return answer
def next_float(self):
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = Xorshift_star()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) | 392Pseudo-random numbers/Xorshift star
| 3python
| taxfw |
package main
import (
"fmt"
"math"
)
const CONST = 6364136223846793005
type Pcg32 struct{ state, inc uint64 }
func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }
func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
pcg.state = 0
pcg.inc = (seedSequence << 1) | 1
pcg.nextInt()
pcg.state = pcg.state + seedState
pcg.nextInt()
}
func (pcg *Pcg32) nextInt() uint32 {
old := pcg.state
pcg.state = old*CONST + pcg.inc
pcgshifted := uint32(((old >> 18) ^ old) >> 27)
rot := uint32(old >> 59)
return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}
func (pcg *Pcg32) nextFloat() float64 {
return float64(pcg.nextInt()) / (1 << 32)
}
func main() {
randomGen := Pcg32New()
randomGen.seed(42, 54)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321, 1)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d:%d\n", i, counts[i])
}
} | 393Pseudo-random numbers/PCG32
| 0go
| yq064 |
package main
import (
"fmt"
"math"
)
type Splitmix64 struct{ state uint64 }
func Splitmix64New(state uint64) *Splitmix64 { return &Splitmix64{state} }
func (sm64 *Splitmix64) nextInt() uint64 {
sm64.state += 0x9e3779b97f4a7c15
z := sm64.state
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
return z ^ (z >> 31)
}
func (sm64 *Splitmix64) nextFloat() float64 {
return float64(sm64.nextInt()) / (1 << 64)
}
func main() {
randomGen := Splitmix64New(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen = Splitmix64New(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d:%d\n", i, counts[i])
}
} | 397Pseudo-random numbers/Splitmix64
| 0go
| c8s9g |
$s = q($s = q(%s); printf($s, $s);
); printf($s, $s); | 389Quine
| 2perl
| k95hc |
import Data.Bits
import Data.Word
import System.Random
import Data.List
data PCGen = PCGen !Word64 !Word64
mkPCGen state sequence =
let
n = 6364136223846793005 :: Word64
inc = (sequence `shiftL` 1) .|. 1 :: Word64
in PCGen ((inc + state)*n + inc) inc
instance RandomGen PCGen where
next (PCGen state inc) =
let
n = 6364136223846793005 :: Word64
xs = fromIntegral $ ((state `shiftR` 18) `xor` state) `shiftR` 27 :: Word32
rot = fromIntegral $ state `shiftR` 59 :: Int
in (fromIntegral $ (xs `shiftR` rot) .|. (xs `shiftL` ((-rot) .&. 31))
, PCGen (state * n + inc) inc)
split _ = error "PCG32 is not splittable"
randoms':: RandomGen g => g -> [Int]
randoms' g = unfoldr (pure . next) g
toFloat n = fromIntegral n / (2^32 - 1) | 393Pseudo-random numbers/PCG32
| 8haskell
| hmcju |
import Data.Bits
import Data.Word
import Data.List
next :: Word64 -> (Word64, Word64)
next state = f4 $ state + 0x9e3779b97f4a7c15
where
f1 z = (z `xor` (z `shiftR` 30)) * 0xbf58476d1ce4e5b9
f2 z = (z `xor` (z `shiftR` 27)) * 0x94d049bb133111eb
f3 z = z `xor` (z `shiftR` 31)
f4 s = ((f3 . f2 . f1) s, s)
randoms = unfoldr (pure . next)
toFloat n = fromIntegral n / (2^64 - 1) | 397Pseudo-random numbers/Splitmix64
| 8haskell
| pl9bt |
use strict;
use warnings;
sub msq
{
use feature qw( state );
state $seed = 675248;
$seed = sprintf "%06d", $seed ** 2 / 1000 % 1e6;
}
print msq, "\n" for 1 .. 5; | 394Pseudo-random numbers/Middle-square method
| 2perl
| yqs6u |
public class PCG32 {
private static final long N = 6364136223846793005L;
private long state = 0x853c49e6748fea9bL;
private long inc = 0xda3e39cb94b95bdbL;
public void seed(long seedState, long seedSequence) {
state = 0;
inc = (seedSequence << 1) | 1;
nextInt();
state = state + seedState;
nextInt();
}
public int nextInt() {
long old = state;
state = old * N + inc;
int shifted = (int) (((old >>> 18) ^ old) >>> 27);
int rot = (int) (old >>> 59);
return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));
}
public double nextFloat() {
var u = Integer.toUnsignedLong(nextInt());
return (double) u / (1L << 32);
}
public static void main(String[] args) {
var r = new PCG32();
r.seed(42, 54);
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println(Integer.toUnsignedString(r.nextInt()));
System.out.println();
int[] counts = {0, 0, 0, 0, 0};
r.seed(987654321, 1);
for (int i = 0; i < 100_000; i++) {
int j = (int) Math.floor(r.nextFloat() * 5.0);
counts[j]++;
}
System.out.println("The counts for 100,000 repetitions are:");
for (int i = 0; i < counts.length; i++) {
System.out.printf(" %d:%d\n", i, counts[i]);
}
}
} | 393Pseudo-random numbers/PCG32
| 9java
| 5fzuf |
use strict;
use warnings;
no warnings 'portable';
use feature 'say';
use Math::AnyNum qw(:overload);
package splitmix64 {
sub new {
my ($class, %opt) = @_;
bless {state => $opt{seed}}, $class;
}
sub next_int {
my ($self) = @_;
my $next = $self->{state} = ($self->{state} + 0x9e3779b97f4a7c15) & (2**64 - 1);
$next = ($next ^ ($next >> 30)) * 0xbf58476d1ce4e5b9 & (2**64 - 1);
$next = ($next ^ ($next >> 27)) * 0x94d049bb133111eb & (2**64 - 1);
($next ^ ($next >> 31)) & (2**64 - 1);
}
sub next_float {
my ($self) = @_;
$self->next_int / 2**64;
}
}
say 'Seed: 1234567, first 5 values:';
my $rng = splitmix64->new(seed => 1234567);
say $rng->next_int for 1 .. 5;
my %h;
say "\nSeed: 987654321, values histogram:";
$rng = splitmix64->new(seed => 987654321);
$h{int 5 * $rng->next_float}++ for 1 .. 100_000;
say "$_ $h{$_}" for sort keys %h; | 397Pseudo-random numbers/Splitmix64
| 2perl
| 07gs4 |
seed = 675248
def random():
global seed
s = str(seed ** 2)
while len(s) != 12:
s = + s
seed = int(s[3:9])
return seed
for i in range(0,5):
print(random()) | 394Pseudo-random numbers/Middle-square method
| 3python
| ms0yh |
class Xorshift_star
MASK64 = (1 << 64) - 1
MASK32 = (1 << 32) - 1
def initialize(seed = 0) = @state = seed & MASK64
def next_int
x = @state
x = x ^ (x >> 12)
x = (x ^ (x << 25)) & MASK64
x = x ^ (x >> 27)
@state = x
(((x * 0x2545F4914F6CDD1D) & MASK64) >> 32) & MASK32
end
def next_float = next_int.fdiv((1 << 32))
end
random_gen = Xorshift_star.new(1234567)
5.times{ puts random_gen.next_int}
random_gen = Xorshift_star.new(987654321)
tally = Hash.new(0)
100_000.times{ tally[(random_gen.next_float*5).floor] += 1 }
puts tally.sort.map{|ar| ar.join() } | 392Pseudo-random numbers/Xorshift star
| 14ruby
| 3wsz7 |
<?php $p = '<?php $p =%c%s%c; printf($p,39,$p,39);?>
'; printf($p,39,$p,39); ?> | 389Quine
| 12php
| 3wozq |
import kotlin.math.floor
class PCG32 {
private var state = 0x853c49e6748fea9buL
private var inc = 0xda3e39cb94b95bdbuL
fun nextInt(): UInt {
val old = state
state = old * N + inc
val shifted = old.shr(18).xor(old).shr(27).toUInt()
val rot = old.shr(59)
return (shifted shr rot.toInt()) or shifted.shl((rot.inv() + 1u).and(31u).toInt())
}
fun nextFloat(): Double {
return nextInt().toDouble() / (1L shl 32)
}
fun seed(seedState: ULong, seedSequence: ULong) {
state = 0u
inc = (seedSequence shl 1).or(1uL)
nextInt()
state += seedState
nextInt()
}
companion object {
private const val N = 6364136223846793005uL
}
}
fun main() {
val r = PCG32()
r.seed(42u, 54u)
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println()
val counts = Array(5) { 0 }
r.seed(987654321u, 1u)
for (i in 0 until 100000) {
val j = floor(r.nextFloat() * 5.0).toInt()
counts[j] += 1
}
println("The counts for 100,000 repetitions are:")
for (iv in counts.withIndex()) {
println(" %d:%d".format(iv.index, iv.value))
}
} | 393Pseudo-random numbers/PCG32
| 11kotlin
| c8i98 |
package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; c <= N; c++ {
s1 = s
s += 2
s2 = s
for d := c + 1; d <= N; d++ {
if ab[s1] {
r[d] = true
}
s1 += s2
s2 += 2
}
}
for d := 1; d <= N; d++ {
if !r[d] {
fmt.Printf("%d ", d)
}
}
fmt.Println()
} | 395Pythagorean quadruples
| 0go
| qggxz |
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
const (
width, height = 800, 600
maxDepth = 11 | 396Pythagoras tree
| 0go
| 6xw3p |
def middle_square (seed)
return to_enum(__method__, seed) unless block_given?
s = seed.digits.size
loop { yield seed = (seed*seed).to_s.rjust(s*2, )[s/2, s].to_i }
end
puts middle_square(675248).take(5) | 394Pseudo-random numbers/Middle-square method
| 14ruby
| c8o9k |
function uint32(n)
return n & 0xffffffff
end
function uint64(n)
return n & 0xffffffffffffffff
end
N = 6364136223846793005
state = 0x853c49e6748fea9b
inc = 0xda3e39cb94b95bdb
function pcg32_seed(seed_state, seed_sequence)
state = 0
inc = (seed_sequence << 1) | 1
pcg32_int()
state = state + seed_state
pcg32_int()
end
function pcg32_int()
local old = state
state = uint64(old * N + inc)
local shifted = uint32(((old >> 18) ~ old) >> 27)
local rot = uint32(old >> 59)
return uint32((shifted >> rot) | (shifted << ((~rot + 1) & 31)))
end
function pcg32_float()
return 1.0 * pcg32_int() / (1 << 32)
end | 393Pseudo-random numbers/PCG32
| 1lua
| lonck |
powersOfTwo :: [Int]
powersOfTwo = iterate (2 *) 1
unrepresentable :: [Int]
unrepresentable = merge powersOfTwo ((5 *) <$> powersOfTwo)
merge :: [Int] -> [Int] -> [Int]
merge xxs@(x:xs) yys@(y:ys)
| x < y = x: merge xs yys
| otherwise = y: merge xxs ys
main :: IO ()
main = do
putStrLn "The values of d <= 2200 which can't be represented."
print $ takeWhile (<= 2200) unrepresentable | 395Pythagorean quadruples
| 8haskell
| mssyf |
mkBranches :: [(Float,Float)] -> [[(Float,Float)]]
mkBranches [a, b, c, d] = let d = 0.5 <*> (b <+> (-1 <*> a))
l1 = d <+> orth d
l2 = orth l1
in
[ [a <+> l2, b <+> (2 <*> l2), a <+> l1, a]
, [a <+> (2 <*> l1), b <+> l1, b, b <+> l2] ]
where
(a, b) <+> (c, d) = (a+c, b+d)
n <*> (a, b) = (a*n, b*n)
orth (a, b) = (-b, a) | 396Pythagoras tree
| 8haskell
| jy67g |
import Foundation
struct XorshiftStar {
private let magic: UInt64 = 0x2545F4914F6CDD1D
private var state: UInt64
init(seed: UInt64) {
state = seed
}
mutating func nextInt() -> UInt64 {
state ^= state &>> 12
state ^= state &<< 25
state ^= state &>> 27
return (state &* magic) &>> 32
}
mutating func nextFloat() -> Float {
return Float(nextInt()) / Float(1 << 32)
}
}
extension XorshiftStar: RandomNumberGenerator, IteratorProtocol, Sequence {
mutating func next() -> UInt64 {
return nextInt()
}
mutating func next() -> UInt64? {
return nextInt()
}
}
for (i, n) in XorshiftStar(seed: 1234567).lazy.enumerated().prefix(5) {
print("\(i): \(n)")
}
var gen = XorshiftStar(seed: 987654321)
var counts = [Float: Int]()
for _ in 0..<100_000 {
counts[floorf(gen.nextFloat() * 5), default: 0] += 1
}
print(counts) | 392Pseudo-random numbers/Xorshift star
| 17swift
| zeqtu |
int64_t mod(int64_t x, int64_t y) {
int64_t m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
const static int64_t a1[3] = { 0, 1403580, -810728 };
const static int64_t m1 = (1LL << 32) - 209;
const static int64_t a2[3] = { 527612, 0, -1370589 };
const static int64_t m2 = (1LL << 32) - 22853;
const static int64_t d = (1LL << 32) - 209 + 1;
static int64_t x1[3];
static int64_t x2[3];
void seed(int64_t seed_state) {
x1[0] = seed_state;
x1[1] = 0;
x1[2] = 0;
x2[0] = seed_state;
x2[1] = 0;
x2[2] = 0;
}
int64_t next_int() {
int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
int64_t z = mod(x1i - x2i, m1);
x1[2] = x1[1];
x1[1] = x1[0];
x1[0] = x1i;
x2[2] = x2[1];
x2[1] = x2[0];
x2[0] = x2i;
return z + 1;
}
double next_float() {
return (double)next_int() / d;
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf(, next_int());
printf();
seed(987654321);
for (i = 0; i < 100000; i++) {
int64_t value = floor(next_float() * 5);
counts[value]++;
}
for (i = 0; i < 5; i++) {
printf(, i, counts[i]);
}
return 0;
} | 398Pseudo-random numbers/Combined recursive generator MRG32k3a
| 5c
| c8q9c |
use strict;
use warnings;
use feature 'say';
use Math::AnyNum qw(:overload);
package PCG32 {
use constant {
mask32 => 2**32 - 1,
mask64 => 2**64 - 1,
const => 6364136223846793005,
};
sub new {
my ($class, %opt) = @_;
my $seed = $opt{seed} // 1;
my $incr = $opt{incr} // 2;
$incr = $incr << 1 | 1 & mask64;
my $state = (($incr + $seed) * const + $incr) & mask64;
bless {incr => $incr, state => $state}, $class;
}
sub next_int {
my ($self) = @_;
my $state = $self->{state};
my $shift = ($state >> 18 ^ $state) >> 27 & mask32;
my $rotate = $state >> 59 & mask32;
$self->{state} = ($state * const + $self->{incr}) & mask64;
($shift >> $rotate) | $shift << (32 - $rotate) & mask32;
}
sub next_float {
my ($self) = @_;
$self->next_int / 2**32;
}
}
say "Seed: 42, Increment: 54, first 5 values:";
my $rng = PCG32->new(seed => 42, incr => 54);
say $rng->next_int for 1 .. 5;
say "\nSeed: 987654321, Increment: 1, values histogram:";
my %h;
$rng = PCG32->new(seed => 987654321, incr => 1);
$h{int 5 * $rng->next_float}++ for 1 .. 100_000;
say "$_ $h{$_}" for sort keys %h; | 393Pseudo-random numbers/PCG32
| 2perl
| x4rw8 |
import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d <%d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
} | 395Pythagorean quadruples
| 9java
| f11dv |
MASK64 = (1 << 64) - 1
C1 = 0x9e3779b97f4a7c15
C2 = 0xbf58476d1ce4e5b9
C3 = 0x94d049bb133111eb
class Splitmix64():
def __init__(self, seed=0):
self.state = seed & MASK64
def seed(self, num):
self.state = num & MASK64
def next_int(self):
z = self.state = (self.state + C1) & MASK64
z = ((z ^ (z >> 30)) * C2) & MASK64
z = ((z ^ (z >> 27)) * C3) & MASK64
answer = (z ^ (z >> 31)) & MASK64
return answer
def next_float(self):
return self.next_int() / (1 << 64)
if __name__ == '__main__':
random_gen = Splitmix64()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) | 397Pseudo-random numbers/Splitmix64
| 3python
| 8jr0o |
(() => {
'use strict'; | 395Pythagorean quadruples
| 10javascript
| yqq6r |
mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.inc = 0
def seed(self, seed_state, seed_sequence):
self.state = 0
self.inc = ((seed_sequence << 1) | 1) & mask64
self.next_int()
self.state = (self.state + seed_state)
self.next_int()
def next_int(self):
old = self.state
self.state = ((old * CONST) + self.inc) & mask64
xorshifted = (((old >> 18) ^ old) >> 27) & mask32
rot = (old >> 59) & mask32
answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
answer = answer &mask32
return answer
def next_float(self):
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = PCG32()
random_gen.seed(42, 54)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321, 1)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist) | 393Pseudo-random numbers/PCG32
| 3python
| qg7xi |
import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class PythagorasTree extends JPanel {
final int depthLimit = 7;
float hue = 0.15f;
public PythagorasTree() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2,
int depth) {
if (depth == depthLimit)
return;
float dx = x2 - x1;
float dy = y1 - y2;
float x3 = x2 - dy;
float y3 = y2 - dx;
float x4 = x1 - dy;
float y4 = y1 - dx;
float x5 = x4 + 0.5F * (dx - dy);
float y5 = y4 - 0.5F * (dx + dy);
Path2D square = new Path2D.Float();
square.moveTo(x1, y1);
square.lineTo(x2, y2);
square.lineTo(x3, y3);
square.lineTo(x4, y4);
square.closePath();
g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1));
g.fill(square);
g.setColor(Color.lightGray);
g.draw(square);
Path2D triangle = new Path2D.Float();
triangle.moveTo(x3, y3);
triangle.lineTo(x4, y4);
triangle.lineTo(x5, y5);
triangle.closePath();
g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1));
g.fill(triangle);
g.setColor(Color.lightGray);
g.draw(triangle);
drawTree(g, x4, y4, x5, y5, depth + 1);
drawTree(g, x5, y5, x3, y3, depth + 1);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawTree((Graphics2D) g, 275, 500, 375, 500, 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pythagoras Tree");
f.setResizable(false);
f.add(new PythagorasTree(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} | 396Pythagoras tree
| 9java
| udnvv |
null | 395Pythagorean quadruples
| 11kotlin
| 8jj0q |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.