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('\...
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) ...
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....
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...
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, ca...
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], ...
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', 'dir...
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[$_] * $o...
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 = {} = {...
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.toDo...
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...
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] = $s...
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) ...
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 ...
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 IllegalArg...
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...
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)...
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) ...
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; impor...
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 __getite...
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 ...
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 ...
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(t...
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 el...
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; ...
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....
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(",") ...
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 } ...
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 == ...
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 ...
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 :...
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); } im...
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) =...
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) ...
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 (ifac...
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....
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 ...
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(val...
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 enumera...
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) ...
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)...
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,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004...
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] } retur...
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 = se...
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] + makePermuta...
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='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='j...
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...
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(_...
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) ...
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(s...
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 100...
1,132Append a record to the end of a text file
14ruby
pa9bh