code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
main(){
var fruits = {
'apples': 'red',
'oranges': 'orange',
'bananas': 'yellow',
'pears': 'green',
'plums': 'purple'
};
print('Key Value pairs:');
fruits.forEach( (fruits, color) => print( '$fruits are $color' ) );
print('\nKeys only:');
fruits.keys.forEach( ( key ) => print( key ) );
print('\nValues only:');
fruits.values.forEach( ( value ) => print( value ) );
} | 1,134Associative array/Iteration
| 18dart
| q0vxo |
import scala.util.Random
object AverageLoopLength extends App {
val factorial: LazyList[Double] = 1 #:: factorial.zip(LazyList.from(1)).map(n => n._2 * factorial(n._2 - 1))
val results = for (n <- 1 to 20;
avg = tested(n, 1000000);
theory = expected(n)
) yield (n, avg, theory, (avg / theory - 1) * 100)
def expected(n: Int): Double = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum
def tested(n: Int, times: Int): Double = (for (i <- 1 to times) yield trial(n)).sum / times
def trial(n: Int): Double = {
var count = 0
var x = 1
var bits = 0
while ((bits & x) == 0) {
count = count + 1
bits = bits | x
x = 1 << Random.nextInt(n)
}
count
}
println("n avg exp diff")
println("------------------------------------")
results foreach { n => {
println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%")
}
}
} | 1,123Average loop length
| 16scala
| q0pxw |
struct SimpleMovingAverage {
var period: Int
var numbers = [Double]()
mutating func addNumber(_ n: Double) -> Double {
numbers.append(n)
if numbers.count > period {
numbers.removeFirst()
}
guard!numbers.isEmpty else {
return 0
}
return numbers.reduce(0, +) / Double(numbers.count)
}
}
for period in [3, 5] {
print("Moving average with period \(period)")
var averager = SimpleMovingAverage(period: period)
for n in [1.0, 2, 3, 4, 5, 5, 4, 3, 2, 1] {
print("n: \(n); average \(averager.addNumber(n))")
}
} | 1,115Averages/Simple moving average
| 17swift
| rhhgg |
<?php
$samples = array(
'1st' => array(350, 10),
'2nd' => array(90, 180, 270, 360),
'3rd' => array(10, 20, 30)
);
foreach($samples as $key => $sample){
echo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL;
}
function meanAngle ($angles){
$y_part = $x_part = 0;
$size = count($angles);
for ($i = 0; $i < $size; $i++){
$x_part += cos(deg2rad($angles[$i]));
$y_part += sin(deg2rad($angles[$i]));
}
$x_part /= $size;
$y_part /= $size;
return rad2deg(atan2($y_part, $x_part));
}
?> | 1,122Averages/Mean angle
| 12php
| onx85 |
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Println(median([]float64{3, 1, 4, 1})) | 1,125Averages/Median
| 0go
| u46vt |
class BalancedTernary
include Comparable
def initialize(str = )
if str =~ /[^-+0]+/
raise ArgumentError,
end
@digits = trim0(str)
end
I2BT = {0 => [,0], 1 => [,0], 2 => [,1]}
def self.from_int(value)
n = value.to_i
digits =
while n!= 0
quo, rem = n.divmod(3)
bt, carry = I2BT[rem]
digits = bt + digits
n = quo + carry
end
new(digits)
end
BT2I = { => -1, => 0, => 1}
def to_int
@digits.chars.inject(0) do |sum, char|
sum = 3 * sum + BT2I[char]
end
end
alias :to_i :to_int
def to_s
@digits.dup
end
alias :inspect :to_s
def <=>(other)
to_i <=> other.to_i
end
ADDITION_TABLE = {
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
=> [,], => [,], => [,],
}
def +(other)
maxl = [to_s.length, other.to_s.length].max
a = pad0_reverse(to_s, maxl)
b = pad0_reverse(other.to_s, maxl)
carry =
sum = a.zip( b ).inject() do |sum, (c1, c2)|
carry, digit = ADDITION_TABLE[carry + c1 + c2]
sum = digit + sum
end
self.class.new(carry + sum)
end
MULTIPLICATION_TABLE = {
=> ,
=> ,
=> ,
}
def *(other)
product = self.class.new
other.to_s.each_char do |bdigit|
row = to_s.tr(, MULTIPLICATION_TABLE[bdigit])
product += self.class.new(row)
product << 1
end
product >> 1
end
def -@()
self.class.new(@digits.tr('-+','+-'))
end
def -(other)
self + (-other)
end
def <<(count)
@digits = trim0(@digits + *count)
self
end
def >>(count)
@digits[-count..-1] = if count > 0
@digits = trim0(@digits)
self
end
private
def trim0(str)
str = str.sub(/^0+/, )
str = if str.empty?
str
end
def pad0_reverse(str, len)
str.rjust(len, ).reverse.chars
end
end
a = BalancedTernary.new()
b = BalancedTernary.from_int(-436)
c = BalancedTernary.new()
%w[a b c a*(b-c)].each do |exp|
val = eval(exp)
puts % [exp, val, val.to_i]
end | 1,119Balanced ternary
| 14ruby
| rj4gs |
require
testvalues = [[100000000000000.01, 100000000000000.011],
[100.01, 100.011],
[10000000000000.001 / 10000.0, 1000000000.0000001000],
[0.001, 0.0010000001],
[0.000000000000000000000101, 0.0],
[(2**0.5) * (2**0.5), 2.0],
[-(2**0.5) * (2**0.5), -2.0],
[BigDecimal(), 3.14159265358979324],
[Float::NAN, Float::NAN,],
[Float::INFINITY, Float::INFINITY],
]
class Numeric
def close_to?(num, tol = Float::EPSILON)
return true if self == num
return false if (self.to_f.nan? or num.to_f.nan?)
return false if [self, num].count( Float::INFINITY) == 1
return false if [self, num].count(-Float::INFINITY) == 1
(self-num).abs <= tol * ([self.abs, num.abs].max)
end
end
testvalues.each do |a,b|
puts
end | 1,128Approximate equality
| 14ruby
| nf1it |
null | 1,128Approximate equality
| 15rust
| dtany |
class PasswdRecord {
String account, password, directory, shell
int uid, gid
SourceRecord source
private static final fs = ':'
private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell']
private static final stringFields = ['account', 'password', 'directory', 'shell']
private static final intFields = ['uid', 'gid']
PasswdRecord(String line = null) {
if (!line) return
def fields = line.split(fs)
if (fields.size() != fieldNames.size()) {
throw new IllegalArgumentException(
"Passwd record must have exactly ${fieldNames.size()} '${fs}'-delimited fields")
}
(0..<fields.size()).each { i ->
switch (fieldNames[i]) {
case stringFields: this[fieldNames[i]] = fields[i]; break
case intFields: this[fieldNames[i]] = fields[i] as Integer; break
default : this.source = new SourceRecord(fields[i]); break
}
}
}
@Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] }
}
class SourceRecord {
String fullname, office, extension, homephone, email
private static final fs = ','
private static final fieldNames =
['fullname', 'office', 'extension', 'homephone', 'email']
SourceRecord(String line = null) {
if (!line) return
def fields = line.split(fs)
if (fields.size() != fieldNames.size()) {
throw new IllegalArgumentException(
"Source record must have exactly ${fieldNames.size()} '${fs}'-delimited fields")
}
(0..<fields.size()).each { i ->
this[fieldNames[i]] = fields[i]
}
}
@Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] }
}
def appendNewPasswdRecord = {
PasswdRecord pwr = new PasswdRecord().with { p ->
(account, password, uid, gid) = ['xyz', 'x', 1003, 1000]
source = new SourceRecord().with { s ->
(fullname, office, extension, homephone, email) =
['X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', '[email protected]']
s
}
(directory, shell) = ['/home/xyz', '/bin/bash']
p
};
new File('passwd.txt').withWriterAppend { w ->
w.append(pwr as String)
w.append('\r\n')
}
} | 1,132Append a record to the end of a text file
| 7groovy
| q05xp |
a = 5
assert (a == 42)
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything') | 1,130Assertions
| 1lua
| idkot |
use strict;
use List::AllUtils 'natatime';
sub TDF_II_filter {
our(@signal,@a,@b);
local(*signal,*a,*b) = (shift, shift, shift);
my @out = (0) x $
for my $i (0..@signal-1) {
my $this;
map { $this += $b[$_] * $signal[$i-$_] if $i-$_ >= 0 } 0..@b;
map { $this -= $a[$_] * $out[$i-$_] if $i-$_ >= 0 } 0..@a;
$out[$i] = $this / $a[0];
}
@out
}
my @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
);
my @a = ( 1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 );
my @b = ( 0.16666667, 0.5, 0.5, 0.16666667 );
my @filtered = TDF_II_filter(\@signal, \@a, \@b);
my $iter = natatime 5, @filtered;
while( my @values = $iter->() ) {
printf('%10.6f' x 5 . "\n", @values);
} | 1,131Apply a digital filter (direct form II transposed)
| 2perl
| rjzgd |
def median(Iterable col) {
def s = col as SortedSet
if (s == null) return null
if (s.empty) return 0
def n = s.size()
def m = n.intdiv(2)
def l = s.collect { it }
n%2 == 1 ? l[m]: (l[m] + l[m-1])/2
} | 1,125Averages/Median
| 7groovy
| 9ldm4 |
use std::{
cmp::min,
convert::{TryFrom, TryInto},
fmt,
ops::{Add, Mul, Neg},
str::FromStr,
};
fn main() -> Result<(), &'static str> {
let a = BalancedTernary::from_str("+-0++0+")?;
let b = BalancedTernary::from(-436);
let c = BalancedTernary::from_str("+-++-")?;
println!("a = {} = {}", a, i128::try_from(a.clone())?);
println!("b = {} = {}", b, i128::try_from(b.clone())?);
println!("c = {} = {}", c, i128::try_from(c.clone())?);
let d = a * (b + -c);
println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?);
let e = BalancedTernary::from_str(
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++",
)?;
assert_eq!(i128::try_from(e).is_err(), true);
Ok(())
}
#[derive(Clone, Copy, PartialEq)]
enum Trit {
Zero,
Pos,
Neg,
}
impl TryFrom<char> for Trit {
type Error = &'static str;
fn try_from(value: char) -> Result<Self, Self::Error> {
match value {
'0' => Ok(Self::Zero),
'+' => Ok(Self::Pos),
'-' => Ok(Self::Neg),
_ => Err("Invalid character for balanced ternary"),
}
}
}
impl From<Trit> for char {
fn from(x: Trit) -> Self {
match x {
Trit::Zero => '0',
Trit::Pos => '+',
Trit::Neg => '-',
}
}
}
impl Add for Trit { | 1,119Balanced ternary
| 15rust
| 7hgrc |
object Approximate extends App {
val (ok, notOk, ) = ("", "", 1e-18d)
private def approxEquals(value: Double, other: Double, epsilon: Double) =
scala.math.abs(value - other) < epsilon
private def test(a: BigDecimal, b: BigDecimal, expected: Boolean): Unit = {
val result = approxEquals(a.toDouble, b.toDouble, )
println(f"$a%40.24f $b%40.24f => $result%5s ${if (expected == result) ok else notOk}")
}
test(BigDecimal("100000000000000.010"), BigDecimal("100000000000000.011"), true)
test(BigDecimal("100.01"), BigDecimal("100.011"), false)
test(BigDecimal(10000000000000.001 / 10000.0), BigDecimal("1000000000.0000001000"), false)
test(BigDecimal("0.001"), BigDecimal("0.0010000001"), false)
test(BigDecimal("0.000000000000000000000101"), BigDecimal(0), true)
test(BigDecimal(math.sqrt(2) * math.sqrt(2d)), BigDecimal(2.0), false)
test(BigDecimal(-Math.sqrt(2) * Math.sqrt(2)), BigDecimal(-2.0), false)
test(BigDecimal("3.14159265358979323846"), BigDecimal("3.14159265358979324"), true)
} | 1,128Approximate equality
| 16scala
| z6xtr |
import System.IO
import Data.List (intercalate)
data Gecos = Gecos { fullname :: String
, office :: String
, extension :: String
, homephone :: String
, email :: String
}
data Record = Record { account :: String
, password :: String
, uid :: Int
, gid :: Int
, directory :: String
, shell :: String
, gecos :: Gecos
}
instance Show Gecos where
show (Gecos {..}) = intercalate "," [fullname, office, extension, homephone, email]
instance Show Record where
show (Record {..}) = intercalate ":" [account, password, show uid, show gid, show gecos, directory, shell]
addRecord :: String -> Record -> IO ()
addRecord path r = appendFile path (show r) | 1,132Append a record to the end of a text file
| 8haskell
| v5o2k |
use strict;
use 5.10.0;
use threads 'yield';
use threads::shared;
my @a :shared = (100) x 10;
my $stop :shared = 0;
sub pick2 {
my $i = int(rand(10));
my $j;
$j = int(rand(10)) until $j != $i;
($i, $j)
}
sub even {
lock @a;
my ($i, $j) = pick2;
my $sum = $a[$i] + $a[$j];
$a[$i] = int($sum / 2);
$a[$j] = $sum - $a[$i];
}
sub rand_move {
lock @a;
my ($i, $j) = pick2;
my $x = int(rand $a[$i]);
$a[$i] -= $x;
$a[$j] += $x;
}
sub show {
lock @a;
my $sum = 0;
$sum += $_ for (@a);
printf "%4d", $_ for @a;
print " total $sum\n";
}
my $t1 = async { even until $stop }
my $t2 = async { rand_move until $stop }
my $t3 = async {
for (1 .. 10) {
show;
sleep(1);
}
$stop = 1;
};
$t1->join; $t2->join; $t3->join; | 1,126Atomic updates
| 2perl
| 3y0zs |
from cmath import rect, phase
from math import radians, degrees
def mean_angle(deg):
return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))
def mean_time(times):
t = (time.split(':') for time in times)
seconds = ((float(s) + int(m) * 60 + int(h) * 3600)
for h, m, s in t)
day = 24 * 60 * 60
to_angles = [s * 360. / day for s in seconds]
mean_as_angle = mean_angle(to_angles)
mean_seconds = mean_as_angle * day / 360.
if mean_seconds < 0:
mean_seconds += day
h, m = divmod(mean_seconds, 3600)
m, s = divmod(m, 60)
return '%02i:%02i:%02i'% (h, m, s)
if __name__ == '__main__':
print( mean_time([, , , ]) ) | 1,120Averages/Mean time of day
| 3python
| 9l6mf |
import Data.List (partition)
nth :: Ord t => [t] -> Int -> t
nth (x:xs) n
| k == n = x
| k > n = nth ys n
| otherwise = nth zs $ n - k - 1
where
(ys, zs) = partition (< x) xs
k = length ys
medianMay :: (Fractional a, Ord a) => [a] -> Maybe a
medianMay xs
| n < 1 = Nothing
| even n = Just ((nth xs (div n 2) + nth xs (div n 2 - 1)) / 2.0)
| otherwise = Just (nth xs (div n 2))
where
n = length xs
main :: IO ()
main =
mapM_
(printMay . medianMay)
[[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]]
where
printMay = maybe (putStrLn "(not defined)") print | 1,125Averages/Median
| 8haskell
| wqjed |
object TernaryBit {
val P = TernaryBit(+1)
val M = TernaryBit(-1)
val Z = TernaryBit( 0)
implicit def asChar(t: TernaryBit): Char = t.charValue
implicit def valueOf(c: Char): TernaryBit = {
c match {
case '0' => 0
case '+' => 1
case '-' => -1
case nc => throw new IllegalArgumentException("Illegal ternary symbol " + nc)
}
}
implicit def asInt(t: TernaryBit): Int = t.intValue
implicit def valueOf(i: Int): TernaryBit = TernaryBit(i)
}
case class TernaryBit(val intValue: Int) {
def inverse: TernaryBit = TernaryBit(-intValue)
def charValue = intValue match {
case 0 => '0'
case 1 => '+'
case -1 => '-'
}
}
class Ternary(val bits: List[TernaryBit]) {
def + (b: Ternary) = {
val sumBits: List[Int] = bits.map(_.intValue).zipAll(b.bits.map(_.intValue), 0, 0).map(p => p._1 + p._2) | 1,119Balanced ternary
| 16scala
| kpjhk |
import Foundation
extension FloatingPoint {
@inlinable
public func isAlmostEqual(
to other: Self,
tolerance: Self = Self.ulpOfOne.squareRoot()
) -> Bool { | 1,128Approximate equality
| 17swift
| idpo0 |
use strict;
use List::Util qw(max);
sub mode
{
my %c;
foreach my $e ( @_ ) {
$c{$e}++;
}
my $best = max(values %c);
return grep { $c{$_} == $best } keys %c;
} | 1,118Averages/Mode
| 2perl
| uguvr |
from __future__ import print_function
from scipy import signal
import matplotlib.pyplot as plt
if __name__==:
sig = [-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]
a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
b = [0.16666667, 0.5, 0.5, 0.16666667]
filt = signal.lfilter(b, a, sig)
print (filt)
plt.plot(sig, 'b')
plt.plot(filt, 'r--')
plt.show() | 1,131Apply a digital filter (direct form II transposed)
| 3python
| 7h3rm |
class AVLnode <T> {
balance: number
left: AVLnode<T>
right: AVLnode<T>
constructor(public key: T, public parent: AVLnode<T> = null) {
this.balance = 0
this.left = null
this.right = null
}
}
class AVLtree <T> { | 1,121AVL tree
| 20typescript
| awk15 |
>>> from cmath import rect, phase
>>> from math import radians, degrees
>>> def mean_angle(deg):
... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))
...
>>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:
... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')
...
The mean angle of [350, 10] is: -0.0 degrees
The mean angle of [90, 180, 270, 360] is: -90.0 degrees
The mean angle of [10, 20, 30] is: 20.0 degrees
>>> | 1,122Averages/Mean angle
| 3python
| 4rl5k |
deg2rad <- function(x) {
x * pi/180
}
rad2deg <- function(x) {
x * 180/pi
}
deg2vec <- function(x) {
c(sin(deg2rad(x)), cos(deg2rad(x)))
}
vec2deg <- function(x) {
res <- rad2deg(atan2(x[1], x[2]))
if (res < 0) {
360 + res
} else {
res
}
}
mean_vec <- function(x) {
y <- lapply(x, deg2vec)
Reduce(`+`, y)/length(y)
}
mean_deg <- function(x) {
vec2deg(mean_vec(x))
}
mean_deg(c(350, 10))
mean_deg(c(90, 180, 270, 360))
mean_deg(c(10, 20, 30)) | 1,122Averages/Mean angle
| 13r
| 2uylg |
function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end
function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} | 1,117Averages/Pythagorean means
| 1lua
| ug5vl |
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RecordAppender {
static class Record {
private final String account;
private final String password;
private final int uid;
private final int gid;
private final List<String> gecos;
private final String directory;
private final String shell;
public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) {
this.account = requireNonNull(account);
this.password = requireNonNull(password);
this.uid = uid;
this.gid = gid;
this.gecos = requireNonNull(gecos);
this.directory = requireNonNull(directory);
this.shell = requireNonNull(shell);
}
@Override
public String toString() {
return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell;
}
public static Record parse(String text) {
String[] tokens = text.split(":");
return new Record(
tokens[0],
tokens[1],
Integer.parseInt(tokens[2]),
Integer.parseInt(tokens[3]),
Arrays.asList(tokens[4].split(",")),
tokens[5],
tokens[6]);
}
}
public static void main(String[] args) throws IOException {
List<String> rawData = Arrays.asList(
"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash",
"xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash"
);
List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList());
Path tmp = Paths.get("_rosetta", ".passwd");
Files.createDirectories(tmp.getParent());
Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator);
Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND);
try (Stream<String> lines = Files.lines(tmp)) {
lines.map(Record::parse).forEach(System.out::println);
}
}
} | 1,132Append a record to the end of a text file
| 9java
| y9w6g |
from __future__ import with_statement
import threading
import random
import time
terminate = threading.Event()
class Buckets:
def __init__(self, nbuckets):
self.nbuckets = nbuckets
self.values = [random.randrange(10) for i in range(nbuckets)]
self.lock = threading.Lock()
def __getitem__(self, i):
return self.values[i]
def transfer(self, src, dst, amount):
with self.lock:
amount = min(amount, self.values[src])
self.values[src] -= amount
self.values[dst] += amount
def snapshot(self):
with self.lock:
return self.values[:]
def randomize(buckets):
nbuckets = buckets.nbuckets
while not terminate.isSet():
src = random.randrange(nbuckets)
dst = random.randrange(nbuckets)
if dst!=src:
amount = random.randrange(20)
buckets.transfer(src, dst, amount)
def equalize(buckets):
nbuckets = buckets.nbuckets
while not terminate.isSet():
src = random.randrange(nbuckets)
dst = random.randrange(nbuckets)
if dst!=src:
amount = (buckets[src] - buckets[dst])
if amount>=0: buckets.transfer(src, dst, amount)
else: buckets.transfer(dst, src, -amount)
def print_state(buckets):
snapshot = buckets.snapshot()
for value in snapshot:
print '%2d'% value,
print '=', sum(snapshot)
buckets = Buckets(15)
t1 = threading.Thread(target=randomize, args=[buckets])
t1.start()
t2 = threading.Thread(target=equalize, args=[buckets])
t2.start()
try:
while True:
print_state(buckets)
time.sleep(1)
except KeyboardInterrupt:
terminate.set()
t1.join()
t2.join() | 1,126Atomic updates
| 3python
| 6m83w |
<?php
function mode($arr) {
$count = array_count_values($arr);
$best = max($count);
return array_keys($count, $best);
}
print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?> | 1,118Averages/Mode
| 12php
| 8n80m |
def filter(a,b,signal)
result = Array.new(signal.length(), 0.0)
for i in 0..signal.length()-1 do
tmp = 0.0
for j in 0 .. b.length()-1 do
if i - j < 0 then next end
tmp += b[j] * signal[i - j]
end
for j in 1 .. a.length()-1 do
if i - j < 0 then next end
tmp -= a[j] * result[i - j]
end
tmp /= a[0]
result[i] = tmp
end
return result
end
def main
a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
b = [0.16666667, 0.5, 0.5, 0.16666667]
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
]
result = filter(a,b,signal)
for i in 0 .. result.length() - 1 do
print % [result[i]]
if (i + 1) % 5 == 0 then
print
else
print
end
end
end
main() | 1,131Apply a digital filter (direct form II transposed)
| 14ruby
| hbyjx |
use ntheory <is_prime factor>;
is_prime +factor $_ and print "$_ " for 1..120; | 1,124Attractive numbers
| 2perl
| 6mi36 |
def time2deg(t)
raise unless m = t.match(/^(\d\d):(\d\d):(\d\d)$/)
hh,mm,ss = m[1..3].map {|e| e.to_i}
raise unless (0..23).include? hh and
(0..59).include? mm and
(0..59).include? ss
(hh*3600 + mm*60 + ss) * 360 / 86400.0
end
def deg2time(d)
sec = (d % 360) * 86400 / 360.0
% [sec/3600, (sec%3600)/60, sec%60]
end
def mean_time(times)
deg2time(mean_angle(times.map {|t| time2deg t}))
end
puts mean_time [, , , ] | 1,120Averages/Mean time of day
| 14ruby
| lvmcl |
require 'complex'
def deg2rad(d)
d * Math::PI / 180
end
def rad2deg(r)
r * 180 / Math::PI
end
def mean_angle(deg)
rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg)
end
[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles|
puts % [angles, mean_angle(angles)]
} | 1,122Averages/Mean angle
| 14ruby
| rjvgs |
null | 1,125Averages/Median
| 9java
| kpuhm |
function median(ary) {
if (ary.length == 0)
return null;
ary.sort(function (a,b){return a - b})
var mid = Math.floor(ary.length / 2);
if ((ary.length % 2) == 1) | 1,125Averages/Median
| 10javascript
| ex7ao |
WITH
FUNCTION babbage(p_ziel IN varchar2, p_max INTEGER) RETURN varchar2 IS
v_max INTEGER:= greatest(p_max,to_number('1E+'||LENGTH(to_char(p_ziel))));
v_start NUMBER:= CASE WHEN substr(p_ziel,1,1)='0' THEN CEIL(SQRT('1'||p_ziel)) ELSE CEIL(SQRT(p_ziel)) END;
v_length NUMBER:= to_number('1E+'||LENGTH(to_char(p_ziel)));
BEGIN
-- first check
IF substr(p_ziel,-1) IN (2,3,7,8) THEN
RETURN 'The exact square of an integer cannot end with '''||substr(p_ziel,-1)||''', so there is no such smallest number whose square ends in '''||p_ziel||'''';
END IF;
-- second check
IF regexp_count(p_ziel,'([^0]0{1,}$)')=1 AND MOD(regexp_count(regexp_substr(p_ziel,'(0{1,}$)'),'0'),2)=1 THEN
RETURN 'An exact square of an integer cannot end with an odd number of zeros, so there is no such smallest number whose square ends in '''||p_ziel||'''';
END IF;
-- main cycle
while v_start < v_max loop
exit WHEN MOD(v_start**2,v_length) = p_ziel;
v_start:= v_start + 1;
END loop;
-- output
IF v_start = v_max THEN
RETURN 'There is no such smallest number before '||v_max||' whose square ends in '''||p_ziel||'''';
ELSE
RETURN ''||v_start||' is the smallest number, whose square '||regexp_replace(to_char(v_start**2),'(\d{1,})('||p_ziel||')','\1''\2''')||' ends in '''||p_ziel||'''';
END IF;
--
END;
--Test
SELECT babbage('222',100000) AS res FROM dual
UNION ALL
SELECT babbage('33',100000) AS res FROM dual
UNION ALL
SELECT babbage('17',100000) AS res FROM dual
UNION ALL
SELECT babbage('888',100000) AS res FROM dual
UNION ALL
SELECT babbage('1000',100000) AS res FROM dual
UNION ALL
SELECT babbage('000',100000) AS res FROM dual
UNION ALL
SELECT babbage('269696',100000) AS res FROM dual -- strict Babbage Problem
UNION ALL
SELECT babbage('269696',10) AS res FROM dual
UNION ALL
SELECT babbage('169696',10) AS res FROM dual
UNION ALL
SELECT babbage('19696',100000) AS res FROM dual
UNION ALL
SELECT babbage('04',100000) AS res FROM dual; | 1,116Babbage problem
| 19sql
| f3zdi |
null | 1,132Append a record to the end of a text file
| 11kotlin
| fzbdo |
use std::cmp::Ordering;
struct IIRFilter<'f>(&'f [f32], &'f [f32]);
impl<'f> IIRFilter<'f> {
pub fn with_coefficients(a: &'f [f32], b: &'f [f32]) -> IIRFilter<'f> {
IIRFilter(a, b)
} | 1,131Apply a digital filter (direct form II transposed)
| 15rust
| kpmh5 |
object ButterworthFilter extends App {
private def filter(a: Vector[Double],
b: Vector[Double],
signal: Vector[Double]): Vector[Double] = {
@scala.annotation.tailrec
def outer(i: Int, acc: Vector[Double]): Vector[Double] = {
if (i >= signal.length) acc
else {
@scala.annotation.tailrec
def inner0(j: Int, tmp: Double): Double = if (j >= b.length) tmp
else if ((i - j) >= 0) inner0(j + 1, tmp + b(j) * signal(i - j)) else inner0(j + 1, tmp)
@scala.annotation.tailrec
def inner1(j: Int, tmp: Double): Double = if (j >= a.length) tmp
else if (i - j >= 0) inner1(j + 1, tmp - a(j) * acc(i - j)) else inner1(j + 1, tmp)
outer(i + 1, acc :+ inner1(1, inner0(0, 0D)) / a(0))
}
}
outer(0, Vector())
}
filter(Vector[Double](1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17),
Vector[Double](0.16666667, 0.5, 0.5, 0.16666667),
Vector[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)
).grouped(5)
.map(_.map(x => f"$x% .8f"))
.foreach(line => println(line.mkString(" ")))
} | 1,131Apply a digital filter (direct form II transposed)
| 16scala
| 1elpf |
<?php
function isPrime ($x) {
if ($x < 2) return false;
if ($x < 4) return true;
if ($x % 2 == 0) return false;
for ($d = 3; $d < sqrt($x); $d++) {
if ($x % $d == 0) return false;
}
return true;
}
function countFacs ($n) {
$count = 0;
$divisor = 1;
if ($n < 2) return 0;
while (!isPrime($n)) {
while (!isPrime($divisor)) $divisor++;
while ($n % $divisor == 0) {
$n /= $divisor;
$count++;
}
$divisor++;
if ($n == 1) return $count;
}
return $count + 1;
}
for ($i = 1; $i <= 120; $i++) {
if (isPrime(countFacs($i))) echo $i.;
}
?> | 1,124Attractive numbers
| 12php
| 1erpq |
use std::f64::consts::PI;
#[derive(Debug, PartialEq, Eq)]
struct Time {
h: u8,
m: u8,
s: u8,
}
impl Time { | 1,120Averages/Mean time of day
| 15rust
| 2u9lt |
use std::f64; | 1,122Averages/Mean angle
| 15rust
| 7hurc |
trait MeanAnglesComputation {
import scala.math.{Pi, atan2, cos, sin}
def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = {
val sums = angles.foldLeft((.0, .0))((r, c) => {
val rads = c / convFactor
(r._1 + sin(rads), r._2 + cos(rads))
})
val result = atan2(sums._1, sums._2)
(result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor
}
}
object MeanAngles extends App with MeanAnglesComputation {
assert(meanAngle(List(350, 10), 180.0 / math.Pi).round == 360, "Unexpected result with 350, 10")
assert(meanAngle(List(90, 180, 270, 360)).round == 270, "Unexpected result with 90, 180, 270, 360")
assert(meanAngle(List(10, 20, 30)).round == 20, "Unexpected result with 10, 20, 30")
println("Successfully completed without errors.")
} | 1,122Averages/Mean angle
| 16scala
| kpghk |
import Swift
for i in 2...Int.max {
if i * i% 1000000 == 269696 {
print(i, "is the smallest number that ends with 269696")
break
}
} | 1,116Babbage problem
| 17swift
| q80xg |
function append(tbl,filename)
local file,err = io.open(filename, "a")
if err then return err end
file:write(tbl.account..":")
file:write(tbl.password..":")
file:write(tbl.uid..":")
file:write(tbl.gid..":")
for i,v in ipairs(tbl.gecos) do
if i>1 then
file:write(",")
end
file:write(v)
end
file:write(":")
file:write(tbl.directory..":")
file:write(tbl.shell.."\n")
file:close()
end
local smith = {}
smith.account = "jsmith"
smith.password = "x"
smith.uid = 1001
smith.gid = 1000
smith.gecos = {"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "[email protected]"}
smith.directory = "/home/jsmith"
smith.shell = "/bin/bash"
append(smith, ".passwd")
local doe = {}
doe.account = "jdoe"
doe.password = "x"
doe.uid = 1002
doe.gid = 1000
doe.gecos = {"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "[email protected]"}
doe.directory = "/home/jdoe"
doe.shell = "/bin/bash"
append(doe, ".passwd")
local xyz = {}
xyz.account = "xyz"
xyz.password = "x"
xyz.uid = 1003
xyz.gid = 1000
xyz.gecos = {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "[email protected]"}
xyz.directory = "/home/xyz"
xyz.shell = "/bin/bash"
append(xyz, ".passwd") | 1,132Append a record to the end of a text file
| 1lua
| t3pfn |
package main
import "fmt"
func countDivisors(n int) int {
if n < 2 {
return 1
}
count := 2 | 1,135Anti-primes
| 0go
| fzjd0 |
def getAntiPrimes(def limit = 10) {
def antiPrimes = []
def candidate = 1L
def maxFactors = 0
while (antiPrimes.size() < limit) {
def factors = factorize(candidate)
if (factors.size() > maxFactors) {
maxFactors = factors.size()
antiPrimes << candidate
}
candidate++
}
antiPrimes
} | 1,135Anti-primes
| 7groovy
| 8i50b |
require 'thread'
class BucketStore
def initialize nbuckets
@buckets = (0...nbuckets).map { rand(1024) }
@mutex = Mutex.new
end
def buckets
@mutex.synchronize { Array.new(@buckets) }
end
def transfer destination, source, amount
return nil if destination == source
@mutex.synchronize do
amount = [amount, @buckets[source]].min
@buckets[source] -= amount
@buckets[destination] += amount
end
nil
end
end
bucket_store = BucketStore.new 8
TOTAL = bucket_store.buckets.inject { |a, b| a += b }
Thread.new do
loop do
buckets = bucket_store.buckets
first = rand buckets.length
second = rand buckets.length
first, second = second, first if buckets[first] > buckets[second]
bucket_store.transfer first, second, (buckets[second] - buckets[first]) / 2
end
end
Thread.new do
loop do
buckets = bucket_store.buckets
first = rand buckets.length
second = rand buckets.length
bucket_store.transfer first, second, rand(buckets[second])
end
end
loop do
sleep 1
buckets = bucket_store.buckets
n = buckets.inject { |a, b| a += b }
printf , (buckets.map { |v| sprintf , v }.join ), n
if n!= TOTAL
$stderr.puts
exit 1
end
end | 1,126Atomic updates
| 14ruby
| mciyj |
print "Give me a number: ";
chomp(my $a = <>);
$a == 42 or die "Error message\n";
die "Error message\n" unless $a == 42;
die "Error message\n" if not $a == 42;
die "Error message\n" if $a != 42; | 1,130Assertions
| 2perl
| g7z4e |
import java.time.LocalTime
import scala.compat.Platform
trait MeanAnglesComputation {
import scala.math.{Pi, atan2, cos, sin}
def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = {
val sums = angles.foldLeft((.0, .0))((r, c) => {
val rads = c / convFactor
(r._1 + sin(rads), r._2 + cos(rads))
})
val result = atan2(sums._1, sums._2)
(result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor
}
}
object MeanBatTime extends App with MeanAnglesComputation {
val dayInSeconds = 60 * 60 * 24
def times = batTimes.map(t => afterMidnight(t).toDouble)
def afterMidnight(twentyFourHourTime: String) = {
val t = LocalTime.parse(twentyFourHourTime)
(if (t.isBefore(LocalTime.NOON)) dayInSeconds else 0) + LocalTime.parse(twentyFourHourTime).toSecondOfDay
}
def batTimes = List("23:00:17", "23:40:20", "00:12:45", "00:17:19")
assert(LocalTime.MIN.plusSeconds(meanAngle(times, dayInSeconds).round).toString == "23:47:40")
println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
} | 1,120Averages/Mean time of day
| 16scala
| 5g2ut |
fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }
fun main(args: Array<String>) {
median(listOf(5.0, 3.0, 4.0)).let { println(it) } | 1,125Averages/Median
| 11kotlin
| g794d |
import Data.List (find, group)
import Data.Maybe (fromJust)
firstPrimeFactor :: Int -> Int
firstPrimeFactor n = head $ filter ((0 ==) . mod n) [2 .. n]
allPrimeFactors :: Int -> [Int]
allPrimeFactors 1 = []
allPrimeFactors n =
let first = firstPrimeFactor n
in first: allPrimeFactors (n `div` first)
factorCount :: Int -> Int
factorCount 1 = 1
factorCount n = product ((succ . length) <$> group (allPrimeFactors n))
divisorCount :: Int -> (Int, Int)
divisorCount = (,) <*> factorCount
hcnNext :: (Int, Int) -> (Int, Int)
hcnNext (num, factors) =
fromJust $ find ((> factors) . snd) (divisorCount <$> [num ..])
hcnSequence :: [Int]
hcnSequence = fst <$> iterate hcnNext (1, 1)
main :: IO ()
main = print $ take 20 hcnSequence | 1,135Anti-primes
| 8haskell
| 4ro5s |
extern crate rand;
use std::sync::{Arc, Mutex};
use std::thread;
use std::cmp;
use std::time::Duration;
use rand::Rng;
use rand::distributions::{IndependentSample, Range};
trait Buckets {
fn equalize<R:Rng>(&mut self, rng: &mut R);
fn randomize<R:Rng>(&mut self, rng: &mut R);
fn print_state(&self);
}
impl Buckets for [i32] {
fn equalize<R:Rng>(&mut self, rng: &mut R) {
let range = Range::new(0,self.len()-1);
let src = range.ind_sample(rng);
let dst = range.ind_sample(rng);
if dst!= src {
let amount = cmp::min(((dst + src) / 2) as i32, self[src]);
let multiplier = if amount >= 0 { -1 } else { 1 };
self[src] += amount * multiplier;
self[dst] -= amount * multiplier;
}
}
fn randomize<R:Rng>(&mut self, rng: &mut R) {
let ind_range = Range::new(0,self.len()-1);
let src = ind_range.ind_sample(rng);
let dst = ind_range.ind_sample(rng);
if dst!= src {
let amount = cmp::min(Range::new(0,20).ind_sample(rng), self[src]);
self[src] -= amount;
self[dst] += amount;
}
}
fn print_state(&self) {
println!("{:?} = {}", self, self.iter().sum::<i32>());
}
}
fn main() {
let e_buckets = Arc::new(Mutex::new([10; 10]));
let r_buckets = e_buckets.clone();
let p_buckets = e_buckets.clone();
thread::spawn(move || {
let mut rng = rand::thread_rng();
loop {
let mut buckets = e_buckets.lock().unwrap();
buckets.equalize(&mut rng);
}
});
thread::spawn(move || {
let mut rng = rand::thread_rng();
loop {
let mut buckets = r_buckets.lock().unwrap();
buckets.randomize(&mut rng);
}
});
let sleep_time = Duration::new(1,0);
loop {
{
let buckets = p_buckets.lock().unwrap();
buckets.print_state();
}
thread::sleep(sleep_time);
}
} | 1,126Atomic updates
| 15rust
| 9lnmm |
<?php
$a = 5
assert($a == 42)
?> | 1,130Assertions
| 12php
| nfbig |
public class Antiprime {
static int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; | 1,135Anti-primes
| 9java
| c2w9h |
object AtomicUpdates {
class Buckets(ns: Int*) {
import scala.actors.Actor._
val buckets = ns.toArray
case class Get(index: Int)
case class Transfer(fromIndex: Int, toIndex: Int, amount: Int)
case object GetAll
val handler = actor {
loop {
react {
case Get(index) => reply(buckets(index))
case Transfer(fromIndex, toIndex, amount) =>
assert(amount >= 0)
val actualAmount = Math.min(amount, buckets(fromIndex))
buckets(fromIndex) -= actualAmount
buckets(toIndex) += actualAmount
case GetAll => reply(buckets.toList)
}
}
}
def get(index: Int): Int = (handler !? Get(index)).asInstanceOf[Int]
def transfer(fromIndex: Int, toIndex: Int, amount: Int) = handler ! Transfer(fromIndex, toIndex, amount)
def getAll: List[Int] = (handler !? GetAll).asInstanceOf[List[Int]]
}
def randomPair(n: Int): (Int, Int) = {
import scala.util.Random._
val pair = (nextInt(n), nextInt(n))
if (pair._1 == pair._2) randomPair(n) else pair
}
def main(args: Array[String]) {
import scala.actors.Scheduler._
val buckets = new Buckets(List.range(1, 11): _*)
val stop = new java.util.concurrent.atomic.AtomicBoolean(false)
val latch = new java.util.concurrent.CountDownLatch(3)
execute {
while (!stop.get) {
val (i1, i2) = randomPair(10)
val (n1, n2) = (buckets.get(i1), buckets.get(i2))
val m = (n1 + n2) / 2
if (n1 < n2)
buckets.transfer(i2, i1, n2 - m)
else
buckets.transfer(i1, i2, n1 - m)
}
latch.countDown
}
execute {
while (!stop.get) {
val (i1, i2) = randomPair(10)
val n = buckets.get(i1)
buckets.transfer(i1, i2, if (n == 0) 0 else scala.util.Random.nextInt(n))
}
latch.countDown
}
execute {
for (i <- 1 to 20) {
val all = buckets.getAll
println(all.sum + ":" + all)
Thread.sleep(500)
}
stop.set(true)
latch.countDown
}
latch.await
shutdown
}
} | 1,126Atomic updates
| 16scala
| 2utlb |
>>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
for v in values:
count[v] +=1
best = max(count.values())
return [k for k,v in count.items() if v == best]
>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 4] | 1,118Averages/Mode
| 3python
| 5r5ux |
import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (s, c) =
angles.lazy
.map(d2r)
.map({ (sin($0), cos($0)) })
.reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 })
return r2d(atan2(cInv * s, cInv * c))
}
let fmt = { String(format: "%lf", $0) }
print("Mean of angles (350, 10) => \(fmt(meanOfAngles([350, 10])))")
print("Mean of angles (90, 180, 270, 360) => \(fmt(meanOfAngles([90, 180, 270, 360])))")
print("Mean of angles (10, 20, 30) => \(fmt(meanOfAngles([10, 20, 30])))") | 1,122Averages/Mean angle
| 17swift
| g7249 |
System.Collections.HashTable map = new System.Collections.HashTable();
map[] = ; | 1,137Associative array/Creation
| 5c
| id5o2 |
function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (ifactors.length > maxFactors) {
antiprimes.push(i);
maxFactors = ifactors.length;
}
}
return antiprimes;
}
function go() {
var number = document.getElementById("n").value;
document.body.removeChild(document.getElementById("result-list"));
document.body.appendChild(showList(generateAntiprimes(number)));
}
function showList(array) {
var list = document.createElement("ul");
list.id = "result-list";
for (var i = 0; i < array.length; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
} | 1,135Anti-primes
| 10javascript
| 5g8ur |
a = 5
assert a == 42
assert a == 42, | 1,130Assertions
| 3python
| rj3gq |
stopifnot(a==42) | 1,130Assertions
| 13r
| u4dvx |
function median (numlist)
if type(numlist) ~= 'table' then return numlist end
table.sort(numlist)
if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
return numlist[math.ceil(#numlist/2)]
end
print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2})) | 1,125Averages/Median
| 1lua
| rjcga |
use strict;
use warnings;
use Fcntl qw( :flock SEEK_END );
use constant {
RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )],
GECOS_FIELDS => [qw( fullname office extension homephone email )],
RECORD_SEP => ':',
GECOS_SEP => ',',
PASSWD_FILE => 'passwd.txt',
};
my $records_to_write = [
{
account => 'jsmith',
password => 'x',
UID => 1001,
GID => 1000,
GECOS => {
fullname => 'John Smith',
office => 'Room 1007',
extension => '(234)555-8917',
homephone => '(234)555-0077',
email => '[email protected]',
},
directory => '/home/jsmith',
shell => '/bin/bash',
},
{
account => 'jdoe',
password => 'x',
UID => 1002,
GID => 1000,
GECOS => {
fullname => 'Jane Doe',
office => 'Room 1004',
extension => '(234)555-8914',
homephone => '(234)555-0044',
email => '[email protected]',
},
directory => '/home/jdoe',
shell => '/bin/bash',
},
];
my $record_to_append = {
account => 'xyz',
password => 'x',
UID => 1003,
GID => 1000,
GECOS => {
fullname => 'X Yz',
office => 'Room 1003',
extension => '(234)555-8913',
homephone => '(234)555-0033',
email => '[email protected]',
},
directory => '/home/xyz',
shell => '/bin/bash',
};
sub record_to_string {
my $rec = shift;
my $sep = shift // RECORD_SEP;
my $fields = shift // RECORD_FIELDS;
my @ary;
for my $field (@$fields) {
my $r = $rec->{$field};
die "Field '$field' not found" unless defined $r;
push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r );
}
return join $sep, @ary;
}
sub write_records_to_file {
my $records = shift;
my $filename = shift // PASSWD_FILE;
open my $fh, '>>', $filename or die "Can't open $filename: $!";
flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!";
seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ;
print $fh record_to_string($_), "\n" for @$records;
flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!";
}
write_records_to_file( $records_to_write );
write_records_to_file( [$record_to_append] );
{
use Test::Simple tests => 1;
open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!";
my @lines = <$fh>;
chomp @lines;
ok(
$lines[-1] eq
'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash',
"Appended record: $lines[-1]"
);
} | 1,132Append a record to the end of a text file
| 2perl
| hb6jl |
import Foundation
final class AtomicBuckets: CustomStringConvertible {
var count: Int {
return buckets.count
}
var description: String {
return withBucketsLocked { "\(buckets)" }
}
var total: Int {
return withBucketsLocked { buckets.reduce(0, +) }
}
private let lock = DispatchSemaphore(value: 1)
private var buckets: [Int]
subscript(n: Int) -> Int {
return withBucketsLocked { buckets[n] }
}
init(with buckets: [Int]) {
self.buckets = buckets
}
func transfer(amount: Int, from: Int, to: Int) {
withBucketsLocked {
let transferAmount = buckets[from] >= amount? amount: buckets[from]
buckets[from] -= transferAmount
buckets[to] += transferAmount
}
}
private func withBucketsLocked<T>(do: () -> T) -> T {
let ret: T
lock.wait()
ret = `do`()
lock.signal()
return ret
}
}
let bucks = AtomicBuckets(with: [21, 39, 40, 20])
let order = DispatchSource.makeTimerSource()
let chaos = DispatchSource.makeTimerSource()
let printer = DispatchSource.makeTimerSource()
printer.setEventHandler {
print("\(bucks) = \(bucks.total)")
}
printer.schedule(deadline: .now(), repeating: .seconds(1))
printer.activate()
order.setEventHandler {
let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count))
let (v1, v2) = (bucks[b1], bucks[b2])
guard v1!= v2 else {
return
}
if v1 > v2 {
bucks.transfer(amount: (v1 - v2) / 2, from: b1, to: b2)
} else {
bucks.transfer(amount: (v2 - v1) / 2, from: b2, to: b1)
}
}
order.schedule(deadline: .now(), repeating: .milliseconds(5))
order.activate()
chaos.setEventHandler {
let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count))
bucks.transfer(amount: Int.random(in: 0..<(bucks[b1] + 1)), from: b1, to: b2)
}
chaos.schedule(deadline: .now(), repeating: .milliseconds(5))
chaos.activate()
dispatchMain() | 1,126Atomic updates
| 17swift
| y9o6e |
statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
for(i in 1:length(a)) {
if ( a[[1]] == a[[i]] ) {
r <- c(r, as.integer(names(a)[i]))
} else break;
}
r
}
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)))
print(statmode(c(1, 1, 2, 4, 4))) | 1,118Averages/Mode
| 13r
| lulce |
myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 } | 1,134Associative array/Iteration
| 0go
| rjdgm |
def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
println "Entries:"
map.each { println it }
println()
println "Keys:"
map.keySet().each { println it }
println()
println "Values:"
map.values().each { println it } | 1,134Associative array/Iteration
| 7groovy
| v5028 |
package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
} | 1,133Averages/Arithmetic mean
| 0go
| q0uxz |
from sympy import sieve
def get_pfct(n):
i = 2; factors = []
while i * i <= n:
if n% i:
i += 1
else:
n
factors.append(i)
if n > 1:
factors.append(n)
return len(factors)
sieve.extend(110)
primes=sieve._list
pool=[]
for each in xrange(0,121):
pool.append(get_pfct(each))
for i,each in enumerate(pool):
if each in primes:
print i, | 1,124Attractive numbers
| 3python
| y9n6q |
import Foundation
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }
public func meanOfAngles(_ angles: [Double]) -> Double {
let cInv = 1 / Double(angles.count)
let (y, x) =
angles.lazy
.map(d2r)
.map({ (sin($0), cos($0)) })
.reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 })
return r2d(atan2(cInv * y, cInv * x))
}
struct DigitTime {
var hour: Int
var minute: Int
var second: Int
init?(fromString str: String) {
let split = str.components(separatedBy: ":").compactMap(Int.init)
guard split.count == 3 else {
return nil
}
(hour, minute, second) = (split[0], split[1], split[2])
}
init(fromDegrees angle: Double) {
let totalSeconds = 24 * 60 * 60 * angle / 360
second = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
minute = Int((totalSeconds.truncatingRemainder(dividingBy: 3600) - Double(second)) / 60)
hour = Int(totalSeconds / 3600)
}
func toDegrees() -> Double {
return 360 * Double(hour) / 24.0 + 360 * Double(minute) / (24 * 60.0) + 360 * Double(second) / (24 * 3600.0)
}
}
extension DigitTime: CustomStringConvertible {
var description: String { String(format: "%02i:%02i:%02i", hour, minute, second) }
}
let times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"].compactMap(DigitTime.init(fromString:))
guard times.count == 4 else {
fatalError()
}
let meanTime = DigitTime(fromDegrees: 360 + meanOfAngles(times.map({ $0.toDegrees() })))
print("Given times \(times), the mean time is \(meanTime)") | 1,120Averages/Mean time of day
| 17swift
| c2y9t |
null | 1,135Anti-primes
| 11kotlin
| 3ybz5 |
require
include Test::Unit::Assertions
n = 5
begin
assert_equal(42, n)
rescue Exception => e
puts e
end | 1,130Assertions
| 14ruby
| jky7x |
let x = 42;
assert!(x == 42);
assert_eq!(x, 42); | 1,130Assertions
| 15rust
| hbmj2 |
import qualified Data.Map as M
myMap :: M.Map String Int
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]
main :: IO ()
main =
(putStrLn . unlines) $
[ show . M.toList
, show . M.keys
, show . M.elems
] <*>
pure myMap | 1,134Associative array/Iteration
| 8haskell
| 0o5s7 |
def avg = { list -> list == [] ? 0: list.sum() / list.size() } | 1,133Averages/Arithmetic mean
| 7groovy
| 1e9p6 |
is_prime <- function(num) {
if (num < 2) return(FALSE)
if (num %% 2 == 0) return(num == 2)
if (num %% 3 == 0) return(num == 3)
d <- 5
while (d*d <= num) {
if (num %% d == 0) return(FALSE)
d <- d + 2
if (num %% d == 0) return(FALSE)
d <- d + 4
}
TRUE
}
count_prime_factors <- function(num) {
if (num == 1) return(0)
if (is_prime(num)) return(1)
count <- 0
f <- 2
while (TRUE) {
if (num %% f == 0) {
count <- count + 1
num <- num / f
if (num == 1) return(count)
if (is_prime(num)) f <- num
}
else if (f >= 3) f <- f + 2
else f <- 3
}
}
max <- 120
cat("The attractive numbers up to and including",max,"are:\n")
count <- 0
for (i in 1:max) {
n <- count_prime_factors(i);
if (is_prime(n)) {
cat(i," ", sep = "")
count <- count + 1
}
} | 1,124Attractive numbers
| 13r
| t30fz |
<?php
$filename = '/tmp/passwd';
$data = array(
'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL,
'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash' . PHP_EOL,
'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash' . PHP_EOL,
);
file_put_contents($filename, $data, LOCK_EX);
echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
$data = array(
'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash' . PHP_EOL
);
file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; | 1,132Append a record to the end of a text file
| 12php
| z61t1 |
null | 1,135Anti-primes
| 1lua
| 6mp39 |
assert(a == 42)
assert(a == 42, "a isn't equal to 42")
assume(a == 42)
assume(a == 42, "a isn't equal to 42") | 1,130Assertions
| 16scala
| palbj |
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs | 1,133Averages/Arithmetic mean
| 8haskell
| mcwyf |
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func generate(n uint) string {
a := bytes.Repeat([]byte("[]"), int(n))
for i := len(a) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
return string(a)
}
func testBalanced(s string) {
fmt.Print(s + ": ")
open := 0
for _,c := range s {
switch c {
case '[':
open++
case ']':
if open == 0 {
fmt.Println("not ok")
return
}
open--
default:
fmt.Println("not ok")
return
}
}
if open == 0 {
fmt.Println("ok")
} else {
fmt.Println("not ok")
}
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 10; i++ {
testBalanced(generate(i))
}
testBalanced("()")
} | 1,129Balanced brackets
| 0go
| 1evp5 |
def mode(ary)
seen = Hash.new(0)
ary.each {|value| seen[value] += 1}
max = seen.values.max
seen.find_all {|key,value| value == max}.map {|key,value| key}
end
def mode_one_pass(ary)
seen = Hash.new(0)
max = 0
max_elems = []
ary.each do |value|
seen[value] += 1
if seen[value] > max
max = seen[value]
max_elems = [value]
elsif seen[value] == max
max_elems << value
end
end
max_elems
end
p mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])
p mode([1, 1, 2, 4, 4])
p mode_one_pass([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])
p mode_one_pass([1, 1, 2, 4, 4]) | 1,118Averages/Mode
| 14ruby
| gjg4q |
def random = new Random()
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j }: 1 }
def makePermutation;
makePermutation = { string, i ->
def n = string.size()
if (n < 2) return string
def fact = factorial(n-1)
assert i < fact*n
def index = i.intdiv(fact)
string[index] + makePermutation(string[0..<index] + string[(index+1)..<n], i % fact)
}
def randomBrackets = { n ->
if (n == 0) return ''
def base = '['*n + ']'*n
def p = random.nextInt(factorial(n*2))
makePermutation(base, p)
} | 1,129Balanced brackets
| 7groovy
| jkm7o |
passwd_list=[
dict(account='jsmith', password='x', UID=1001, GID=1000,
GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917',
homephone='(234)555-0077', email='[email protected]'),
directory='/home/jsmith', shell='/bin/bash'),
dict(account='jdoe', password='x', UID=1002, GID=1000,
GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914',
homephone='(234)555-0044', email='[email protected]'),
directory='/home/jdoe', shell='/bin/bash')
]
passwd_fields=.split()
GECOS_fields=.split()
def passwd_text_repr(passwd_rec):
passwd_rec[]=.join([ passwd_rec[][field] for field in GECOS_fields])
for field in passwd_rec:
if not isinstance(passwd_rec[field], str):
passwd_rec[field]=`passwd_rec[field]`
return .join([ passwd_rec[field] for field in passwd_fields ])
passwd_text=open(,)
for passwd_rec in passwd_list:
print >> passwd_text,passwd_text_repr(passwd_rec)
passwd_text.close()
passwd_text=open(,)
new_rec=dict(account='xyz', password='x', UID=1003, GID=1000,
GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913',
homephone='(234)555-0033', email='[email protected]'),
directory='/home/xyz', shell='/bin/bash')
print >> passwd_text, passwd_text_repr(new_rec)
passwd_text.close()
passwd_list=list(open(,))
if in passwd_list[-1]:
print ,passwd_list[-1][:-1] | 1,132Append a record to the end of a text file
| 3python
| kpyhf |
{:key "value"
:key2 "value2"
:key3 "value3"} | 1,137Associative array/Creation
| 6clojure
| z6jtj |
var a = 5 | 1,130Assertions
| 17swift
| 7h6rq |
use std::collections::HashMap;
fn main() {
let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);
println!("Mode of vec1 is: {:?}", mode_vec1);
println!("Mode of vec2 is: {:?}", mode_vec2);
assert!( mode_vec1 == [6], "Error in mode calculation");
assert!( (mode_vec2 == [1, 4]) || (mode_vec2 == [4,1]), "Error in mode calculation" );
}
fn mode(vs: Vec<i32>) -> Vec<i32> {
let mut vec_mode = Vec::new();
let mut seen_map = HashMap::new();
let mut max_val = 0;
for i in vs{
let ctr = seen_map.entry(i).or_insert(0);
*ctr += 1;
if *ctr > max_val{
max_val = *ctr;
}
}
for (key, val) in seen_map {
if val == max_val{
vec_mode.push(key);
}
}
vec_mode
} | 1,118Averages/Mode
| 15rust
| rhrg5 |
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3); | 1,134Associative array/Iteration
| 9java
| aw91y |
require
p (1..120).select{|n| n.prime_division.sum(&:last).prime? } | 1,124Attractive numbers
| 14ruby
| 9lfmz |
isMatching :: String -> Bool
isMatching = null . foldl aut []
where
aut ('[':s) ']' = s
aut s x = x:s | 1,129Balanced brackets
| 8haskell
| t3ef7 |
import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
[T, CC[X] <: Seq[X]](coll: CC[T])
(implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
: CC[T] = {
val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
val max = grouped.map(_._2).max
grouped.filter(_._2 == max).map(_._1)(breakOut)
} | 1,118Averages/Mode
| 16scala
| hphja |
var myhash = {}; | 1,134Associative array/Iteration
| 10javascript
| s8uqz |
public static double avg(double... arr) {
double sum = 0.0;
for (double x: arr) {
sum += x;
}
return sum / arr.length;
} | 1,133Averages/Arithmetic mean
| 9java
| fzkdv |
function mean(array)
{
var sum = 0, i;
for (i = 0; i < array.length; i++)
{
sum += array[i];
}
return array.length ? sum / array.length : 0;
}
alert( mean( [1,2,3,4,5] ) ); | 1,133Averages/Arithmetic mean
| 10javascript
| y9e6r |
use primal::Primes;
const MAX: u64 = 120; | 1,124Attractive numbers
| 15rust
| c2t9z |
object AttractiveNumbers extends App {
private val max = 120
private var count = 0
private def nFactors(n: Int): Int = {
@scala.annotation.tailrec
def factors(x: Int, f: Int, acc: Int): Int =
if (f * f > x) acc + 1
else
x % f match {
case 0 => factors(x / f, f, acc + 1)
case _ => factors(x, f + 1, acc)
}
factors(n, 2, 0)
}
private def ls: Seq[String] =
for (i <- 4 to max;
n = nFactors(i)
if n >= 2 && nFactors(n) == 1 | 1,124Attractive numbers
| 16scala
| v562s |
use ntheory qw(divisors);
my @anti_primes;
for (my ($k, $m) = (1, 0) ; @anti_primes < 20 ; ++$k) {
my $sigma0 = divisors($k);
if ($sigma0 > $m) {
$m = $sigma0;
push @anti_primes, $k;
}
}
printf("%s\n", join(' ', @anti_primes)); | 1,135Anti-primes
| 2perl
| pa6b0 |
import Foundation
extension BinaryInteger {
@inlinable
public var isAttractive: Bool {
return primeDecomposition().count.isPrime
}
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if self% i == 0 {
return false
}
}
return true
}
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0? 2: 3
while q <= maxQ && self% q!= 0 {
q = step(d)
d += 1
}
return q <= maxQ? [q] + (self / q).primeDecomposition(): [self]
}
}
let attractive = Array((1...).lazy.filter({ $0.isAttractive }).prefix(while: { $0 <= 120 }))
print("Attractive numbers up to and including 120: \(attractive)") | 1,124Attractive numbers
| 17swift
| mcdyk |
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email
class Gecos
def to_s
% to_a
end
end
Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do
def to_s
to_a.join(':')
end
end
jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', '[email protected]'), '/home/jsmith', '/bin/bash')
jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', '[email protected]'), '/home/jdoe', '/bin/bash')
xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', '[email protected]'), '/home/xyz', '/bin/bash')
filename = 'append.records.test'
File.open(filename, 'w') do |io|
io.puts jsmith
io.puts jdoe
end
puts
puts File.readlines(filename)
File.open(filename, 'a') do |io|
io.puts xyz
end
puts
puts File.readlines(filename) | 1,132Append a record to the end of a text file
| 14ruby
| pa9bh |
Subsets and Splits