code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
function clone(obj){
if (obj == null || typeof(obj) != 'object')
return obj;
var temp = {};
for (var key in obj)
temp[key] = clone(obj[key]);
return temp;
} | 414Polymorphic copy | 10javascript | sriqz |
package main
import (
"fmt"
"log"
"gonum.org/v1/gonum/mat"
)
func main() {
var (
x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
degree = 2
a = Vandermonde(x, degree+1)
b = mat.NewDense(len(y), 1, y)
c = mat.NewDense(degree+1, 1, nil)
)
... | 417Polynomial regression | 0go | gzr4n |
PriorityQueue = {
__index = {
put = function(self, p, v)
local q = self[p]
if not q then
q = {first = 1, last = 0}
self[p] = q
end
q.last = q.last + 1
q[q.last] = v
end,
pop = function(self)
... | 408Priority queue | 1lua | 5f1u6 |
import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n!= 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1)% n == 0
}
print((1...100).map... | 412Primality by Wilson's theorem | 17swift | bcxkd |
null | 423Pointers and references | 11kotlin | 5d9ua |
package main
import (
"fmt"
"sort"
"strings"
)
type card struct {
face byte
suit byte
}
const faces = "23456789tjqka"
const suits = "shdc"
func isStraight(cards []card) bool {
sorted := make([]card, 5)
copy(sorted, cards)
sort.Slice(sorted, func(i, j int) bool {
return sorted... | 419Poker hand analyser | 0go | ev1a6 |
int main() {
{
unsigned long long n = 1;
for (int i = 0; i < 30; i++) {
printf(, __builtin_popcountll(n));
n *= 3;
}
printf();
}
int od[30];
int ne = 0, no = 0;
printf();
for (int n = 0; ne+no < 60; n++) {
if ((__builtin_popcount(n) & 1) == 0) {
if... | 424Population count | 5c | 3eoza |
null | 414Polymorphic copy | 11kotlin | hm1j3 |
T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }
function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T) S1.name=function(s) return "S1" end
function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=func... | 414Polymorphic copy | 1lua | k9ah2 |
import Data.List
import Data.Array
import Control.Monad
import Control.Arrow
import Matrix.LU
ppoly p x = map (x**) p
polyfit d ry = elems $ solve mat vec where
mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d]
vec = listArray (1,d) $ take d ry | 417Polynomial regression | 8haskell | sr0qk |
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Proper{
public static List<Integer> properDivs(int n){
List<Integer> divs = new LinkedList<Integer>();
if(n == 1) return divs;
divs.add(1);
for(int x = 2; x < n; x++){
if(n % x... | 411Proper divisors | 9java | zeltq |
var total = 0
var prim = 0
var maxPeri = 100
func newTri(s0:Int, _ s1:Int, _ s2: Int) -> () {
let p = s0 + s1 + s2
if p <= maxPeri {
prim += 1
total += maxPeri / p
newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2)
newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+s1+... | 399Pythagorean triples | 17swift | gzn49 |
local table1 = {1,2,3}
local table2 = table1
table2[3] = 4
print(unpack(table1)) | 423Pointers and references | 1lua | 4fc5c |
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | King
... | 419Poker hand analyser | 8haskell | 3etzj |
(function () { | 411Proper divisors | 10javascript | 904ml |
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class PokerHandAnalyzer {
final static String faces = "AKQJT98765432";
final static String suits = "HDSC";
final static String[] deck = buildDeck();
public static void main(String[] args) {
System.out.prin... | 419Poker hand analyser | 9java | ih8os |
(defn population-count [n]
(Long/bitCount n))
(defn exp [n pow]
(reduce * (repeat pow n)))
(defn evil? [n]
(even? (population-count n)))
(defn odious? [n]
(odd? (population-count n)))
(defn integers []
(iterate inc 0))
(defn powers-of-n [n]
(map #(exp n %) (integers)))
(defn evil-numbers... | 424Population count | 6clojure | c0t9b |
package main
import "fmt"
func main() {
n := []float64{-42, 0, -12, 1}
d := []float64{-3, 1}
fmt.Println("N:", n)
fmt.Println("D:", d)
q, r, ok := pld(n, d)
if ok {
fmt.Println("Q:", q)
fmt.Println("R:", r)
} else {
fmt.Println("error")
}
}
func degree(p []floa... | 416Polynomial long division | 0go | mscyi |
const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'];
const SUITS = ['', '', '', ''];
function analyzeHand(hand){
let cards = hand.split(' ').filter(x => x !== 'joker');
let jokers = hand.split(' ').length - cards.length;
let faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) )... | 419Poker hand analyser | 10javascript | zaft2 |
import Data.List
shift n l = l ++ replicate n 0
pad n l = replicate n 0 ++ l
norm :: Fractional a => [a] -> [a]
norm = dropWhile (== 0)
deg l = length (norm l) - 1
zipWith' op p q = zipWith op (pad (-d) p) (pad d q)
where d = (length p) - (length q)
polydiv f g = aux (norm f) (norm g) []
where aux f s q | ddi... | 416Polynomial long division | 8haskell | k9ph0 |
package T;
sub new {
my $cls = shift;
bless [ @_ ], $cls
}
sub set_data {
my $self = shift;
@$self = @_;
}
sub copy {
my $self = shift;
bless [ @$self ], ref $self;
}
sub manifest {
my $self = shift;
print "type T, content: @$self\n\n";
}
package S;
ou... | 414Polymorphic copy | 2perl | zemtb |
import java.util.Arrays;
import java.util.function.IntToDoubleFunction;
import java.util.stream.IntStream;
public class PolynomialRegression {
private static void polyRegression(int[] x, int[] y) {
int n = x.length;
int[] r = IntStream.range(0, n).toArray();
double xm = Arrays.stream(x).ave... | 417Polynomial regression | 9java | 12ap2 |
int is_prime(unsigned int n)
{
unsigned int p;
if (!(n & 1) || n < 2 ) return n == 2;
for (p = 3; p <= n/p; p += 2)
if (!(n % p)) return 0;
return 1;
} | 425Primality by trial division | 5c | rzcg7 |
package main
import "fmt"
func pf(v float64) float64 {
switch {
case v < .06:
return .10
case v < .11:
return .18
case v < .16:
return .26
case v < .21:
return .32
case v < .26:
return .38
case v < .31:
return .44
case v < .36:
re... | 415Price fraction | 0go | f13d0 |
null | 411Proper divisors | 11kotlin | ik6o4 |
import random, bisect
def probchoice(items, probs):
'''\
Splits the interval 0.0-1.0 in proportion to probs
then finds where each random.random() choice lies
'''
prob_accumulator = 0
accumulator = []
for p in probs:
prob_accumulator += p
accumulator.append(prob_accumulator)
while True:
r ... | 410Probabilistic choice | 3python | r3agq |
my $scalar = 'aa';
my @array = ('bb', 'cc');
my %hash = ( dd => 'DD', ee => 'EE' );
my $scalarref = \$scalar;
my $arrayref = \@array;
my $hashref = \%hash; | 423Pointers and references | 2perl | ojw8x |
package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.... | 422Plot coordinate pairs | 0go | 87w0g |
<?php
class T {
function name() { return ; }
}
class S {
function name() { return ; }
}
$obj1 = new T();
$obj2 = new S();
$obj3 = clone $obj1;
$obj4 = clone $obj2;
echo $obj3->name(), ;
echo $obj4->name(), ;
?> | 414Polymorphic copy | 12php | bcek9 |
def priceFraction(value) {
assert value >= 0.0 && value <= 1.0
def priceMappings = [(0.06): 0.10, (0.11): 0.18, (0.16): 0.26, (0.21): 0.32, (0.26): 0.38,
(0.31): 0.44, (0.36): 0.50, (0.41): 0.54, (0.46): 0.58, (0.51): 0.62,
(0.56): 0.66, (0.61): 0.70, (0.66): 0.74, (0.71): 0.78, (0.76): 0.82,... | 415Price fraction | 7groovy | 8jn0b |
null | 411Proper divisors | 1lua | nbyi8 |
prob = c(aleph=1/5, beth=1/6, gimel=1/7, daleth=1/8, he=1/9, waw=1/10, zayin=1/11, heth=1759/27720)
hebrew = c(rmultinom(1, 1e6, prob))
d = data.frame(
Requested = prob,
Obtained = hebrew/sum(hebrew))
print(d) | 410Probabilistic choice | 13r | udkvx |
<?php
$a = 1;
$b =& $a;
$b = 2;
$c = $b;
$c = 7;
unset($a);
function &pass_out() {
global $filestr;
$filestr = get_file_contents();
return $_GLOBALS['filestr'];
}
function pass_in(&$in_filestr) {
echo . strlen($in_filestr);
$in_filestr .= ;
echo . strlen($in_filestr);
}
$tmp = &... | 423Pointers and references | 12php | gtl42 |
import groovy.swing.SwingBuilder
import javax.swing.JFrame
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection
import org.jfree.chart.plot.PlotOrientation
def chart = {
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [2.7, 2... | 422Plot coordinate pairs | 7groovy | wubel |
null | 419Poker hand analyser | 11kotlin | q4wx1 |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class PolynomialLongDivision {
public static void main(String[] args) {
RunDivideTest(new Polynomial(1, 3, -12, 2, -42, 0), new Polynomial(1, 1, -3, 0));
... | 416Polynomial long division | 9java | 4tr58 |
import copy
class T:
def classname(self):
return self.__class__.__name__
def __init__(self):
self.myValue =
def speak(self):
print self.classname(), 'Hello', self.myValue
def clone(self):
return copy.copy(self)
class S1(T):
def speak(self):
print self.classname(),, se... | 414Polymorphic copy | 3python | 3w9zc |
null | 417Polynomial regression | 11kotlin | jyh7r |
price_fraction n
| n < 0 || n > 1 = error "Values must be between 0 and 1."
| n < 0.06 = 0.10
| n < 0.11 = 0.18
| n < 0.16 = 0.26
| n < 0.21 = 0.32
| n < 0.26 = 0.38
| n < 0.31 = 0.44
| n < 0.36 = 0.50
| n < 0.41 = 0.54
| n < 0.46 = 0.58
| n < 0.51 = 0.62
| n < 0.56 = 0.66
| n < 0.61 = 0.70
... | 415Price fraction | 8haskell | 4t75s |
import Graphics.Gnuplot.Simple
pnts = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
doPlot = plotPathStyle [ ( Title "plotting dots" )]
(PlotStyle Points (CustomStyle [])) (zip [0..] pnts) | 422Plot coordinate pairs | 8haskell | l86ch |
null | 419Poker hand analyser | 1lua | sgxq8 |
function eval(a,b,c,x)
return a + (b + c * x) * x
end
function regression(xa,ya)
local n = #xa
local xm = 0.0
local ym = 0.0
local x2m = 0.0
local x3m = 0.0
local x4m = 0.0
local xym = 0.0
local x2ym = 0.0
for i=1,n do
xm = xm + xa[i]
ym = ym + ya[i]
x2... | 417Polynomial regression | 1lua | hmkj8 |
a =
b = []
class Foo(object):
pass
c = Foo()
class Bar(object):
def __init__(self, initializer = None)
if initializer is not None:
self.value = initializer
d = Bar(10)
print d.value
if a is b: pass
if id(a) == id(b): pass
def a(fmt, *args):
if fmt is N... | 423Pointers and references | 3python | ihxof |
null | 416Polynomial long division | 11kotlin | lovcp |
class T
def name
end
end
class S
def name
end
end
obj1 = T.new
obj2 = S.new
puts obj1.dup.name
puts obj2.dup.name | 414Polymorphic copy | 14ruby | yql6n |
object PolymorphicCopy {
def main(args: Array[String]) {
val a: Animal = Dog("Rover", 3, "Terrier")
val b: Animal = a.copy() | 414Polymorphic copy | 16scala | lo5cq |
(defn divides? [k n] (zero? (mod k n))) | 425Primality by trial division | 6clojure | b95kz |
probabilities = {
=> 1/5.0,
=> 1/6.0,
=> 1/7.0,
=> 1/8.0,
=> 1/9.0,
=> 1/10.0,
=> 1/11.0,
}
probabilities[] = 1.0 - probabilities.each_value.inject(:+)
ordered_keys = probabilities.keys
sum, sums = 0.0, {}
ordered_keys.each do |key|
sum += probabilities[key]
sums[key] = sum
end
ac... | 410Probabilistic choice | 14ruby | jyw7x |
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static doubl... | 422Plot coordinate pairs | 9java | 3enzg |
package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer | 420Polymorphism | 0go | a2b1f |
use strict;
use warnings;
use utf8;
use feature 'say';
use open qw<:encoding(utf-8) :std>;
package Hand {
sub describe {
my $str = pop;
my $hand = init($str);
return "$str: INVALID" if !$hand;
return analyze($hand);
}
sub init {
(my $str = lc shift) =~ tr/234567891j... | 419Poker hand analyser | 2perl | vil20 |
class T {
required init() { } | 414Polymorphic copy | 17swift | 6xc3j |
extern crate rand;
use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice};
use rand::{weak_rng, Rng};
const DATA: [(&str, f64); 8] = [
("aleph", 1.0 / 5.0),
("beth", 1.0 / 6.0),
("gimel", 1.0 / 7.0),
("daleth", 1.0 / 8.0),
("he", 1.0 / 9.0),
("waw", 1.0 / 10.0),
("z... | 410Probabilistic choice | 15rust | hmxj2 |
object ProbabilisticChoice extends App {
import scala.collection.mutable.LinkedHashMap
def weightedProb[A](prob: LinkedHashMap[A,Double]): A = {
require(prob.forall{case (_, p) => p > 0 && p < 1})
assume(prob.values.sum == 1)
def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A ... | 410Probabilistic choice | 16scala | pl0bj |
use 5.10.0;
use strict;
use Heap::Priority;
my $h = new Heap::Priority;
$h->highest_first();
$h->add(@$_) for ["Clear drains", 3],
["Feed cat", 4],
["Make tea", 5],
["Solve RC tasks", 1],
["Tax return", 2];
say while ($_ = $h->pop); | 408Priority queue | 2perl | 8jy0w |
#!/usr/local/bin/shale
aVariable var | 423Pointers and references | 16scala | 3eizy |
@Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true)
class Point {
Point(Point p) { x = p.x; y = p.y }
void print() { println toString() }
Number x
Number y
}
@Canonical
@TupleConstructor(force = true)
@ToString(includeNames = true, includeSuper = true)
class Circle extends Point {... | 420Polymorphism | 7groovy | hyrj9 |
import java.util.Random;
public class Main {
private static float priceFraction(float f) {
if (0.00f <= f && f < 0.06f) return 0.10f;
else if (f < 0.11f) return 0.18f;
else if (f < 0.16f) return 0.26f;
else if (f < 0.21f) return 0.32f;
else if (f < 0.26f) return 0.38f;
else if (f < 0.31f) return 0.44f;
... | 415Price fraction | 9java | c8v9h |
null | 422Plot coordinate pairs | 11kotlin | nksij |
data Point = Point Integer Integer
instance Show Point where
show (Point x y) = "Point at "++(show x)++","++(show y)
ponXAxis = flip Point 0
ponYAxis = Point 0
porigin = Point 0 0
data Circle = Circle Integer Integer Integer
instance Show Circle where
show (Circle x y r) = "Circle at "++(show x)++","++(s... | 420Polymorphism | 8haskell | zadt0 |
function getScaleFactor(v) {
var values = ['0.10','0.18','0.26','0.32','0.38','0.44','0.50','0.54',
'0.58','0.62','0.66','0.70','0.74','0.78','0.82','0.86',
'0.90','0.94','0.98','1.00'];
return values[(v * 100 - 1) / 5 | 0];
} | 415Price fraction | 10javascript | 5frur |
<?php
$pq = new SplPriorityQueue;
$pq->insert('Clear drains', 3);
$pq->insert('Feed cat', 4);
$pq->insert('Make tea', 5);
$pq->insert('Solve RC tasks', 1);
$pq->insert('Tax return', 2);
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
while (!$pq->isEmpty()) {
print_r($pq->extract());
}
?> | 408Priority queue | 12php | 4ta5n |
use strict;
use List::Util qw(min);
sub poly_long_div
{
my ($rn, $rd) = @_;
my @n = @$rn;
my $gd = scalar(@$rd);
if ( scalar(@n) >= $gd ) {
my @q = ();
while ( scalar(@n) >= $gd ) {
my $piv = $n[0]/$rd->[0];
push @q, $piv;
$n[$_] -= $rd->[$_] * $piv foreach ( 0 .. min(scalar(@n), $gd)... | 416Polynomial long division | 2perl | qg0x6 |
package main
import (
"fmt"
"math/big"
)
var (
ZERO = big.NewInt(0)
ONE = big.NewInt(1)
)
func Primes(n *big.Int) []*big.Int {
res := []*big.Int{}
mod, div := new(big.Int), new(big.Int)
for i := big.NewInt(2); i.Cmp(n) != 1; {
div.DivMod(n, i, mod)
for mod.Cmp(ZERO) == 0 ... | 418Prime decomposition | 0go | srsqa |
w_width = love.graphics.getWidth()
w_height = love.graphics.getHeight()
x = {0,1,2,3,4,5,6,7,8,9}
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
origin = {24,24}
points = {}
x_unit = w_width/x[10]/2
y_unit = w_height/10 | 422Plot coordinate pairs | 1lua | db0nq |
class Point {
protected int x, y;
public Point() { this(0); }
public Point(int x) { this(x, 0); }
public Point(int x, int y) { this.x = x; this.y = y; }
public Point(Point p) { this(p.x, p.y); }
public int getX() { return this.x; }
public int getY() { return this.y; }
public void setX(int x) { t... | 420Polymorphism | 9java | ojs8d |
from collections import namedtuple
class Card(namedtuple('Card', 'face, suit')):
def __repr__(self):
return ''.join(self)
suit = ' '.split()
faces = '2 3 4 5 6 7 8 9 10 j q k a'
lowaces = 'a 2 3 4 5 6 7 8 9 10 j q k'
face = faces.split()
lowace = lowaces.split()
def straightflush(hand):
f,f... | 419Poker hand analyser | 3python | un2vd |
package main
import (
"fmt"
"strconv"
"strings"
) | 421Power set | 0go | ojq8q |
null | 415Price fraction | 11kotlin | 3wmz5 |
def factorize = { long target ->
if (target == 1) return [1L]
if (target < 4) return [1L, target]
def targetSqrt = Math.sqrt(target)
def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 }
if (lowfactors == []) return [1L, target]
def nhalf = lowfactors.size() - ((lowfactors[-1]**2 ... | 418Prime decomposition | 7groovy | ava1p |
function Point() {
var arg1 = arguments[0];
var arg2 = arguments[1];
if (arg1 instanceof Point) {
this.x = arg1.x;
this.y = arg1.y;
}
else {
this.x = arg1 == null ? 0 : arg1;
this.y = arg2 == null ? 0 : arg1;
}
this.set_x = function(_x) {this.x = _x;}
... | 420Polymorphism | 10javascript | t1nfm |
from itertools import izip
def degree(poly):
while poly and poly[-1] == 0:
poly.pop()
return len(poly)-1
def poly_div(N, D):
dD = degree(D)
dN = degree(N)
if dD < 0: raise ZeroDivisionError
if dN >= dD:
q = [0] * dN
while dN >= dD:
d = [0]*(dN - dD) + D
... | 416Polynomial long division | 3python | sr8q9 |
def powerSetRec(head, tail) {
if (!tail) return [head]
powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail())
}
def powerSet(set) { powerSetRec([], set as List) as Set} | 421Power set | 7groovy | x51wl |
use ntheory qw/divisors/;
sub proper_divisors {
my $n = shift;
return 1 if $n == 0;
my @d = divisors($n);
pop @d;
@d;
}
say "$_: ", join " ", proper_divisors($_) for 1..10;
my($max,$ind) = (0,0);
for (1..20000) {
my $nd = scalar proper_divisors($_);
($max,$ind) = ($nd,$_) if $nd > $max;
}
say "$max $... | 411Proper divisors | 2perl | r31gd |
factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ]
where
divs n p | rem n p == 0 = p: divs (quot n p) p
| otherwise = [] | 418Prime decomposition | 8haskell | 909mo |
polylongdiv <- function(n,d) {
gd <- length(d)
pv <- vector("numeric", length(n))
pv[1:gd] <- d
if ( length(n) >= gd ) {
q <- c()
while ( length(n) >= gd ) {
q <- c(q, n[1]/pv[1])
n <- n - pv * (n[1]/pv[1])
n <- n[2:length(n)]
pv <- pv[1:(length(pv)-1)]
}
list(q=q, r=n)
... | 416Polynomial long division | 13r | euxad |
import Data.Set
import Control.Monad
powerset :: Ord a => Set a -> Set (Set a)
powerset = fromList . fmap fromList . listPowerset . toList
listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False]) | 421Power set | 8haskell | 2omll |
null | 420Polymorphism | 11kotlin | x5aws |
use strict;
use warnings;
use Statistics::Regression;
my @x = <0 1 2 3 4 5 6 7 8 9 10>;
my @y = <1 6 17 34 57 86 121 162 209 262 321>;
my @model = ('const', 'X', 'X**2');
my $reg = Statistics::Regression->new( '', [@model] );
$reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1;
my @coeff = $reg->theta();
... | 417Polynomial regression | 2perl | tazfg |
scaleTable = {
{0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32},
{0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54},
{0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70},
{0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86},
{0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00}
}
fun... | 415Price fraction | 1lua | 6x939 |
<?php
function ProperDivisors($n) {
yield 1;
$large_divisors = [];
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
yield $i;
if ($i*$i != $n) {
$large_divisors[] = $n / $i;
}
}
}
foreach (array_reverse($large_divisors) as $i) {
yield $i;
}
}
assert([1, 2, 4, 5... | 411Proper divisors | 12php | dpmn8 |
>>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, ), (4, ), (5, ), (1, ), (2, )):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>> | 408Priority queue | 3python | ohm81 |
null | 420Polymorphism | 1lua | q4ex0 |
class Card
include Comparable
attr_accessor :ordinal
attr_reader :suit, :face
SUITS = %i( )
FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)
def initialize(str)
@face, @suit = parse(str)
@ordinal = FACES.index(@face)
end
def <=> (other)
self.ordinal <=> other.ordinal
end
def to_s
en... | 419Poker hand analyser | 14ruby | 4fu5p |
public boolean prime(BigInteger i); | 418Prime decomposition | 9java | tatf9 |
fn main() {
let hands = vec![
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
];
for hand in hands{
... | 419Poker hand analyser | 15rust | gt54o |
public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
{
if(n<0)
{
return null;
}
if(n==0)
{
if(ps==null)
ps=new ArrayList<String>();
ps.add(" ");
return ps;
}
ps=getpower... | 421Power set | 9java | 6wf3z |
PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys... | 408Priority queue | 13r | qgzxs |
function run_factorize(input, output) {
var n = new BigInteger(input.value, 10);
var TWO = new BigInteger("2", 10);
var divisor = new BigInteger("3", 10);
var prod = false;
if (n.compareTo(TWO) < 0)
return;
output.value = "";
while (true) {
var qr = n.divideAndRemainder(... | 418Prime decomposition | 10javascript | msmyv |
val faces = "23456789TJQKA"
val suits = "CHSD"
sealed trait Card
object Joker extends Card
case class RealCard(face: Int, suit: Char) extends Card
val allRealCards = for {
face <- 0 until faces.size
suit <- suits
} yield RealCard(face, suit)
def parseCard(str: String): Card = {
if (str == "joker") {
Joker
... | 419Poker hand analyser | 16scala | j6r7i |
def polynomial_long_division(numerator, denominator)
dd = degree(denominator)
raise ArgumentError, if dd < 0
if dd == 0
return [multiply(numerator, 1.0/denominator[0]), [0]*numerator.length]
end
q = [0] * numerator.length
while (dn = degree(numerator)) >= dd
d = shift_right(denominator, dn - dd)
... | 416Polynomial long division | 14ruby | 8ji01 |
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs
array([ 3., 2., 1.]) | 417Polynomial regression | 3python | ze3tt |
function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(ary[i]));
}
}
return ps;
}
var res = powerset([1,2,3,4]);
load('json2.js');
print(JSON.stringify(res)); | 421Power set | 10javascript | l8ycf |
use GD::Graph::points;
@data = (
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0],
);
$graph = GD::Graph::points->new(400, 300);
open my $fh, '>', "qsort-range-10-9.png";
binmode $fh;
print $fh $graph->plot(\@data)->png;
close $fh; | 422Plot coordinate pairs | 2perl | 73urh |
package main
import (
"fmt"
"math/bits"
)
func main() {
fmt.Println("Pop counts, powers of 3:")
n := uint64(1) | 424Population count | 0go | b94kh |
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
coef(lm(y ~ x + I(x^2))) | 417Polynomial regression | 13r | nbdi2 |
import Data.Bits (popCount)
printPops :: (Show a, Integral a) => String -> [a] -> IO ()
printPops title counts = putStrLn $ title ++ show (take 30 counts)
main :: IO ()
main = do
printPops "popcount " $ map popCount $ iterate (*3) (1 :: Integer)
printPops "evil " $ filter (even . popCount) ([0..] :: [Integer]... | 424Population count | 8haskell | dbqn4 |
null | 418Prime decomposition | 11kotlin | oho8z |
class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
ite... | 408Priority queue | 14ruby | nbcit |
protocol Dividable {
static func / (lhs: Self, rhs: Self) -> Self
}
extension Int: Dividable { }
struct Solution<T> {
var quotient: [T]
var remainder: [T]
}
func polyDegree<T: SignedNumeric>(_ p: [T]) -> Int {
for i in stride(from: p.count - 1, through: 0, by: -1) where p[i]!= 0 {
return i
}
return ... | 416Polynomial long division | 17swift | 07os6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.