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 + parseInt(parts[2]); return seconds; } function seconds_to_time( s ) { var h = Math.floor( s/(60 * 60) ); if ( h < 10 ) { h = '0' + h; } s = s % (60 * 60); var m = Math.floor( s/60 ); if ( m < 10 ) { m = '0' + m; } s = s % 60 if ( s < 10 ) { s = '0' + s; } return h + ':' + m + ':' + s; } var sum = 0, count = 0, idx; for (idx in args) { var seconds = time_to_seconds( args[idx] ); sum += seconds; count++; } var seconds = Math.floor( sum / count ) console.log( 'Mean time is ', seconds_to_time(seconds));
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 >= g && g >= h) }
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 function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a:%14s%10d", a, from_bt(a))) print(string.format(" b:%14s%10d", b, from_bt(b))) print(string.format(" c:%14s%10d", c, from_bt(c))) print(string.format("a*(b-c):%14s%10d", d, from_bt(d))) end main()
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().key} which has a frequency of $maxFreq") else { print("There are ${modes.size} modes with a frequency of $maxFreq, namely: ") println(modes.map { it.key }.joinToString(", ")) } } fun main(args: Array<String>) { val a = arrayOf(7, 1, 1, 6, 2, 4, 2, 4, 2, 1, 5) println("[" + a.joinToString(", ") + "]") modeOf(a) println() val b = arrayOf(true, false, true, false, true, true) println("[" + b.joinToString(", ") + "]") modeOf(b) }
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){ coeff.values[i++] = atof(token); token = strtok(NULL,); } return coeff; } vector processSignalFile(char* fileName){ int i,j; float sum; char str[MAX_LEN]; vector coeff1,coeff2,signal,filteredSignal; FILE* fp = fopen(fileName,); fgets(str,MAX_LEN,fp); coeff1 = extractVector(str); fgets(str,MAX_LEN,fp); coeff2 = extractVector(str); fgets(str,MAX_LEN,fp); signal = extractVector(str); fclose(fp); filteredSignal.values = (float*)calloc(signal.size,sizeof(float)); filteredSignal.size = signal.size; for(i=0;i<signal.size;i++){ sum = 0; for(j=0;j<coeff2.size;j++){ if(i-j>=0) sum += coeff2.values[j]*signal.values[i-j]; } for(j=0;j<coeff1.size;j++){ if(i-j>=0) sum -= coeff1.values[j]*filteredSignal.values[i-j]; } sum /= coeff1.values[0]; filteredSignal.values[i] = sum; } return filteredSignal; } void printVector(vector v, char* outputFile){ int i; if(outputFile==NULL){ printf(); for(i=0;i<v.size;i++) printf(,v.values[i]); printf(); } else{ FILE* fp = fopen(outputFile,); for(i=0;i<v.size-1;i++) fprintf(fp,,v.values[i]); fprintf(fp,,v.values[i]); fclose(fp); } } int main(int argC,char* argV[]) { char *str; if(argC<2||argC>3) printf(,argV[0]); else{ if(argC!=2){ str = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char)); strcpy(str,); } printf(,(argC==2)?:strcat(str,argV[2])); printVector(processSignalFile(argV[1]),argV[2]); } return 0; }
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(x)==1L if(!is.numeric.scalar(latestvalue) ||!is.numeric.scalar(len)) { stop("all arguments must be numeric scalars") } mean(lastvalues(latestvalue, len)) } moving.average(5) moving.average(1) moving.average(-3) moving.average(8) moving.average(7)
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 { var n: Node? = root var parent: Node while (true) { if (n!!.key == key) return false parent = n val goLeft = n.key > key n = if (goLeft) n.left else n.right if (n == null) { if (goLeft) parent.left = Node(key, parent) else parent.right = Node(key, parent) rebalance(parent) break } } } return true } fun delete(delKey: Int) { if (root == null) return var n: Node? = root var parent: Node? = root var delNode: Node? = null var child: Node? = root while (child!= null) { parent = n n = child child = if (delKey >= n.key) n.right else n.left if (delKey == n.key) delNode = n } if (delNode!= null) { delNode.key = n!!.key child = if (n.left!= null) n.left else n.right if (0 == root!!.key.compareTo(delKey)) { root = child if (null!= root) { root!!.parent = null } } else { if (parent!!.left == n) parent.left = child else parent.right = child if (null!= child) { child.parent = parent } rebalance(parent) } } private fun rebalance(n: Node) { setBalance(n) var nn = n if (nn.balance == -2) if (height(nn.left!!.left) >= height(nn.left!!.right)) nn = rotateRight(nn) else nn = rotateLeftThenRight(nn) else if (nn.balance == 2) if (height(nn.right!!.right) >= height(nn.right!!.left)) nn = rotateLeft(nn) else nn = rotateRightThenLeft(nn) if (nn.parent!= null) rebalance(nn.parent!!) else root = nn } private fun rotateLeft(a: Node): Node { val b: Node? = a.right b!!.parent = a.parent a.right = b.left if (a.right!= null) a.right!!.parent = a b.left = a a.parent = b if (b.parent!= null) { if (b.parent!!.right == a) b.parent!!.right = b else b.parent!!.left = b } setBalance(a, b) return b } private fun rotateRight(a: Node): Node { val b: Node? = a.left b!!.parent = a.parent a.left = b.right if (a.left!= null) a.left!!.parent = a b.right = a a.parent = b if (b.parent!= null) { if (b.parent!!.right == a) b.parent!!.right = b else b.parent!!.left = b } setBalance(a, b) return b } private fun rotateLeftThenRight(n: Node): Node { n.left = rotateLeft(n.left!!) return rotateRight(n) } private fun rotateRightThenLeft(n: Node): Node { n.right = rotateRight(n.right!!) return rotateLeft(n) } private fun height(n: Node?): Int { if (n == null) return -1 return 1 + Math.max(height(n.left), height(n.right)) } private fun setBalance(vararg nodes: Node) { for (n in nodes) n.balance = height(n.right) - height(n.left) } fun printKey() { printKey(root) println() } private fun printKey(n: Node?) { if (n!= null) { printKey(n.left) print("${n.key} ") printKey(n.right) } } fun printBalance() { printBalance(root) println() } private fun printBalance(n: Node?) { if (n!= null) { printBalance(n.left) print("${n.balance} ") printBalance(n.right) } } } fun main(args: Array<String>) { val tree = AvlTree() println("Inserting values 1 to 10") for (i in 1..10) tree.insert(i) print("Printing key : ") tree.printKey() print("Printing balance: ") tree.printBalance() }
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); } private static void printAverageAngle(double... sample) { double meanAngle = getMeanAngle(sample); System.out.printf("The mean angle of%s is%s%n", Arrays.toString(sample), meanAngle); } public static double getMeanAngle(double... anglesDeg) { double x = 0.0; double y = 0.0; for (double angleD: anglesDeg) { double angleR = Math.toRadians(angleD); x += Math.cos(angleR); y += Math.sin(angleR); } double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length); return Math.toDegrees(avgR); } }
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()) } def harmMean = { list -> list == null \ ? null \ : list.empty \ ? 0 \ : list.size() / list.collect { 1.0/it }.sum() }
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.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
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) } } return sum.toDouble() / TESTS } fun ana(n: Int): Double { val nn = n.toDouble() var term = 1.0 var sum = 1.0 for (i in n - 1 downTo 1) { term *= i / nn sum += term } return sum } fun main(args: Array<String>) { println(" N average analytical (error)") println("=== ========= ============ =========") for (n in 1..NMAX) { val a = avg(n) val b = ana(n) println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0)) } }
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.left.right, self.right.left = self.right.left, self.right, self.right.left.right self.right.right.balance=self.right.balance>-1 and 0 or 1 self.right.balance=self.right.balance>0 and 2 or 1 end self, self.right.left, self.right = self.right, self, self.right.left self.left.balance=1-self.balance self.balance=self.balance==0 and -1 or 0 rotated=true elseif self.balance<-1 then if self.left.balance>0 then self.left, self.left.right.left, self.left.right = self.left.right, self.left, self.left.right.left self.left.left.balance=self.left.balance<1 and 0 or -1 self.left.balance=self.left.balance<0 and -2 or -1 end self, self.left.right, self.left = self.left, self, self.left.right self.right.balance=-1-self.balance self.balance=self.balance==0 and 1 or 0 rotated=true end return self,rotated end function AVL:insert(v) if not self.value then self.value=v self.balance=0 return self,1 end local grow if v==self.value then return self,0 elseif v<self.value then if not self.left then self.left=self:new() end self.left,grow=self.left:insert(v) self.balance=self.balance-grow else if not self.right then self.right=self:new() end self.right,grow=self.right:insert(v) self.balance=self.balance+grow end self,rotated=self:rebalance() return self, (rotated or self.balance==0) and 0 or grow end function AVL:delete_move(dir,other,mul) if self[dir] then local sb2,v self[dir], sb2, v=self[dir]:delete_move(dir,other,mul) self.balance=self.balance+sb2*mul self,sb2=self:rebalance() return self,(sb2 or self.balance==0) and -1 or 0,v else return self[other],-1,self.value end end function AVL:delete(v,isSubtree) local grow=0 if v==self.value then local v if self.balance>0 then self.right,grow,v=self.right:delete_move("left","right",-1) elseif self.left then self.left,grow,v=self.left:delete_move("right","left",1) grow=-grow else return not isSubtree and AVL:new(),-1 end self.value=v self.balance=self.balance+grow elseif v<self.value and self.left then self.left,grow=self.left:delete(v,true) self.balance=self.balance-grow elseif v>self.value and self.right then self.right,grow=self.right:delete(v,true) self.balance=self.balance+grow else return self,0 end self,rotated=self:rebalance() return self, grow~=0 and (rotated or self.balance==0) and -1 or 0 end
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)) / a.length ); } var a = [350, 10], b = [90, 180, 270, 360], c = [10, 20, 30]; console.log(meanAngleDeg(a)); console.log(meanAngleDeg(b)); console.log(meanAngleDeg(c));
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) -> putStrLn $ t: ": " ++ show m) ms putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))
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.putAll(update) println("base: $base") println("update: $update") println("merged: $merged") }
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, 1, -1 do t=t*i/n s=s+t end return s end print(" N average analytical (error)") print("=== ========= ============ =========") for n = 1, 20 do local avg, ana = average(n, 1e6), analytical(n) local err = (avg-ana) / ana * 100 print(string.format("%3d %9.4f %12.4f (%6.3f%%)", n, avg, ana, err)) end
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)) } static void main(String[] args) { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0) test(-Math.sqrt(2.0) * Math.sqrt(2.0), -2.0) test(3.14159265358979323846, 3.14159265358979324) } }
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 = 1e-14 instance AlmostEq Float where eps = 1e-5
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, {, , , , }, , } }; main(){ FILE *passwd_text=fopen(, ); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT, passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen(, ); char passwd_buf[BUFSIZ]; passwd_t new_rec = {, , 1003, 1000, {, , , , }, , }; sprintf(passwd_buf, PASSWD_FMT, new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen(, ); while(!feof(passwd_text)) fscanf(passwd_text, , passwd_buf, ); if(strstr(passwd_buf, )) printf(, passwd_buf); }
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)); } return 0; }
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 += 2 if n%d == 0 { return false } d += 4 } return true } } func countPrimeFactors(n int) int { switch { case n == 1: return 0 case isPrime(n): return 1 default: count, f := 0, 2 for { if n%f == 0 { count++ n /= f if n == 1 { return count } if isPrime(n) { f = n } } else if f >= 3 { f += 2 } else { f = 3 } } return count } } func main() { const max = 120 fmt.Println("The attractive numbers up to and including", max, "are:") count := 0 for i := 1; i <= max; i++ { n := countPrimeFactors(i) if isPrime(n) { fmt.Printf("%4d", i) count++ if count % 20 == 0 { fmt.Println() } } } fmt.Println() }
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, epsilon)); } public static void main(String[] args) { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0); test(-Math.sqrt(2.0) * Math.sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); } }
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 .. $MAX) { my $empiric = ( sum map { find_loop($n) } 1..$TRIALS ) / $TRIALS; my $theoric = sum map { (reduce { $a*$b } $_**2, ($n-$_+1)..$n ) / $n ** ($_+1) } 1..$n; printf "%3d %9.4f %12.4f (%5.2f%%)\n", $n, $empiric, $theoric, 100 * ($empiric - $theoric) / $theoric; }
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 d += 4 } return true } static int countPrimeFactors(int n) { if (n == 1) return 0 if (isPrime(n)) return 1 int count = 0, f = 2 while (true) { if (n % f == 0) { count++ n /= f if (n == 1) return count if (isPrime(n)) f = n } else if (f >= 3) f += 2 else f = 3 } } static void main(String[] args) { final int max = 120 printf("The attractive numbers up to and including%d are:\n", max) int count = 0 for (int i = 1; i <= max; ++i) { int n = countPrimeFactors(i) if (isPrime(n)) { printf("%4d", i) if (++count % 20 == 0) println() } } println() } }
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, 10})) print(meanAngle({90, 180, 270, 360})) print(meanAngle({10, 20, 30}))
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; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); printf " a:%14s%10d\n", $a, from_bt( $a ); printf " b:%14s%10d\n", $b, from_bt( $b ); printf " c:%14s%10d\n", $c, from_bt( $c ); printf "a*(b-c):%14s%10d\n", $d, from_bt( $d );
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.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(sqrt(2.0) * sqrt(2.0), 2.0) test(-sqrt(2.0) * sqrt(2.0), -2.0) test(3.14159265358979323846, 3.14159265358979324) }
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 in (0..<n) && to in (0..<n) def cappedAmt = [cells[from], amount].min() cells[from] -= cappedAmt cells[to] += cappedAmt } synchronized String toString() { cells.toString() } } def random = new Random() def buckets = new Buckets(5) def makeCloser = { i, j -> synchronized(buckets) { def targetDiff = (buckets[i]-buckets[j]).intdiv(2) if (targetDiff < 0) { buckets.transfer(j, i, -targetDiff) } else { buckets.transfer(i, j, targetDiff) } } } def randomize = { i, j -> synchronized(buckets) { def targetLimit = buckets[i] + buckets[j] def targetI = random.nextInt(targetLimit + 1) if (targetI < buckets[i]) { buckets.transfer(i, j, buckets[i] - targetI) } else { buckets.transfer(j, i, targetI - buckets[i]) } } } Thread.start { def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { def i = random.nextInt(buckets.n) def j = random.nextInt(buckets.n) makeCloser(i, j) } } Thread.start { def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { def i = random.nextInt(buckets.n) def j = random.nextInt(buckets.n) randomize(i, j) } } def start = System.currentTimeMillis() while (start + 10000 > System.currentTimeMillis()) { synchronized(buckets) { def sum = buckets.cells.sum() println "${new Date()}: checksum: ${sum} buckets: ${buckets}" } Thread.sleep(500) }
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; foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + + kvp.Value); } foreach (string key in assocArray.Keys) { Console.WriteLine(key); } foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }
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 := range b { tmp += bj * in[i-j] } a := f.a[1:] if i < len(a) { a = a[:i] } for j, aj := range a { tmp -= aj * out[i-j-1] } out[i] = tmp * s } return out }
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{$_} = [$base{$_}] for keys %base; push @{$merge{$_}}, $more{$_} for keys %more; printf "%-7s%s\n", $_, join ', ', @{$merge{$_}} for sort keys %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| printf , num, ma3.call(num), ma5.call(num) end
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.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(math.sqrt(2.0) * math.sqrt(2.0), 2.0) test(-math.sqrt(2.0) * math.sqrt(2.0), -2.0) test(3.14159265358979323846, 3.14159265358979324) end main()
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) type Index = Int type Value = Integer data Buckets = Buckets Index (MVar (IntMap Value)) makeBuckets :: Int -> IO Buckets size :: Buckets -> Index currentValue :: Buckets -> Index -> IO Value currentValues :: Buckets -> IO (IntMap Value) transfer :: Buckets -> Index -> Index -> Value -> IO () makeBuckets n = do v <- newMVar (fromList [(i, 100) | i <- [1..n]]) return (Buckets n v) size (Buckets n _) = n currentValue (Buckets _ v) i = fmap (! i) (readMVar v) currentValues (Buckets _ v) = readMVar v transfer b@(Buckets n v) i j amt | amt < 0 = transfer b j i (-amt) | otherwise = do modifyMVar_ v $ \map -> let amt' = min amt (map! i) in return $ adjust (subtract amt') i $ adjust (+ amt') j $ map roughen, smooth, display:: Buckets -> IO () pick buckets = randomRIO (1, size buckets) roughen buckets = forever loop where loop = do i <- pick buckets j <- pick buckets iv <- currentValue buckets i transfer buckets i j (iv `div` 3) smooth buckets = forever loop where loop = do i <- pick buckets j <- pick buckets iv <- currentValue buckets i jv <- currentValue buckets j transfer buckets i j ((iv - jv) `div` 4) display buckets = forever loop where loop = do threadDelay 1000000 bmap <- currentValues buckets putStrLn (report $ map snd $ toAscList bmap) report list = "\nTotal: " ++ show (sum list) ++ "\n" ++ bars where bars = concatMap row $ map (*40) $ reverse [1..5] row lim = printf "%3d " lim ++ [if x >= lim then '*' else ' ' | x <- list] ++ "\n" main = do buckets <- makeBuckets 100 forkIO (roughen buckets) forkIO (smooth buckets) display buckets
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 tmp += b[j] * signal[i - j] } for (int j = 1; j < a.length; ++j) { if (i - j < 0) continue tmp -= a[j] * result[i - j] } tmp /= a[0] result[i] = tmp } return result } static void main(String[] args) { double[] a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] as double[] double[] b = [0.16666667, 0.5, 0.5, 0.16666667] as double[] double[] signal = [ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ] as double[] double[] result = filter(a, b, signal) for (int i = 0; i < result.length; ++i) { printf("% .8f", result[i]) print((i + 1) % 5 != 0 ? ", ": "\n") } } }
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 / numbers.size(); } public static double geometricMean(List<Double> numbers) { if (numbers.isEmpty()) return Double.NaN; double mean = 1.0; for (Double number : numbers) { mean *= number; } return Math.pow(mean, 1.0 / numbers.size()); } public static double harmonicMean(List<Double> numbers) { if (numbers.isEmpty() || numbers.contains(0.0)) return Double.NaN; double mean = 0.0; for (Double number : numbers) { mean += (1.0 / number); } return numbers.size() / mean; } public static void main(String[] args) { Double[] array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; List<Double> list = Arrays.asList(array); double arithmetic = arithmeticMean(list); double geometric = geometricMean(list); double harmonic = harmonicMean(list); System.out.format("A =%f G =%f H =%f%n", arithmetic, geometric, harmonic); System.out.format("A >= G is%b, G >= H is%b%n", (arithmetic >= geometric), (geometric >= harmonic)); } }
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: zipWith (-) (conv b s) (conv a res)
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.numbers.push(number); if self.numbers.len() > self.period { self.numbers.remove(0); } if self.numbers.is_empty() { return 0f64; }else { let sum = self.numbers.iter().fold(0, |acc, x| acc+x); return sum as f64 / self.numbers.len() as f64; } } } fn main() { for period in [3, 5].iter() { println!("Moving average with period {}", period); let mut sma = SimpleMovingAverage::new(*period); for i in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1].iter() { println!("Number: {} | Average: {}", i, sma.add_number(*i)); } } }
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 false; d += 4; } return true; } static int count_prime_factors(int n) { if (n == 1) return 0; if (is_prime(n)) return 1; int count = 0, f = 2; while (true) { if (n % f == 0) { count++; n /= f; if (n == 1) return count; if (is_prime(n)) f = n; } else if (f >= 3) f += 2; else f = 3; } } public static void main(String[] args) { final int max = 120; System.out.printf("The attractive numbers up to and including%d are:\n", max); for (int i = 1, count = 0; i <= max; ++i) { int n = count_prime_factors(i); if (is_prime(n)) { System.out.printf("%4d", i); if (++count % 20 == 0) System.out.println(); } } System.out.println(); } }
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(ABC): @abstractmethod def compare(self,t): pass class node(comparer): def __init__(self): self.parent = None self.left = self self.right = self self.balance = state.header def compare(self,t): if self.key < t: return -1 elif t < self.key: return 1 else: return 0 def is_header(self): return self.balance == state.header def length(self): if self != None: if self.left != None: left = self.left.length() else: left = 0 if self.right != None: right = self.right.length() else: right = 0 return left + right + 1 else: return 0 def rotate_left(self): _parent = self.parent x = self.right self.parent = x x.parent = _parent if x.left is not None: x.left.parent = self self.right = x.left x.left = self return x def rotate_right(self): _parent = self.parent x = self.left self.parent = x x.parent = _parent; if x.right is not None: x.right.parent = self self.left = x.right x.right = self return x def balance_left(self): _left = self.left if _left is None: return self; if _left.balance == state.left_high: self.balance = state.balanced _left.balance = state.balanced self = self.rotate_right() elif _left.balance == state.right_high: subright = _left.right if subright.balance == state.balanced: self.balance = state.balanced _left.balance = state.balanced elif subright.balance == state.right_high: self.balance = state.balanced _left.balance = state.left_high elif subright.balance == left_high: root.balance = state.right_high _left.balance = state.balanced subright.balance = state.balanced _left = _left.rotate_left() self.left = _left self = self.rotate_right() elif _left.balance == state.balanced: self.balance = state.left_high _left.balance = state.right_high self = self.rotate_right() return self; def balance_right(self): _right = self.right if _right is None: return self; if _right.balance == state.right_high: self.balance = state.balanced _right.balance = state.balanced self = self.rotate_left() elif _right.balance == state.left_high: subleft = _right.left; if subleft.balance == state.balanced: self.balance = state.balanced _right.balance = state.balanced elif subleft.balance == state.left_high: self.balance = state.balanced _right.balance = state.right_high elif subleft.balance == state.right_high: self.balance = state.left_high _right.balance = state.balanced subleft.balance = state.balanced _right = _right.rotate_right() self.right = _right self = self.rotate_left() elif _right.balance == state.balanced: self.balance = state.right_high _right.balance = state.left_high self = self.rotate_left() return self def balance_tree(self, direct): taller = True while taller: _parent = self.parent; if _parent.left == self: next_from = direction.from_left else: next_from = direction.from_right; if direct == direction.from_left: if self.balance == state.left_high: if _parent.is_header(): _parent.parent = _parent.parent.balance_left() elif _parent.left == self: _parent.left = _parent.left.balance_left() else: _parent.right = _parent.right.balance_left() taller = False elif self.balance == state.balanced: self.balance = state.left_high taller = True elif self.balance == state.right_high: self.balance = state.balanced taller = False else: if self.balance == state.left_high: self.balance = state.balanced taller = False elif self.balance == state.balanced: self.balance = state.right_high taller = True elif self.balance == state.right_high: if _parent.is_header(): _parent.parent = _parent.parent.balance_right() elif _parent.left == self: _parent.left = _parent.left.balance_right() else: _parent.right = _parent.right.balance_right() taller = False if taller: if _parent.is_header(): taller = False else: self = _parent direct = next_from def balance_tree_remove(self, _from): if self.is_header(): return; shorter = True; while shorter: _parent = self.parent; if _parent.left == self: next_from = direction.from_left else: next_from = direction.from_right if _from == direction.from_left: if self.balance == state.left_high: shorter = True elif self.balance == state.balanced: self.balance = state.right_high; shorter = False elif self.balance == state.right_high: if self.right is not None: if self.right.balance == state.balanced: shorter = False else: shorter = True else: shorter = False; if _parent.is_header(): _parent.parent = _parent.parent.balance_right() elif _parent.left == self: _parent.left = _parent.left.balance_right(); else: _parent.right = _parent.right.balance_right() else: if self.balance == state.right_high: self.balance = state.balanced shorter = True elif self.balance == state.balanced: self.balance = state.left_high shorter = False elif self.balance == state.left_high: if self.left is not None: if self.left.balance == state.balanced: shorter = False else: shorter = True else: short = False; if _parent.is_header(): _parent.parent = _parent.parent.balance_left(); elif _parent.left == self: _parent.left = _parent.left.balance_left(); else: _parent.right = _parent.right.balance_left(); if shorter: if _parent.is_header(): shorter = False else: _from = next_from self = _parent def previous(self): if self.is_header(): return self.right if self.left is not None: y = self.left while y.right is not None: y = y.right return y else: y = self.parent; if y.is_header(): return y x = self while x == y.left: x = y y = y.parent return y def next(self): if self.is_header(): return self.left if self.right is not None: y = self.right while y.left is not None: y = y.left return y; else: y = self.parent if y.is_header(): return y x = self; while x == y.right: x = y y = y.parent; return y def swap_nodes(a, b): if b == a.left: if b.left is not None: b.left.parent = a if b.right is not None: b.right.parent = a if a.right is not None: a.right.parent = b if not a.parent.is_header(): if a.parent.left == a: a.parent.left = b else: a.parent.right = b; else: a.parent.parent = b b.parent = a.parent a.parent = b a.left = b.left b.left = a temp = a.right a.right = b.right b.right = temp elif b == a.right: if b.right is not None: b.right.parent = a if b.left is not None: b.left.parent = a if a.left is not None: a.left.parent = b if not a.parent.is_header(): if a.parent.left == a: a.parent.left = b else: a.parent.right = b else: a.parent.parent = b b.parent = a.parent a.parent = b a.right = b.right b.right = a temp = a.left a.left = b.left b.left = temp elif a == b.left: if a.left is not None: a.left.parent = b if a.right is not None: a.right.parent = b if b.right is not None: b.right.parent = a if not parent.is_header(): if b.parent.left == b: b.parent.left = a else: b.parent.right = a else: b.parent.parent = a a.parent = b.parent b.parent = a b.left = a.left a.left = b temp = a.right a.right = b.right b.right = temp elif a == b.right: if a.right is not None: a.right.parent = b if a.left is not None: a.left.parent = b if b.left is not None: b.left.parent = a if not b.parent.is_header(): if b.parent.left == b: b.parent.left = a else: b.parent.right = a else: b.parent.parent = a a.parent = b.parent b.parent = a b.right = a.right a.right = b temp = a.left a.left = b.left b.left = temp else: if a.parent == b.parent: temp = a.parent.left a.parent.left = a.parent.right a.parent.right = temp else: if not a.parent.is_header(): if a.parent.left == a: a.parent.left = b else: a.parent.right = b else: a.parent.parent = b if not b.parent.is_header(): if b.parent.left == b: b.parent.left = a else: b.parent.right = a else: b.parent.parent = a if b.left is not None: b.left.parent = a if b.right is not None: b.right.parent = a if a.left is not None: a.left.parent = b if a.right is not None: a.right.parent = b temp1 = a.left a.left = b.left b.left = temp1 temp2 = a.right a.right = b.right b.right = temp2 temp3 = a.parent a.parent = b.parent b.parent = temp3 balance = a.balance a.balance = b.balance b.balance = balance class parent_node(node): def __init__(self, parent): self.parent = parent self.left = None self.right = None self.balance = state.balanced class set_node(node): def __init__(self, parent, key): self.parent = parent self.left = None self.right = None self.balance = state.balanced self.key = key class ordered_set: def __init__(self): self.header = node() def __iter__(self): self.node = self.header return self def __next__(self): self.node = self.node.next() if self.node.is_header(): raise StopIteration return self.node.key def __delitem__(self, key): self.remove(key) def __lt__(self, other): first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header while (first1 != last1) and (first2 != last2): l = first1.key < first2.key if not l: first1 = first1.next(); first2 = first2.next(); else: return True; a = self.__len__() b = other.__len__() return a < b def __hash__(self): h = 0 for i in self: h = h + i.__hash__() return h def __eq__(self, other): if self < other: return False if other < self: return False return True def __ne__(self, other): if self < other: return True if other < self: return True return False def __len__(self): return self.header.parent.length() def __getitem__(self, key): return self.contains(key) def __str__(self): l = self.header.right s = i = self.header.left h = self.header while i != h: s = s + i.key.__str__() if i != l: s = s + i = i.next() s = s + return s def __or__(self, other): r = ordered_set() first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header while first1 != last1 and first2 != last2: les = first1.key < first2.key graater = first2.key < first1.key if les: r.add(first1.key) first1 = first1.next() elif graater: r.add(first2.key) first2 = first2.next() else: r.add(first1.key) first1 = first1.next() first2 = first2.next() while first1 != last1: r.add(first1.key) first1 = first1.next() while first2 != last2: r.add(first2.key) first2 = first2.next() return r def __and__(self, other): r = ordered_set() first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header while first1 != last1 and first2 != last2: les = first1.key < first2.key graater = first2.key < first1.key if les: first1 = first1.next() elif graater: first2 = first2.next() else: r.add(first1.key) first1 = first1.next() first2 = first2.next() return r def __xor__(self, other): r = ordered_set() first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header while first1 != last1 and first2 != last2: les = first1.key < first2.key graater = first2.key < first1.key if les: r.add(first1.key) first1 = first1.next() elif graater: r.add(first2.key) first2 = first2.next() else: first1 = first1.next() first2 = first2.next() while first1 != last1: r.add(first1.key) first1 = first1.next() while first2 != last2: r.add(first2.key) first2 = first2.next() return r def __sub__(self, other): r = ordered_set() first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header while first1 != last1 and first2 != last2: les = first1.key < first2.key graater = first2.key < first1.key if les: r.add(first1.key) first1 = first1.next() elif graater: r.add(first2.key) first2 = first2.next() else: first1 = first1.next() first2 = first2.next() while first1 != last1: r.add(first1.key) first1 = first1.next() return r def __lshift__(self, data): self.add(data) return self def __rshift__(self, data): self.remove(data) return self def is_subset(self, other): first1 = self.header.left last1 = self.header first2 = other.header.left last2 = other.header is_subet = True while first1 != last1 and first2 != last2: if first1.key < first2.key: is_subset = False break elif first2.key < first1.key: first2 = first2.next() else: first1 = first1.next() first2 = first2.next() if is_subet: if first1 != last1: is_subet = False return is_subet def is_superset(self,other): return other.is_subset(self) def add(self, data): if self.header.parent is None: self.header.parent = set_node(self.header,data) self.header.left = self.header.parent self.header.right = self.header.parent else: root = self.header.parent while True: c = root.compare(data) if c >= 0: if root.left is not None: root = root.left else: new_node = set_node(root,data) root.left = new_node if self.header.left == root: self.header.left = new_node root.balance_tree(direction.from_left) return else: if root.right is not None: root = root.right else: new_node = set_node(root, data) root.right = new_node if self.header.right == root: self.header.right = new_node root.balance_tree(direction.from_right) return def remove(self,data): root = self.header.parent; while True: if root is None: raise entry_not_found() c = root.compare(data) if c < 0: root = root.left; elif c > 0: root = root.right; else: if root.left is not None: if root.right is not None: replace = root.left while replace.right is not None: replace = replace.right root.swap_nodes(replace) _parent = root.parent if _parent.left == root: _from = direction.from_left else: _from = direction.from_right if self.header.left == root: n = root.next(); if n.is_header(): self.header.left = self.header self.header.right = self.header else: self.header.left = n elif self.header.right == root: p = root.previous(); if p.is_header(): self.header.left = self.header self.header.right = self.header else: self.header.right = p if root.left is None: if _parent == self.header: self.header.parent = root.right elif _parent.left == root: _parent.left = root.right else: _parent.right = root.right if root.right is not None: root.right.parent = _parent else: if _parent == self.header: self.header.parent = root.left elif _parent.left == root: _parent.left = root.left else: _parent.right = root.left if root.left is not None: root.left.parent = _parent; _parent.balance_tree_remove(_from) return def contains(self,data): root = self.header.parent; while True: if root == None: return False c = root.compare(data); if c > 0: root = root.left; elif c < 0: root = root.right; else: return True def find(self,data): root = self.header.parent; while True: if root == None: raise entry_not_found() c = root.compare(data); if c > 0: root = root.left; elif c < 0: root = root.right; else: return root.key; class key_value(comparer): def __init__(self, key, value): self.key = key self.value = value def compare(self,kv): if self.key < kv.key: return -1 elif kv.key < self.key: return 1 else: return 0 def __lt__(self, other): return self.key < other.key def __str__(self): return '(' + self.key.__str__() + ',' + self.value.__str__() + ')' def __eq__(self, other): return self.key == other.key def __hash__(self): return hash(self.key) class dictionary: def __init__(self): self.set = ordered_set() return None def __lt__(self, other): if self.keys() < other.keys(): return true if other.keys() < self.keys(): return false first1 = self.set.header.left last1 = self.set.header first2 = other.set.header.left last2 = other.set.header while (first1 != last1) and (first2 != last2): l = first1.key.value < first2.key.value if not l: first1 = first1.next(); first2 = first2.next(); else: return True; a = self.__len__() b = other.__len__() return a < b def add(self, key, value): try: self.set.remove(key_value(key,None)) except entry_not_found: pass self.set.add(key_value(key,value)) return def remove(self, key): self.set.remove(key_value(key,None)) return def clear(self): self.set.header = node() def sort(self): sort_bag = bag() for e in self: sort_bag.add(e.value) keys_set = self.keys() self.clear() i = sort_bag.__iter__() i = sort_bag.__next__() try: for e in keys_set: self.add(e,i) i = sort_bag.__next__() except: return def keys(self): keys_set = ordered_set() for e in self: keys_set.add(e.key) return keys_set def __len__(self): return self.set.header.parent.length() def __str__(self): l = self.set.header.right; s = i = self.set.header.left; h = self.set.header; while i != h: s = s + s = s + i.key.key.__str__() s = s + s = s + i.key.value.__str__() s = s + if i != l: s = s + i = i.next() s = s + return s; def __iter__(self): self.set.node = self.set.header return self def __next__(self): self.set.node = self.set.node.next() if self.set.node.is_header(): raise StopIteration return key_value(self.set.node.key.key,self.set.node.key.value) def __getitem__(self, key): kv = self.set.find(key_value(key,None)) return kv.value def __setitem__(self, key, value): self.add(key,value) return def __delitem__(self, key): self.set.remove(key_value(key,None)) class array: def __init__(self): self.dictionary = dictionary() return None def __len__(self): return self.dictionary.__len__() def push(self, value): k = self.dictionary.set.header.right if k == self.dictionary.set.header: self.dictionary.add(0,value) else: self.dictionary.add(k.key.key+1,value) return def pop(self): if self.dictionary.set.header.parent != None: data = self.dictionary.set.header.right.key.value self.remove(self.dictionary.set.header.right.key.key) return data def add(self, key, value): try: self.dictionary.remove(key) except entry_not_found: pass self.dictionary.add(key,value) return def remove(self, key): self.dictionary.remove(key) return def sort(self): self.dictionary.sort() def clear(self): self.dictionary.header = node(); def __iter__(self): self.dictionary.node = self.dictionary.set.header return self def __next__(self): self.dictionary.node = self.dictionary.node.next() if self.dictionary.node.is_header(): raise StopIteration return self.dictionary.node.key.value def __getitem__(self, key): kv = self.dictionary.set.find(key_value(key,None)) return kv.value def __setitem__(self, key, value): self.add(key,value) return def __delitem__(self, key): self.dictionary.remove(key) def __lshift__(self, data): self.push(data) return self def __lt__(self, other): return self.dictionary < other.dictionary def __str__(self): l = self.dictionary.set.header.right; s = i = self.dictionary.set.header.left; h = self.dictionary.set.header; while i != h: s = s + i.key.value.__str__() if i != l: s = s + i = i.next() s = s + return s; class bag: def __init__(self): self.header = node() def __iter__(self): self.node = self.header return self def __delitem__(self, key): self.remove(key) def __next__(self): self.node = self.node.next() if self.node.is_header(): raise StopIteration return self.node.key def __str__(self): l = self.header.right; s = i = self.header.left; h = self.header; while i != h: s = s + i.key.__str__() if i != l: s = s + i = i.next() s = s + return s; def __len__(self): return self.header.parent.length() def __lshift__(self, data): self.add(data) return self def add(self, data): if self.header.parent is None: self.header.parent = set_node(self.header,data) self.header.left = self.header.parent self.header.right = self.header.parent else: root = self.header.parent while True: c = root.compare(data) if c >= 0: if root.left is not None: root = root.left else: new_node = set_node(root,data) root.left = new_node if self.header.left == root: self.header.left = new_node root.balance_tree(direction.from_left) return else: if root.right is not None: root = root.right else: new_node = set_node(root, data) root.right = new_node if self.header.right == root: self.header.right = new_node root.balance_tree(direction.from_right) return def remove_first(self,data): root = self.header.parent; while True: if root is None: return False; c = root.compare(data); if c > 0: root = root.left; elif c < 0: root = root.right; else: if root.left is not None: if root.right is not None: replace = root.left; while replace.right is not None: replace = replace.right; root.swap_nodes(replace); _parent = root.parent if _parent.left == root: _from = direction.from_left else: _from = direction.from_right if self.header.left == root: n = root.next(); if n.is_header(): self.header.left = self.header self.header.right = self.header else: self.header.left = n; elif self.header.right == root: p = root.previous(); if p.is_header(): self.header.left = self.header self.header.right = self.header else: self.header.right = p if root.left is None: if _parent == self.header: self.header.parent = root.right elif _parent.left == root: _parent.left = root.right else: _parent.right = root.right if root.right is not None: root.right.parent = _parent else: if _parent == self.header: self.header.parent = root.left elif _parent.left == root: _parent.left = root.left else: _parent.right = root.left if root.left is not None: root.left.parent = _parent; _parent.balance_tree_remove(_from) return True; def remove(self,data): success = self.remove_first(data) while success: success = self.remove_first(data) def remove_node(self, root): if root.left != None and root.right != None: replace = root.left while replace.right != None: replace = replace.right root.swap_nodes(replace) parent = root.parent; if parent.left == root: next_from = direction.from_left else: next_from = direction.from_right if self.header.left == root: n = root.next() if n.is_header(): self.header.left = self.header; self.header.right = self.header else: self.header.left = n elif self.header.right == root: p = root.previous() if p.is_header(): root.header.left = root.header root.header.right = header else: self.header.right = p if root.left == None: if parent == self.header: self.header.parent = root.right elif parent.left == root: parent.left = root.right else: parent.right = root.right if root.right != None: root.right.parent = parent else: if parent == self.header: self.header.parent = root.left elif parent.left == root: parent.left = root.left else: parent.right = root.left if root.left != None: root.left.parent = parent; parent.balance_tree_remove(next_from) def remove_at(self, data, ophset): p = self.search(data); if p == None: return else: lower = p after = after(data) s = 0 while True: if ophset == s: remove_node(lower); return; lower = lower.next_node() if after == lower: break s = s+1 return def search(self, key): s = before(key) s.next() if s.is_header(): return None c = s.compare(s.key) if c != 0: return None return s def before(self, data): y = self.header; x = self.header.parent; while x != None: if x.compare(data) >= 0: x = x.left; else: y = x; x = x.right; return y def after(self, data): y = self.header; x = self.header.parent; while x != None: if x.compare(data) > 0: y = x x = x.left else: x = x.right return y; def find(self,data): root = self.header.parent; results = array() while True: if root is None: break; p = self.before(data) p = p.next() if not p.is_header(): i = p l = self.after(data) while i != l: results.push(i.key) i = i.next() return results else: break; return results class bag_dictionary: def __init__(self): self.bag = bag() return None def add(self, key, value): self.bag.add(key_value(key,value)) return def remove(self, key): self.bag.remove(key_value(key,None)) return def remove_at(self, key, index): self.bag.remove_at(key_value(key,None), index) return def clear(self): self.bag.header = node() def __len__(self): return self.bag.header.parent.length() def __str__(self): l = self.bag.header.right; s = i = self.bag.header.left; h = self.bag.header; while i != h: s = s + s = s + i.key.key.__str__() s = s + s = s + i.key.value.__str__() s = s + if i != l: s = s + i = i.next() s = s + return s; def __iter__(self): self.bag.node = self.bag.header return self def __next__(self): self.bag.node = self.bag.node.next() if self.bag.node.is_header(): raise StopIteration return key_value(self.bag.node.key.key,self.bag.node.key.value) def __getitem__(self, key): kv_array = self.bag.find(key_value(key,None)) return kv_array def __setitem__(self, key, value): self.add(key,value) return def __delitem__(self, key): self.bag.remove(key_value(key,None)) class unordered_set: def __init__(self): self.bag_dictionary = bag_dictionary() def __len__(self): return self.bag_dictionary.__len__() def __hash__(self): h = 0 for i in self: h = h + i.__hash__() return h def __eq__(self, other): for t in self: if not other.contains(t): return False for u in other: if self.contains(u): return False return true; def __ne__(self, other): return not self == other def __or__(self, other): r = unordered_set() for t in self: r.add(t); for u in other: if not self.contains(u): r.add(u); return r def __and__(self, other): r = unordered_set() for t in self: if other.contains(t): r.add(t) for u in other: if self.contains(u) and not r.contains(u): r.add(u); return r def __xor__(self, other): r = unordered_set() for t in self: if not other.contains(t): r.add(t) for u in other: if not self.contains(u) and not r.contains(u): r.add(u) return r def __sub__(self, other): r = ordered_set() for t in self: if not other.contains(t): r.add(t); return r def __lshift__(self, data): self.add(data) return self def __rshift__(self, data): self.remove(data) return self def __getitem__(self, key): return self.contains(key) def is_subset(self, other): is_subet = True for t in self: if not other.contains(t): subset = False break return is_subet def is_superset(self,other): return other.is_subset(self) def add(self, value): if not self.contains(value): self.bag_dictionary.add(hash(value),value) else: raise entry_already_exists() def contains(self, data): if self.bag_dictionary.bag.header.parent == None: return False; else: index = hash(data); _search = self.bag_dictionary.bag.header.parent; search_index = _search.key.key; if index < search_index: _search = _search.left elif index > search_index: _search = _search.right if _search == None: return False while _search != None: search_index = _search.key.key; if index < search_index: _search = _search.left elif index > search_index: _search = _search.right else: break if _search == None: return False return self.contains_node(data, _search) def contains_node(self,data,_node): previous = _node.previous() save = _node while not previous.is_header() and previous.key.key == _node.key.key: save = previous; previous = previous.previous() c = _node.key.value _node = save if c == data: return True next = _node.next() while not next.is_header() and next.key.key == _node.key.key: _node = next c = _node.key.value if c == data: return True; next = _node.next() return False; def find(self,data,_node): previous = _node.previous() save = _node while not previous.is_header() and previous.key.key == _node.key.key: save = previous; previous = previous.previous(); _node = save; c = _node.key.value if c == data: return _node next = _node.next() while not next.is_header() and next.key.key == _node.key.key: _node = next c = _node.data.value if c == data: return _node next = _node.next() return None def search(self, data): if self.bag_dictionary.bag.header.parent == None: return None else: index = hash(data) _search = self.bag_dictionary.bag.header.parent c = _search.key.key if index < c: _search = _search.left; elif index > c: _search = _search.right; while _search != None: if index != c: break c = _search.key.key if index < c: _search = _search.left; elif index > c: _search = _search.right; else: break if _search == None: return None return self.find(data, _search) def remove(self,data): found = self.search(data); if found != None: self.bag_dictionary.bag.remove_node(found); else: raise entry_not_found() def clear(self): self.bag_dictionary.bag.header = node() def __str__(self): l = self.bag_dictionary.bag.header.right; s = i = self.bag_dictionary.bag.header.left; h = self.bag_dictionary.bag.header; while i != h: s = s + i.key.value.__str__() if i != l: s = s + i = i.next() s = s + return s; def __iter__(self): self.bag_dictionary.bag.node = self.bag_dictionary.bag.header return self def __next__(self): self.bag_dictionary.bag.node = self.bag_dictionary.bag.node.next() if self.bag_dictionary.bag.node.is_header(): raise StopIteration return self.bag_dictionary.bag.node.key.value class map: def __init__(self): self.set = unordered_set() return None def __len__(self): return self.set.__len__() def add(self, key, value): try: self.set.remove(key_value(key,None)) except entry_not_found: pass self.set.add(key_value(key,value)) return def remove(self, key): self.set.remove(key_value(key,None)) return def clear(self): self.set.clear() def __str__(self): l = self.set.bag_dictionary.bag.header.right; s = i = self.set.bag_dictionary.bag.header.left; h = self.set.bag_dictionary.bag.header; while i != h: s = s + s = s + i.key.value.key.__str__() s = s + s = s + i.key.value.value.__str__() s = s + if i != l: s = s + i = i.next() s = s + return s; def __iter__(self): self.set.node = self.set.bag_dictionary.bag.header return self def __next__(self): self.set.node = self.set.node.next() if self.set.node.is_header(): raise StopIteration return key_value(self.set.node.key.key,self.set.node.key.value) def __getitem__(self, key): kv = self.set.find(key_value(key,None)) return kv.value def __setitem__(self, key, value): self.add(key,value) return def __delitem__(self, key): self.remove(key)
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 int getBucket(int index) { synchronized (data) { return data[index]; } } public int transfer(int srcIndex, int dstIndex, int amount) { if (amount < 0) throw new IllegalArgumentException("negative amount: " + amount); if (amount == 0) return 0; synchronized (data) { if (data[srcIndex] - amount < 0) amount = data[srcIndex]; if (data[dstIndex] + amount < 0) amount = Integer.MAX_VALUE - data[dstIndex]; if (amount < 0) throw new IllegalStateException(); data[srcIndex] -= amount; data[dstIndex] += amount; return amount; } } public int[] getBuckets() { synchronized (data) { return data.clone(); } } } private static long getTotal(int[] values) { long total = 0; for (int value : values) { total += value; } return total; } public static void main(String[] args) { ThreadLocalRandom rnd = ThreadLocalRandom.current(); int[] values = new int[NUM_BUCKETS]; for (int i = 0; i < values.length; i++) values[i] = rnd.nextInt() & Integer.MAX_VALUE; System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values)); Buckets buckets = new Buckets(values); new Thread(() -> equalize(buckets), "equalizer").start(); new Thread(() -> transferRandomAmount(buckets), "transferrer").start(); new Thread(() -> print(buckets), "printer").start(); } private static void transferRandomAmount(Buckets buckets) { ThreadLocalRandom rnd = ThreadLocalRandom.current(); while (true) { int srcIndex = rnd.nextInt(NUM_BUCKETS); int dstIndex = rnd.nextInt(NUM_BUCKETS); int amount = rnd.nextInt() & Integer.MAX_VALUE; buckets.transfer(srcIndex, dstIndex, amount); } } private static void equalize(Buckets buckets) { ThreadLocalRandom rnd = ThreadLocalRandom.current(); while (true) { int srcIndex = rnd.nextInt(NUM_BUCKETS); int dstIndex = rnd.nextInt(NUM_BUCKETS); int amount = (buckets.getBucket(srcIndex) - buckets.getBucket(dstIndex)) / 2; if (amount >= 0) buckets.transfer(srcIndex, dstIndex, amount); } } private static void print(Buckets buckets) { while (true) { long nextPrintTime = System.currentTimeMillis() + 3000; long now; while ((now = System.currentTimeMillis()) < nextPrintTime) { try { Thread.sleep(nextPrintTime - now); } catch (InterruptedException e) { return; } } int[] bucketValues = buckets.getBuckets(); System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues)); } } }
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) continue; tmp += b[j] * signal[i - j]; } for (int j = 1; j < a.length; ++j) { if (i - j < 0) continue; tmp -= a[j] * result[i - j]; } tmp /= a[0]; result[i] = tmp; } return result; } public static void main(String[] args) { double[] a = new double[]{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}; double[] b = new double[]{0.16666667, 0.5, 0.5, 0.16666667}; double[] signal = new double[]{ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 }; double[] result = filter(a, b, signal); for (int i = 0; i < result.length; ++i) { System.out.printf("% .8f", result[i]); System.out.print((i + 1) % 5 != 0 ? ", " : "\n"); } } }
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 (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print() for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print(% (n, avg, theory, diff))
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 { place <- v[[place]] steps <- steps + 1 if (visit[[place]]) break visit[[place]] <- TRUE } steps } cat(" N average analytical (error)\n") cat("=== ========= ============ ==========\n") for (num in 1:20) { average <- mean(replicate(1e6, knuth(num))) analytical <- expected(num) error <- abs(average/analytical-1)*100 cat(sprintf("%3d%11.4f%14.4f (%4.4f%%)\n", num, round(average,4), round(analytical,4), round(error,2))) }
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 "+(queue.sum / queue.size) def clear = queue.clear }
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(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError() else: raise TypeError() @staticmethod def _int2ternary(n): if n == 0: return [] if (n% 3) == 0: return [0] + BalancedTernary._int2ternary(n if (n% 3) == 1: return [1] + BalancedTernary._int2ternary(n if (n% 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return return .join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary() print , a.to_int(), a b = BalancedTernary(-436) print , b.to_int(), b c = BalancedTernary() print , c.to_int(), c r = a * (b - c) print , r.to_int(), r main()
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); printf "%-5s%s %s\n", ($afmt eq $bfmt ? 'True' : 'False'), $afmt, $bfmt; } for ( [100000000000000.01, 100000000000000.011], [100.01, 100.011], [10000000000000.001 / 10000.0, 1000000000.0000001000], [0.001, 0.0010000001], [0.000000000000000000000101, 0.0], [sqrt(2) * sqrt(2), 2.0], [-sqrt(2) * sqrt(2), -2.0], [100000000000000003.0, 100000000000000004.0], [3.14159265358979323846, 3.14159265358979324] ) { my($a,$b) = @$_; is_close($a,$b); } print "\nTolerance may be adjusted.\n"; my $real_pi = 2 * atan2(1, 0); my $roman_pi = 22/7; is_close($real_pi,$roman_pi,$_) for <10 3>;
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 > maxDiv) { printf(, n); maxDiv = d; count++; } } printf(); return 0; }
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"); update.insert("year", "1974"); original.extend(&update); println!("{:#?}", original); }
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($x/60,60), fm($x,60); } sub fm { my($n,$b) = @_; $x = fmod($n,$b); $x += $b if $x < 0; } sub phase { arg($_[0]) } sub cis { cos($_[0]) + i*sin($_[0]) } sub mean_time { rad2tod phase sum map { cis tod2rad $_ } @_ } @times = ("23:00:17", "23:40:20", "00:12:45", "00:17:19"); print mean_time(@times) . " is the mean time of " . join(' ', @times) . "\n";
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](f: A => U): Unit = { val stack = mutable.Stack[AVLNode]() var current = root var done = false while (!done) { if (current != null) { stack.push(current) current = current.left } else if (stack.nonEmpty) { current = stack.pop() f.apply(current.key) current = current.right } else { done = true } } } def root: AVLNode = _root override def isEmpty: Boolean = root == null override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key def minNode(): AVLNode = { if (root == null) throw new UnsupportedOperationException("empty tree") var node = root while (node.left != null) node = node.left node } override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key def maxNode(): AVLNode = { if (root == null) throw new UnsupportedOperationException("empty tree") var node = root while (node.right != null) node = node.right node } def next(node: AVLNode): Option[AVLNode] = { var successor = node if (successor != null) { if (successor.right != null) { successor = successor.right while (successor != null && successor.left != null) { successor = successor.left } } else { successor = node.parent var n = node while (successor != null && successor.right == n) { n = successor successor = successor.parent } } } Option(successor) } def prev(node: AVLNode): Option[AVLNode] = { var predecessor = node if (predecessor != null) { if (predecessor.left != null) { predecessor = predecessor.left while (predecessor != null && predecessor.right != null) { predecessor = predecessor.right } } else { predecessor = node.parent var n = node while (predecessor != null && predecessor.left == n) { n = predecessor predecessor = predecessor.parent } } } Option(predecessor) } override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ??? override def +=(key: A): AVLTree.this.type = { insert(key) this } def insert(key: A): AVLNode = { if (root == null) { _root = new AVLNode(key) _size += 1 return root } var node = root var parent: AVLNode = null var cmp = 0 while (node != null) { parent = node cmp = ordering.compare(key, node.key) if (cmp == 0) return node
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 Determine whether two floating point numbers are close in value. Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves.
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](f: A => U): Unit = { val stack = mutable.Stack[AVLNode]() var current = root var done = false while (!done) { if (current != null) { stack.push(current) current = current.left } else if (stack.nonEmpty) { current = stack.pop() f.apply(current.key) current = current.right } else { done = true } } } def root: AVLNode = _root override def isEmpty: Boolean = root == null override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key def minNode(): AVLNode = { if (root == null) throw new UnsupportedOperationException("empty tree") var node = root while (node.left != null) node = node.left node } override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key def maxNode(): AVLNode = { if (root == null) throw new UnsupportedOperationException("empty tree") var node = root while (node.right != null) node = node.right node } def next(node: AVLNode): Option[AVLNode] = { var successor = node if (successor != null) { if (successor.right != null) { successor = successor.right while (successor != null && successor.left != null) { successor = successor.left } } else { successor = node.parent var n = node while (successor != null && successor.right == n) { n = successor successor = successor.parent } } } Option(successor) } def prev(node: AVLNode): Option[AVLNode] = { var predecessor = node if (predecessor != null) { if (predecessor.left != null) { predecessor = predecessor.left while (predecessor != null && predecessor.right != null) { predecessor = predecessor.right } } else { predecessor = node.parent var n = node while (predecessor != null && predecessor.left == n) { n = predecessor predecessor = predecessor.parent } } } Option(predecessor) } override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ??? override def +=(key: A): AVLTree.this.type = { insert(key) this } def insert(key: A): AVLNode = { if (root == null) { _root = new AVLNode(key) _size += 1 return root } var node = root var parent: AVLNode = null var cmp = 0 while (node != null) { parent = node cmp = ordering.compare(key, node.key) if (cmp == 0) return node
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; } print "The mean angle of [@$_] is: ", meandegrees(@$_), " degrees\n" for ([350,10], [90,180,270,360], [10,20,30]);
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) * sqrt(2), 2.0), c(-sqrt(2) * sqrt(2), -2.0), c(3.14159265358979323846, 3.14159265358979324)) results <- mapply(approxEq, tests[, 1], tests[, 2]) printableTests <- format(tests, scientific = FALSE) print(data.frame(x = printableTests[, 1], y = printableTests[, 2], Equal = results, row.names = paste0("Test ", 1:8, ": ")))
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_until_rep(n)} avg = sum_of_runs / runs.to_f analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)} puts % [n, avg, analytical, (avg/analytical - 1)*100] end
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 mut max_n: u32 = 20; let mut trials: u32 = 1000; match args.len() { 1 => {} 3 => { max_n = args[1].parse::<u32>().unwrap(); trials = args[2].parse::<u32>().unwrap(); } _ => { help(); process::exit(0); } } let mut rng = thread_rng(); println!(" N average analytical (error)"); println!("=== ========= ============ ========="); for n in 1..(max_n + 1) { let the_analytical = analytical(n); let the_empirical = empirical(n, trials, &mut rng); println!(" {:>2} {:3.4} {:3.4} ( {:>+1.2}%)", n, the_empirical, the_analytical, 100f64 * (the_empirical / the_analytical - 1f64)); } } fn factorial(n: u32) -> f64 { (1..n + 1).fold(1f64, |p, n| p * n as f64) } fn analytical(n: u32) -> f64 { let sum: f64 = (1..(n + 1)) .map(|i| factorial(n) / (n as f64).powi(i as i32) / factorial(n - i)) .fold(0f64, |a, v| a + v); sum } fn empirical(n: u32, trials: u32, rng: &mut ThreadRng) -> f64 { let sum: f64 = (0..trials) .map(|_t| { let mut item = 1u32; let mut seen = HashSet::new(); let range = Range::new(1u32, n + 1); for step in 0..n { if seen.contains(&item) { return step as f64; } seen.insert(item); item = range.ind_sample(rng); } n as f64 }) .fold(0f64, |a, v| a + v); sum / trials as f64 }
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_numeric($ang)) return $ang; $sec = 86400.0 * $ang / 360.0; $parts = array(floor($sec/3600),floor(($sec % 3600)/60),$sec % 60); $tim = sprintf('%02d:%02d:%02d',$parts[0],$parts[1],$parts[2]); return $tim; } function meanang($ang) { if (!is_array($ang)) return $ang; $sins = 0.0; $coss = 0.0; foreach($ang as $a) { $sins += sin(deg2rad($a)); $coss += cos(deg2rad($a)); } $avgsin = $sins / (0.0+count($ang)); $avgcos = $coss / (0.0+count($ang)); $avgang = rad2deg(atan2($avgsin,$avgcos)); while ($avgang < 0.0) $avgang += 360.0; return $avgang; } $bats = array('23:00:17','23:40:20','00:12:45','00:17:19'); $angs = array(); foreach ($bats as $t) $angs[] = time2ang($t); $ma = meanang($angs); $result = ang2time($ma); print ; ?>
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 } fun Double.toFixed(len: Int = 6) = round(this * 10.0.pow(len)) / 10.0.pow(len) fun main() { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val a = list.average()
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) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) }
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