code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
var args = process.argv.slice(2); function time_to_seconds( hms ) { var parts = hms.split(':'); var h = parseInt(parts[0]); var m = parseInt(parts[1]); var s = parseInt(parts[2]); if ( h < 12 ) { h += 24; } var seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + pars...
1,120Averages/Mean time of day
10javascript
id0ol
package main import ( "fmt" "math" ) func main() { sum, sumr, prod := 0., 0., 1. for n := 1.; n <= 10; n++ { sum += n sumr += 1 / n prod *= n } a, g, h := sum/10, math.Pow(prod, .1), 10/sumr fmt.Println("A:", a, "G:", g, "H:", h) fmt.Println("A >= G >= H:", a >=...
1,117Averages/Pythagorean means
0go
cvl9g
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end func...
1,119Balanced ternary
1lua
8is0e
(let [i 42] (assert (= i 42)))
1,130Assertions
6clojure
rj3g2
fun <T> modeOf(a: Array<T>) { val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size } val maxFreq = sortedByFreq.first().value.size val modes = sortedByFreq.takeWhile { it.value.size == maxFreq } if (modes.size == 1) println("The mode of the collection is ${modes.first()....
1,118Averages/Mode
11kotlin
sosq7
typedef struct{ float* values; int size; }vector; vector extractVector(char* str){ vector coeff; int i=0,count = 1; char* token; while(str[i]!=00){ if(str[i++]==' ') count++; } coeff.values = (float*)malloc(count*sizeof(float)); coeff.size = count; token = strtok(str,); i = 0; while(token!=NULL){...
1,131Apply a digital filter (direct form II transposed)
5c
u4nv4
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000;
1,123Average loop length
9java
9ltmu
lastvalues <- local( { values <- c(); function(x, len) { values <<- c(values, x); lenv <- length(values); if(lenv > len) values <<- values[(len-lenv):-1] values } }) moving.average <- function(latestvalue, len=3) { is.numeric.scalar <- function(x) is.numeric(x) && length(...
1,115Averages/Simple moving average
13r
v4427
class AvlTree { private var root: Node? = null private class Node(var key: Int, var parent: Node?) { var balance: Int = 0 var left: Node? = null var right: Node? = null } fun insert(key: Int): Boolean { if (root == null) root = Node(key, null) else {...
1,121AVL tree
11kotlin
exba4
import java.util.Arrays; public class AverageMeanAngle { public static void main(String[] args) { printAverageAngle(350.0, 10.0); printAverageAngle(90.0, 180.0, 270.0, 360.0); printAverageAngle(10.0, 20.0, 30.0); printAverageAngle(370.0); printAverageAngle(180.0); } ...
1,122Averages/Mean angle
9java
dt0n9
def arithMean = { list -> list == null \ ? null \ : list.empty \ ? 0 \ : list.sum() / list.size() } def geomMean = { list -> list == null \ ? null \ : list.empty \ ? 1 \ : list.inject(1) { prod, item -> prod*item } ** (1 / list.size())...
1,117Averages/Pythagorean means
7groovy
3m6zd
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.p...
1,127Associative array/Merging
9java
g7y4m
(() => { 'use strict'; console.log(JSON.stringify( Object.assign({},
1,127Associative array/Merging
10javascript
kp2hq
const val NMAX = 20 const val TESTS = 1000000 val rand = java.util.Random() fun avg(n: Int): Double { var sum = 0 for (t in 0 until TESTS) { val v = BooleanArray(NMAX) var x = 0 while (!v[x]) { v[x] = true sum++ x = rand.nextInt(n) } } ...
1,123Average loop length
11kotlin
z6ots
null
1,120Averages/Mean time of day
11kotlin
1ekpd
AVL={balance=0} AVL.__mt={__index = AVL} function AVL:new(list) local o={} setmetatable(o, AVL.__mt) for _,v in ipairs(list or {}) do o=o:insert(v) end return o end function AVL:rebalance() local rotated=false if self.balance>1 then if self.right.balance<0 then self.right, self.right.le...
1,121AVL tree
1lua
wqpea
function sum(a) { var s = 0; for (var i = 0; i < a.length; i++) s += a[i]; return s; } function degToRad(a) { return Math.PI / 180 * a; } function meanAngleDeg(a) { return 180 / Math.PI * Math.atan2( sum(a.map(degToRad).map(Math.sin)) / a.length, sum(a.map(degToRad).map(Math.cos))...
1,122Averages/Mean angle
10javascript
6md38
import Data.List (genericLength) import Control.Monad (zipWithM_) mean :: Double -> [Double] -> Double mean 0 xs = product xs ** (1 / genericLength xs) mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p) main = do let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1] mapM_ (\(t,m) -> putStr...
1,117Averages/Pythagorean means
8haskell
pe1bt
package main import ( "fmt" "log" "math/big" ) func max(a, b *big.Float) *big.Float { if a.Cmp(b) > 0 { return a } return b } func isClose(a, b *big.Float) bool { relTol := big.NewFloat(1e-9)
1,128Approximate equality
0go
lvncw
(defn gen-brackets [n] (->> (concat (repeat n \[) (repeat n \])) shuffle (apply str ,))) (defn balanced? [s] (loop [[first & coll] (seq s) stack '()] (if first (if (= first \[) (recur coll (conj stack \[)) (when (= (peek stack) \[) (recur coll (pop stack)))) (zero? (count stack...
1,129Balanced brackets
6clojure
2unl1
main() { var i = 42; assert( i == 42 ); }
1,130Assertions
18dart
y9q65
function mode(tbl)
1,118Averages/Mode
1lua
0i0sd
fun main() { val base = HashMap<String,String>() val update = HashMap<String,String>() base["name"] = "Rocket Skates" base["price"] = "12.75" base["color"] = "yellow" update["price"] = "15.25" update["color"] = "red" update["year"] = "1974" val merged = HashMap(base) merged.p...
1,127Associative array/Merging
11kotlin
2ufli
function average(n, reps) local count = 0 for r = 1, reps do local f = {} for i = 1, n do f[i] = math.random(n) end local seen, x = {}, 1 while not seen[x] do seen[x], x, count = true, f[x], count+1 end end return count / reps end function analytical(n) local s, t = 1, 1 for i = n...
1,123Average loop length
1lua
3yizo
class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon } private static void test(double a, double b) { double epsilon = 1e-18 System.out.printf("%f,%f =>%s\n", a, b, approxEquals(a, b, epsilon))...
1,128Approximate equality
7groovy
6ms3o
class (Num a, Ord a, Eq a) => AlmostEq a where eps :: a infix 4 ~= (~=) :: AlmostEq a => a -> a -> Bool a ~= b = or [ a == b , abs (a - b) < eps * abs(a + b) , abs (a - b) < eps ] instance AlmostEq Int where eps = 0 instance AlmostEq Integer where eps = 0 instance AlmostEq Double where eps =...
1,128Approximate equality
8haskell
1eups
typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; passwd_t passwd_list[]={ {, , 1001, 1000, {, , , , }, , }, {, , 1002, 1000, {, , , ,...
1,132Append a record to the end of a text file
5c
g7f45
double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf(); for (i = 0; i < len; i++) printf(i ? : , v[i]); printf(, mean(v, len)); }...
1,133Averages/Arithmetic mean
5c
2u0lo
base = {name="Rocket Skates", price=12.75, color="yellow"} update = {price=15.25, color="red", year=1974}
1,127Associative array/Merging
1lua
v5t2x
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
1,124Attractive numbers
0go
jkv7d
local times = {"23:00:17","23:40:20","00:12:45","00:17:19"}
1,120Averages/Mean time of day
1lua
awb1v
null
1,122Averages/Mean angle
11kotlin
0oesf
public class Approximate { private static boolean approxEquals(double value, double other, double epsilon) { return Math.abs(value - other) < epsilon; } private static void test(double a, double b) { double epsilon = 1e-18; System.out.printf("%f,%f =>%s\n", a, b, approxEquals(a, b, ...
1,128Approximate equality
9java
7hmrj
package main import ( "fmt" "math/rand" "sync" "time" ) const nBuckets = 10 type bucketList struct { b [nBuckets]int
1,126Atomic updates
0go
7hcr2
use List::Util qw(sum reduce); sub find_loop { my($n) = @_; my($r,@seen); while () { $seen[$r] = $seen[($r = int(1+rand $n))] ? return sum @seen : 1 } } print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n"; my $MAX = 20; my $TRIALS = 1000; for my $n (1 ...
1,123Average loop length
2perl
b1gk4
class AttractiveNumbers { static boolean isPrime(int n) { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 int d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false ...
1,124Attractive numbers
7groovy
5gmuv
function meanAngle (angleList) local sumSin, sumCos = 0, 0 for i, angle in pairs(angleList) do sumSin = sumSin + math.sin(math.rad(angle)) sumCos = sumCos + math.cos(math.rad(angle)) end local result = math.deg(math.atan2(sumSin, sumCos)) return string.format("%.2f", result) end print(meanAngle({350,...
1,122Averages/Mean angle
1lua
8iw0e
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; ...
1,119Balanced ternary
2perl
5gvu2
import kotlin.math.abs import kotlin.math.sqrt fun approxEquals(value: Double, other: Double, epsilon: Double): Boolean { return abs(value - other) < epsilon } fun test(a: Double, b: Double) { val epsilon = 1e-18 println("$a, $b => ${approxEquals(a, b, epsilon)}") } fun main() { test(100000000000000....
1,128Approximate equality
11kotlin
u4tvc
class Buckets { def cells = [] final n Buckets(n, limit=1000, random=new Random()) { this.n = n (0..<n).each { cells << random.nextInt(limit) } } synchronized getAt(i) { cells[i] } synchronized transfer(from, to, amount) { assert from i...
1,126Atomic updates
7groovy
u43v9
using System; using System.Collections.Generic; namespace AssocArrays { class Program { static void Main(string[] args) { Dictionary<string,int> assocArray = new Dictionary<string,int>(); assocArray[] = 1; assocArray.Add(, 2); assocArray[] = 3; ...
1,134Associative array/Iteration
5c
nf7i6
package main import "fmt" type filter struct { b, a []float64 } func (f filter) filter(in []float64) []float64 { out := make([]float64, len(in)) s := 1. / f.a[0] for i := range in { tmp := 0. b := f.b if i+1 < len(b) { b = b[:i+1] } for j, bj := ran...
1,131Apply a digital filter (direct form II transposed)
0go
0orsk
(defn mean [sq] (if (empty? sq) 0 (/ (reduce + sq) (count sq))))
1,133Averages/Arithmetic mean
6clojure
g7d4f
use strict; use warnings; my %base = ("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); my %more = ("price" => 15.25, "color" => "red", "year" => 1974); print "Update\n"; my %update = (%base, %more); printf "%-7s%s\n", $_, $update{$_} for sort keys %update; print "\nMerge\n"; my %merge; $merge{$_} =...
1,127Associative array/Merging
2perl
s8hq3
def simple_moving_average(size) nums = [] sum = 0.0 lambda do |hello| nums << hello goodbye = nums.length > size? nums.shift: 0 sum += hello - goodbye sum / nums.length end end ma3 = simple_moving_average(3) ma5 = simple_moving_average(5) (1.upto(5).to_a + 5.downto(1).to_a).each do |num| pri...
1,115Averages/Simple moving average
14ruby
7kkri
import Data.Numbers.Primes import Data.Bool (bool) attractiveNumbers :: [Integer] attractiveNumbers = [1 ..] >>= (bool [] . return) <*> (isPrime . length . primeFactors) main :: IO () main = print $ takeWhile (<= 120) attractiveNumbers
1,124Attractive numbers
8haskell
one8p
n=0 while n**2% 1000000 != 269696: n += 1 print(n) >>> [x for x in range(30000) if (x*x)% 1000000 == 269696] [0] 25264
1,116Babbage problem
3python
x0swr
function approxEquals(value, other, epsilon) return math.abs(value - other) < epsilon end function test(a, b) local epsilon = 1e-18 print(string.format("%f,%f =>%s", a, b, tostring(approxEquals(a, b, epsilon)))) end function main() test(100000000000000.01, 100000000000000.011); test(100.01, 100.01...
1,128Approximate equality
1lua
5gzu6
module AtomicUpdates (main) where import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_) import Control.Monad (forever, forM_) import Data.IntMap (IntMap, (!), toAscList, fromList, adjust) import System.Random (randomRIO) import Text.Printf (printf) typ...
1,126Atomic updates
8haskell
8ip0z
class DigitalFilter { private static double[] filter(double[] a, double[] b, double[] signal) { double[] result = new double[signal.length] for (int i = 0; i < signal.length; ++i) { double tmp = 0.0 for (int j = 0; j < b.length; ++j) { if (i - j < 0) continue ...
1,131Apply a digital filter (direct form II transposed)
7groovy
exval
<? $base = array( => , => 12.75, => ); $update = array( => 15.25, => , => 1974); $result = $update + $base; print_r($result); ?>
1,127Associative array/Merging
12php
u4zv5
(() => { 'use strict';
1,124Attractive numbers
10javascript
8ia0l
import java.util.Arrays; import java.util.List; public class PythagoreanMeans { public static double arithmeticMean(List<Double> numbers) { if (numbers.isEmpty()) return Double.NaN; double mean = 0.0; for (Double number : numbers) { mean += number; } return mean ...
1,117Averages/Pythagorean means
9java
rh7g0
babbage_function=function(){ n=0 while (n**2%%1000000!=269696) { n=n+1 } return(n) } babbage_function()[length(babbage_function())]
1,116Babbage problem
13r
1wepn
import Data.List (tails) conv :: Num a => [a] -> [a] -> [a] conv ker = map (dot (reverse ker)) . tails . pad where pad v = replicate (length ker - 1) 0 ++ v dot v = sum . zipWith (*) v dFilter :: [Double] -> [Double] -> [Double] -> [Double] dFilter (a0:a) b s = tail res where res = (/ a0) <$> 0: zi...
1,131Apply a digital filter (direct form II transposed)
8haskell
c2094
base = {:, :12.75, :} update = {:15.25, :, :1974} result = {**base, **update} print(result)
1,127Associative array/Merging
3python
0oksq
struct SimpleMovingAverage { period: usize, numbers: Vec<usize> } impl SimpleMovingAverage { fn new(p: usize) -> SimpleMovingAverage { SimpleMovingAverage { period: p, numbers: Vec::new() } } fn add_number(&mut self, number: usize) -> f64 { self.numb...
1,115Averages/Simple moving average
15rust
jbb72
public class Attractive { static boolean is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d *d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return f...
1,124Attractive numbers
9java
wqhej
import enum class entry_not_found(Exception): pass class entry_already_exists(Exception): pass class state(enum.Enum): header = 0 left_high = 1 right_high = 2 balanced = 3 class direction(enum.Enum): from_left = 0 from_right = 1 from abc import ABC, abstractmethod class comparer(AB...
1,121AVL tree
3python
lvycv
(function () { 'use strict';
1,117Averages/Pythagorean means
10javascript
bapki
import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; public class AtomicUpdates { private static final int NUM_BUCKETS = 10; public static class Buckets { private final int[] data; public Buckets(int[] data) { this.data = data.clone(); } public...
1,126Atomic updates
9java
exra5
package main func main() { x := 43 if x != 42 { panic(42) } }
1,130Assertions
0go
s8rqa
def checkTheAnswer = { assert it == 42: "This: " + it + " is not the answer!" }
1,130Assertions
7groovy
awv1p
public class DigitalFilter { private static double[] filter(double[] a, double[] b, double[] signal) { double[] result = new double[signal.length]; for (int i = 0; i < signal.length; ++i) { double tmp = 0.0; for (int j = 0; j < b.length; ++j) { if (i - j < 0) ...
1,131Apply a digital filter (direct form II transposed)
9java
z6atq
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (...
1,123Average loop length
3python
parbm
expected <- function(size) { result <- 0 for (i in 1:size) { result <- result + factorial(size) / size^i / factorial(size -i) } result } knuth <- function(size) { v <- sample(1:size, size, replace = TRUE) visit <- vector('logical',size) place <- 1 visit[[1]] <- TRUE steps <- 0 repeat { pl...
1,123Average loop length
13r
jku78
class MovingAverage(period: Int) { private var queue = new scala.collection.mutable.Queue[Double]() def apply(n: Double) = { queue.enqueue(n) if (queue.size > period) queue.dequeue queue.sum / queue.size } override def toString = queue.mkString("(", ", ", ")")+", period "+period+", average "+(...
1,115Averages/Simple moving average
16scala
baak6
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(...
1,119Balanced ternary
3python
4ru5k
use strict; use warnings; sub is_close { my($a,$b,$eps) = @_; $eps //= 15; my $epse = $eps; $epse++ if sprintf("%.${eps}f",$a) =~ /\./; $epse++ if sprintf("%.${eps}f",$a) =~ /\-/; my $afmt = substr((sprintf "%.${eps}f", $a), 0, $epse); my $bfmt = substr((sprintf "%.${eps}f", $b), 0, $epse);...
1,128Approximate equality
2perl
8ik0w
int countDivisors(int n) { int i, count; if (n < 2) return 1; count = 2; for (i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; } int main() { int n, d, maxDiv = 0, count = 0; printf(); for (n = 1; count < 20; ++n) { d = countDivisors(n); if (d...
1,135Anti-primes
5c
jkf70
null
1,126Atomic updates
11kotlin
kpvh3
import Control.Exception main = let a = someValue in assert (a == 42) somethingElse
1,130Assertions
8haskell
9l0mo
(doseq [[k v] {:a 1,:b 2,:c 3}] (println k "=" v)) (doseq [k (keys {:a 1,:b 2,:c 3})] (println k)) (doseq [v (vals {:a 1,:b 2,:c 3})] (println v))
1,134Associative array/Iteration
6clojure
3ypzr
null
1,131Apply a digital filter (direct form II transposed)
11kotlin
idho4
num mean(List<num> l) => l.reduce((num p, num n) => p + n) / l.length; void main(){ print(mean([1,2,3,4,5,6,7])); }
1,133Averages/Arithmetic mean
18dart
6ma34
base = { => , => 12.75, => } update = { => 15.25, => , => 1974} result = base.merge(update) p result
1,127Associative array/Merging
14ruby
onp8v
use std::collections::HashMap; fn main() { let mut original = HashMap::new(); original.insert("name", "Rocket Skates"); original.insert("price", "12.75"); original.insert("color", "yellow"); let mut update = HashMap::new(); update.insert("price", "15.25"); update.insert("color", "red"); ...
1,127Associative array/Merging
15rust
id1od
null
1,124Attractive numbers
11kotlin
b14kb
use strict; use warnings; use POSIX 'fmod'; use Math::Complex; use List::Util qw(sum); use utf8; use constant => 2 * 3.1415926535; sub tod2rad { ($h,$m,$s) = split /:/, @_[0]; (3600*$h + 60*$m + $s) * / 86400; } sub rad2tod { my $x = $_[0] * 86400 / ; sprintf '%02d:%02d:%02d', fm($x/3600,24), fm(...
1,120Averages/Mean time of day
2perl
mc3yz
import scala.collection.mutable class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] { if (ordering eq null) throw new NullPointerException("ordering must not be null") private var _root: AVLNode = _ private var _size = 0 override def size: Int = _size override def foreach[U]...
1,121AVL tree
15rust
u4cvj
n = 0 n = n + 2 until (n*n).modulo(1000000) == 269696 print n
1,116Babbage problem
14ruby
so8qw
math.isclose -> bool a: double b: double * rel_tol: double = 1e-09 maximum difference for being considered , relative to the magnitude of the input values abs_tol: double = 0.0 maximum difference for being considered , regardless of the magnitude of the input values D...
1,128Approximate equality
3python
onb81
public class Assertions { public static void main(String[] args) { int a = 13;
1,130Assertions
9java
t3af9
function check() { try { if (isNaN(answer)) throw '$answer is not a number'; if (answer != 42) throw '$answer is not 42'; } catch(err) { console.log(err); answer = 42; } finally { console.log(answer); } } console.count('try');
1,130Assertions
10javascript
mcsyv
void map(int* array, int len, void(*callback)(int,int));
1,136Apply a callback to an array
5c
awy11
function filter(b,a,input) local out = {} for i=1,table.getn(input) do local tmp = 0 local j = 0 out[i] = 0 for j=1,table.getn(b) do if i - j < 0 then
1,131Apply a digital filter (direct form II transposed)
1lua
nfki8
let base: [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"] let update: [String: Any] = ["price": 15.25, "color": "red", "year": 1974] let result = base.merging(update) { (_, new) in new } print(result)
1,127Associative array/Merging
17swift
8ib0v
import scala.collection.mutable class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] { if (ordering eq null) throw new NullPointerException("ordering must not be null") private var _root: AVLNode = _ private var _size = 0 override def size: Int = _size override def foreach[U]...
1,121AVL tree
16scala
g7v4i
sub Pi () { 3.1415926535897932384626433832795028842 } sub meanangle { my($x, $y) = (0,0); ($x,$y) = ($x + sin($_), $y + cos($_)) for @_; my $atan = atan2($x,$y); $atan += 2*Pi while $atan < 0; $atan -= 2*Pi while $atan > 2*Pi; $atan; } sub meandegrees { meanangle( map { $_ * Pi/180 } @_ ) * 180/Pi; ...
1,122Averages/Mean angle
2perl
5gcu2
fn main() { let mut current = 0; while (current * current)% 1_000_000!= 269_696 { current += 1; } println!( "The smallest number whose square ends in 269696 is {}", current ); }
1,116Babbage problem
15rust
0iosl
approxEq <- function(...) isTRUE(all.equal(...)) tests <- rbind(c(100000000000000.01, 100000000000000.011), c(100.01, 100.011), c(10000000000000.001 / 10000.0, 1000000000.0000001000), c(0.001, 0.0010000001), c(0.000000000000000000000101, 0.0), c(sqrt(2) *...
1,128Approximate equality
13r
q07xs
fun main() { val a = 42 assert(a == 43) }
1,130Assertions
11kotlin
onh8z
class Integer def factorial self == 0? 1: (1..self).inject(:*) end end def rand_until_rep(n) rands = {} loop do r = rand(1..n) return rands.size if rands[r] rands[r] = true end end runs = 1_000_000 puts , (1..20).each do |n| sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_un...
1,123Average loop length
14ruby
awj1s
extern crate rand; use rand::{ThreadRng, thread_rng}; use rand::distributions::{IndependentSample, Range}; use std::collections::HashSet; use std::env; use std::process; fn help() { println!("usage: average_loop_length <max_N> <trials>"); } fn main() { let args: Vec<String> = env::args().collect(); let m...
1,123Average loop length
15rust
exhaj
null
1,124Attractive numbers
1lua
pagbw
<?php function time2ang($tim) { if (!is_string($tim)) return $tim; $parts = explode(':',$tim); if (count($parts)!=3) return $tim; $sec = ($parts[0]*3600)+($parts[1]*60)+$parts[2]; $ang = 360.0 * ($sec/86400.0); return $ang; } function ang2time($ang) { if (!is_nume...
1,120Averages/Mean time of day
12php
expa9
import kotlin.math.round import kotlin.math.pow fun Collection<Double>.geometricMean() = if (isEmpty()) Double.NaN else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size) fun Collection<Double>.harmonicMean() = if (isEmpty() || contains(0.0)) Double.NaN else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 } f...
1,117Averages/Pythagorean means
11kotlin
v4u21
object BabbageProblem { def main( args:Array[String] ): Unit = { var x : Int = 524
1,116Babbage problem
16scala
ifdox
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error...
1,132Append a record to the end of a text file
0go
idjog
(map inc [1 2 3 4])
1,136Apply a callback to an array
6clojure
s82qr