code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
} | 1,136Apply a callback to an array
| 0go
| mc1yi |
fun main(a: Array<String>) {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
with(map) {
entries.forEach { println("key = ${it.key}, value = ${it.value}") }
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}
} | 1,134Associative array/Iteration
| 11kotlin
| hbzj3 |
fun main(args: Array<String>) {
val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
println("average =%f".format(nums.average()))
} | 1,133Averages/Arithmetic mean
| 11kotlin
| 8ig0q |
public class BalancedBrackets {
public static boolean hasBalancedBrackets(String str) {
int brackets = 0;
for (char ch: str.toCharArray()) {
if (ch == '[') {
brackets++;
} else if (ch == ']') {
brackets--;
} else {
return false; | 1,129Balanced brackets
| 9java
| 8ih06 |
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Result;
use std::io::Write;
use std::path::Path; | 1,132Append a record to the end of a text file
| 15rust
| 1ecpu |
import java.io.{File, FileWriter, IOException}
import scala.io.Source
object RecordAppender extends App {
val rawDataIt = Source.fromString(rawData).getLines()
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
def rawData =
"""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""".stripMargin
case class Record(account: String,
password: String,
uid: Int,
gid: Int,
gecos: Array[String],
directory: String,
shell: String) {
def asLine: String = s"$account:$password:$uid:$gid:${gecos.mkString(",")}:$directory:$shell\n"
}
object Record {
def apply(line: String): Record = {
val token = line.trim.split(":")
require((token != null) || (token.length == 7))
this(token(0).trim,
token(1).trim,
Integer.parseInt(token(2).trim),
Integer.parseInt(token(3).trim),
token(4).split(","),
token(5).trim,
token(6).trim)
}
}
try {
val file = File.createTempFile("_rosetta", ".passwd")
using(new FileWriter(file))(writer => rawDataIt.take(2).foreach(line => writer.write(Record(line).asLine)))
writeStringToFile(file, Record(rawDataIt.next()).asLine, appending = true) | 1,132Append a record to the end of a text file
| 16scala
| wqves |
[1,2,3,4].each { println it } | 1,136Apply a callback to an array
| 7groovy
| t3jfh |
let square x = x*x
let values = [1..10]
map square values | 1,136Apply a callback to an array
| 8haskell
| kpth0 |
function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
return a.join('')
}
function isBalanced(str) {
var a = str, b
do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
return !a
}
var M = 20
while (M-- > 0) {
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
} | 1,129Balanced brackets
| 10javascript
| fzadg |
-- setup
CREATE TABLE averages (val INTEGER);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (4);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (5);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (6);
-- find the mode
WITH
counts AS
(
SELECT
val,
COUNT(*) AS num
FROM
averages
GROUP BY
val
)
SELECT
val AS mode_val
FROM
counts
WHERE
num IN (SELECT MAX(num) FROM counts); | 1,118Averages/Mode
| 19sql
| pepb1 |
main() {
var rosettaCode = { | 1,137Associative array/Creation
| 18dart
| xs9wh |
null | 1,118Averages/Mode
| 17swift
| 4745g |
sub A
{
my $a = 0;
$a += $_ for @_;
return $a / @_;
}
sub G
{
my $p = 1;
$p *= $_ for @_;
return $p**(1/@_);
}
sub H
{
my $h = 0;
$h += 1/$_ for @_;
return @_/$h;
}
my @ints = (1..10);
my $a = A(@ints);
my $g = G(@ints);
my $h = H(@ints);
print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $h; | 1,117Averages/Pythagorean means
| 2perl
| 0i8s4 |
public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
} | 1,136Apply a callback to an array
| 9java
| 4r858 |
local t = {
["foo"] = "bar",
["baz"] = 6,
fortytwo = 7
}
for key,val in pairs(t) do
print(string.format("%s:%s", key, val))
end | 1,134Associative array/Iteration
| 1lua
| kp3h2 |
from itertools import chain, count, cycle, islice, accumulate
def factors(n):
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n
yield d
if n > 1: yield n,
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r
def antiprimes():
mx = 0
yield 1
for c in count(2,2):
if c >= 58: break
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
for c in count(60,30):
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
if __name__ == '__main__':
print(*islice(antiprimes(), 40))) | 1,135Anti-primes
| 3python
| 1eypc |
function map(a, func) {
var ret = [];
for (var i = 0; i < a.length; i++) {
ret[i] = func(a[i]);
}
return ret;
}
map([1, 2, 3, 4, 5], function(v) { return v * v; }); | 1,136Apply a callback to an array
| 10javascript
| hbfjh |
sub median {
my @a = sort {$a <=> $b} @_;
return ($a[$
} | 1,125Averages/Median
| 2perl
| nfwiw |
<?php
function ArithmeticMean(array $values)
{
return array_sum($values) / count($values);
}
function GeometricMean(array $values)
{
return array_product($values) ** (1 / count($values));
}
function HarmonicMean(array $values)
{
$sum = 0;
foreach ($values as $value) {
$sum += 1 / $value;
}
return count($values) / $sum;
}
$values = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo . ArithmeticMean($values) . ;
echo . GeometricMean($values) . ;
echo . HarmonicMean($values) . ; | 1,117Averages/Pythagorean means
| 12php
| 5r4us |
import java.util.Random
fun isBalanced(s: String): Boolean {
if (s.isEmpty()) return true
var countLeft = 0 | 1,129Balanced brackets
| 11kotlin
| wq4ek |
max_divisors <- 0
findFactors <- function(x){
myseq <- seq(x)
myseq[(x%% myseq) == 0]
}
antiprimes <- vector()
x <- 1
n <- 1
while(length(antiprimes) < 20){
y <- findFactors(x)
if (length(y) > max_divisors){
antiprimes <- c(antiprimes, x)
max_divisors <- length(y)
n <- n + 1
}
x <- x + 1
}
antiprimes | 1,135Anti-primes
| 13r
| hbtjj |
function median($arr)
{
sort($arr);
$count = count($arr);
$middleval = floor(($count-1)/2);
if ($count % 2) {
$median = $arr[$middleval];
} else {
$low = $arr[$middleval];
$high = $arr[$middleval+1];
$median = (($low+$high)/2);
}
return $median;
}
echo median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . ;
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . ; | 1,125Averages/Median
| 12php
| 7hlrp |
fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) | 1,136Apply a callback to an array
| 11kotlin
| lvwcp |
function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
table.foreach(numlist,function(i,v) num=num+v end)
return num / #numlist
end
print (mean({3,1,4,1,5,9})) | 1,133Averages/Arithmetic mean
| 1lua
| onr8h |
require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
anti_primes = Enumerator.new do |y|
max = 0
y << 1
2.step(nil,2) do |candidate|
num = num_divisors(candidate)
if num > max
y << candidate
max = num
end
end
end
puts anti_primes.take(20).join() | 1,135Anti-primes
| 14ruby
| ex9ax |
function isBalanced(s) | 1,129Balanced brackets
| 1lua
| xsgwz |
fn count_divisors(n: u64) -> usize {
if n < 2 {
return 1;
}
2 + (2..=(n / 2)).filter(|i| n% i == 0).count()
}
fn main() {
println!("The first 20 anti-primes are:");
(1..)
.scan(0, |max, n| {
let d = count_divisors(n);
Some(if d > *max {
*max = d;
Some(n)
} else {
None
})
})
.flatten()
.take(20)
.for_each(|n| print!("{} ", n));
println!();
} | 1,135Anti-primes
| 15rust
| wqce4 |
def factorCount(num: Int): Int = Iterator.range(1, num/2 + 1).count(num%_ == 0) + 1
def antiPrimes: LazyList[Int] = LazyList.iterate((1: Int, 1: Int)){case (n, facs) => Iterator.from(n + 1).map(i => (i, factorCount(i))).dropWhile(_._2 <= facs).next}.map(_._1) | 1,135Anti-primes
| 16scala
| s8vqo |
myArray = {1, 2, 3, 4, 5} | 1,136Apply a callback to an array
| 1lua
| 2uxl3 |
def median(aray):
srtd = sorted(aray)
alen = len(srtd)
return 0.5*( srtd[(alen-1)
a = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a)
a = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print a, median(a) | 1,125Averages/Median
| 3python
| dtxn1 |
omedian <- function(v) {
if ( length(v) < 1 )
NA
else {
sv <- sort(v)
l <- length(sv)
if ( l %% 2 == 0 )
(sv[floor(l/2)+1] + sv[floor(l/2)])/2
else
sv[floor(l/2)+1]
}
}
a <- c(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)
b <- c(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)
print(median(a))
print(omedian(a))
print(median(b))
print(omedian(b)) | 1,125Averages/Median
| 13r
| 8i10x |
from operator import mul
from functools import reduce
def amean(num):
return sum(num) / len(num)
def gmean(num):
return reduce(mul, num, 1)**(1 / len(num))
def hmean(num):
return len(num) / sum(1 / n for n in num)
numbers = range(1, 11)
a, g, h = amean(numbers), gmean(numbers), hmean(numbers)
print(a, g, h)
assert a >= g >= h | 1,117Averages/Pythagorean means
| 3python
| 8no0o |
extension BinaryInteger {
@inlinable
public func countDivisors() -> Int {
var workingN = self
var count = 1
while workingN & 1 == 0 {
workingN >>= 1
count += 1
}
var d = Self(3)
while d * d <= workingN {
var (quo, rem) = workingN.quotientAndRemainder(dividingBy: d)
if rem == 0 {
var dc = 0
while rem == 0 {
dc += count
workingN = quo
(quo, rem) = workingN.quotientAndRemainder(dividingBy: d)
}
count += dc
}
d += 2
}
return workingN!= 1? count * 2: count
}
}
var antiPrimes = [Int]()
var maxDivs = 0
for n in 1... {
guard antiPrimes.count < 20 else {
break
}
let divs = n.countDivisors()
if maxDivs < divs {
maxDivs = divs
antiPrimes.append(n)
}
}
print("First 20 anti-primes are \(Array(antiPrimes))") | 1,135Anti-primes
| 17swift
| awm1i |
x <- 1:10 | 1,117Averages/Pythagorean means
| 13r
| x0qw2 |
use strict;
my %pairs = ( "hello" => 13,
"world" => 31,
"!" => 71 );
while ( my ($k, $v) = each %pairs) {
print "(k,v) = ($k, $v)\n";
}
foreach my $key ( keys %pairs ) {
print "key = $key, value = $pairs{$key}\n";
}
while ( my $key = each %pairs) {
print "key = $key, value = $pairs{$key}\n";
}
foreach my $val ( values %pairs ) {
print "value = $val\n";
} | 1,134Associative array/Iteration
| 2perl
| z6btb |
def median(ary)
return nil if ary.empty?
mid, rem = ary.length.divmod(2)
if rem == 0
ary.sort[mid-1,2].inject(:+) / 2.0
else
ary.sort[mid]
end
end
p median([])
p median([5,3,4])
p median([5,4,2,3])
p median([3,4,1,-8.4,7.2,4,1,1.2]) | 1,125Averages/Median
| 14ruby
| t3sf2 |
<?php
$pairs = array( => 1,
=> 2,
=> 3 );
foreach($pairs as $k => $v) {
echo ;
}
foreach(array_keys($pairs) as $key) {
echo ;
}
foreach($pairs as $value) {
echo ;
}
?> | 1,134Associative array/Iteration
| 12php
| b16k9 |
fn median(mut xs: Vec<f64>) -> f64 { | 1,125Averages/Median
| 15rust
| z60to |
def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
import n._
val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
} | 1,125Averages/Median
| 16scala
| y9i63 |
class Array
def arithmetic_mean
inject(0.0,:+) / length
end
def geometric_mean
inject(:*) ** (1.0 / length)
end
def harmonic_mean
length / inject(0.0) {|s, m| s + 1.0/m}
end
end
class Range
def method_missing(m, *args)
case m
when /_mean$/ then to_a.send(m)
else super
end
end
end
p a = (1..10).arithmetic_mean
p g = (1..10).geometric_mean
p h = (1..10).harmonic_mean
p g.between?(h, a) | 1,117Averages/Pythagorean means
| 14ruby
| ifnoh |
null | 1,137Associative array/Creation
| 0go
| g784n |
fn main() {
let mut sum = 0.0;
let mut prod = 1;
let mut recsum = 0.0;
for i in 1..11{
sum += i as f32;
prod *= i;
recsum += 1.0/(i as f32);
}
let avg = sum/10.0;
let gmean = (prod as f32).powf(0.1);
let hmean = 10.0/recsum;
println!("Average: {}, Geometric mean: {}, Harmonic mean: {}", avg, gmean, hmean);
assert!( ( (avg >= gmean) && (gmean >= hmean) ), "Incorrect calculation");
} | 1,117Averages/Pythagorean means
| 15rust
| ntdi4 |
def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble
def geometricMean(n: Seq[Int]) = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.toDouble)
def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum
var nums = 1 to 10
var a = arithmeticMean(nums)
var g = geometricMean(nums)
var h = harmonicMean(nums)
println("Arithmetic mean " + a)
println("Geometric mean " + g)
println("Harmonic mean " + h)
assert(a >= g && g >= h) | 1,117Averages/Pythagorean means
| 16scala
| t6zfb |
myDict = { : 13,
: 31,
: 71 }
for key, value in myDict.items():
print (% (key, value))
for key in myDict:
print (% key)
for key in myDict.keys():
print (% key)
for value in myDict.values():
print (% value) | 1,134Associative array/Iteration
| 3python
| 3ypzc |
map = [:]
map[7] = 7
map['foo'] = 'foovalue'
map.put('bar', 'barvalue')
map.moo = 'moovalue'
assert 7 == map[7]
assert 'foovalue' == map.foo
assert 'barvalue' == map['bar']
assert 'moovalue' == map.get('moo') | 1,137Associative array/Creation
| 7groovy
| 2uwlv |
> env <- new.env()
> env[["x"]] <- 123
> env[["x"]] | 1,134Associative array/Iteration
| 13r
| dtjnt |
import Data.Map
dict = fromList [("key1","val1"), ("key2","val2")]
ans = Data.Map.lookup "key2" dict | 1,137Associative array/Creation
| 8haskell
| s8lqk |
sub avg {
@_ or return 0;
my $sum = 0;
$sum += $_ foreach @_;
return $sum/@_;
}
print avg(qw(3 1 4 1 5 9)), "\n"; | 1,133Averages/Arithmetic mean
| 2perl
| 4rn5d |
--setup
CREATE TABLE averages (val INTEGER);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (4);
INSERT INTO averages VALUES (5);
INSERT INTO averages VALUES (6);
INSERT INTO averages VALUES (7);
INSERT INTO averages VALUES (8);
INSERT INTO averages VALUES (9);
INSERT INTO averages VALUES (10);
-- calculate means
SELECT
1/avg(1/val) AS harm,
avg(val) AS arith
FROM
averages; | 1,117Averages/Pythagorean means
| 19sql
| 69y3m |
my_dict = { => 13,
=> 31,
=> 71 }
my_dict.each {|key, value| puts }
my_dict.each_pair {|key, value| puts }
my_dict.each_key {|key| puts }
my_dict.each_value {|value| puts } | 1,134Associative array/Iteration
| 14ruby
| y9a6n |
use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
olympic_medals.insert("United States", (1072, 859, 749));
olympic_medals.insert("Soviet Union", (473, 376, 355));
olympic_medals.insert("Great Britain", (246, 276, 284));
olympic_medals.insert("Germany", (252, 260, 270));
for (country, medals) in olympic_medals {
println!("{} has had {} gold medals, {} silver medals, and {} bronze medals",
country, medals.0, medals.1, medals.2);
}
} | 1,134Associative array/Iteration
| 15rust
| mceya |
$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), ;
else
echo ; | 1,133Averages/Arithmetic mean
| 12php
| id7ov |
val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
println(f"Key->Value: ${m.mkString(", ")}%s")
println(f"Pairs: ${m.toList.mkString(", ")}%s")
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s") | 1,134Associative array/Iteration
| 16scala
| lvqcq |
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("foo", 5);
map.put("bar", 10);
map.put("baz", 15);
map.put("foo", 6); | 1,137Associative array/Creation
| 9java
| 1e3p2 |
my @a = (1, 2, 3, 4, 5);
sub mycallback {
return 2 * shift;
}
for (my $i = 0; $i < scalar @a; $i++) {
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}
my @b = map mycallback($_), @a;
my @c = map { $_ * 2 } @a;
my $func = \&mycallback;
my @d = map $func->($_), @a;
my @e = grep { $_ % 2 == 0 } @a; | 1,136Apply a callback to an array
| 2perl
| q0lx6 |
sub generate {
my $n = shift;
my $str = '[' x $n;
substr($str, rand($n + $_), 0) = ']' for 1..$n;
return $str;
}
sub balanced {
shift =~ /^ (\[ (?1)* \])* $/x;
}
for (0..8) {
my $input = generate($_);
print balanced($input) ? " ok:" : "bad:", " '$input'\n";
} | 1,129Balanced brackets
| 2perl
| lvic5 |
var assoc = {};
assoc['foo'] = 'bar';
assoc['another-key'] = 3; | 1,137Associative array/Creation
| 10javascript
| q0cx8 |
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map(, $a);
print_r($b); | 1,136Apply a callback to an array
| 12php
| v5q2v |
let myMap = [
"hello": 13,
"world": 31,
"!" : 71 ] | 1,134Associative array/Iteration
| 17swift
| 6m13j |
from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20])) | 1,133Averages/Arithmetic mean
| 3python
| g7d4h |
<?php
function bgenerate ($n) {
if ($n==0) return '';
$s = str_repeat('[', $n) . str_repeat(']', $n);
return str_shuffle($s);
}
function printbool($b) {return ($b)? 'OK' : 'NOT OK';}
function isbalanced($s) {
$bal = 0;
for ($i=0; $i < strlen($s); $i++) {
$ch = substr($s, $i, 1);
if ($ch == '[') {
$bal++;
} else {
$bal--;
}
if ($bal < 0) return false;
}
return ($bal == 0);
}
$tests = array(0, 2,2,2, 3,3,3, 4,4,4,4);
foreach ($tests as $v) {
$s = bgenerate($v);
printf(, $s, printbool(isbalanced($s)), PHP_EOL);
} | 1,129Balanced brackets
| 12php
| q0rx3 |
fun main(args: Array<String>) { | 1,137Associative array/Creation
| 11kotlin
| jkn7r |
omean <- function(v) {
m <- mean(v)
ifelse(is.na(m), 0, m)
} | 1,133Averages/Arithmetic mean
| 13r
| v5827 |
def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers) | 1,136Apply a callback to an array
| 3python
| s82q9 |
cube <- function(x) x*x*x
elements <- 1:5
cubes <- cube(elements) | 1,136Apply a callback to an array
| 13r
| exmad |
def mean(nums)
nums.sum(0.0) / nums.size
end
nums = [3, 1, 4, 1, 5, 9]
nums.size.downto(0) do |i|
ary = nums[0,i]
puts
end | 1,133Averages/Arithmetic mean
| 14ruby
| 7htri |
>>> def gen(N):
... txt = ['[', ']'] * N
... random.shuffle( txt )
... return ''.join(txt)
...
>>> def balanced(txt):
... braced = 0
... for ch in txt:
... if ch == '[': braced += 1
... if ch == ']':
... braced -= 1
... if braced < 0: return False
... return braced == 0
...
>>> for txt in (gen(N) for N in range(10)):
... print (% (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'[]' is balanced
'[][]' is balanced
'][[[]]' is not balanced
'[]][[][]' is not balanced
'[][[][]]][' is not balanced
'][]][][[]][[' is not balanced
'[[]]]]][]][[[[' is not balanced
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced | 1,129Balanced brackets
| 3python
| 2unlz |
fn sum(arr: &[f64]) -> f64 {
arr.iter().fold(0.0, |p,&q| p + q)
}
fn mean(arr: &[f64]) -> f64 {
sum(arr) / arr.len() as f64
}
fn main() {
let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0];
println!("mean of {:?}: {:?}", v, mean(v));
let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));
} | 1,133Averages/Arithmetic mean
| 15rust
| jkz72 |
def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size | 1,133Averages/Arithmetic mean
| 16scala
| b1yk6 |
hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
hash[ "key-3" ] = {} | 1,137Associative array/Creation
| 1lua
| hbdj8 |
balanced <- function(str){
str <- strsplit(str, "")[[1]]
str <- ifelse(str=='[', 1, -1)
all(cumsum(str) >= 0) && sum(str) == 0
} | 1,129Balanced brackets
| 13r
| mc0y4 |
for i in [1,2,3,4,5] do
puts i**2
end | 1,136Apply a callback to an array
| 14ruby
| 8iu01 |
fn echo(n: &i32) {
println!("{}", n);
}
fn main() {
let a: [i32; 5];
a = [1, 2, 3, 4, 5];
let _: Vec<_> = a.into_iter().map(echo).collect();
} | 1,136Apply a callback to an array
| 15rust
| on583 |
val l = List(1,2,3,4)
l.foreach {i => println(i)} | 1,136Apply a callback to an array
| 16scala
| dtrng |
CREATE TABLE ( INTEGER);
INSERT INTO SELECT rownum FROM tab;
SELECT SUM()/COUNT(*) FROM ; | 1,133Averages/Arithmetic mean
| 19sql
| awc1t |
func meanDoubles(s: [Double]) -> Double {
return s.reduce(0, +) / Double(s.count)
}
func meanInts(s: [Int]) -> Double {
return meanDoubles(s.map{Double($0)})
} | 1,133Averages/Arithmetic mean
| 17swift
| rjfgg |
re = /\A
(?<bb>
\[
\g<bb>*
\]
)*
\z/x
10.times do |i|
s = (%w{[ ]} * i).shuffle.join
puts (s =~ re? : ) + s
end
[, , ].each do |s|
t = s.gsub(/[^\[\]]/, )
puts (t =~ re? : ) + s
end | 1,129Balanced brackets
| 14ruby
| u4fvz |
function mean(numbersArr)
{
let arrLen = numbersArr.length;
if (arrLen > 0) {
let sum: number = 0;
for (let i of numbersArr) {
sum += i;
}
return sum/arrLen;
}
else return "Not defined";
}
alert( mean( [1,2,3,4,5] ) );
alert( mean( [] ) ); | 1,133Averages/Arithmetic mean
| 20typescript
| 0o4s3 |
extern crate rand;
trait Balanced { | 1,129Balanced brackets
| 15rust
| 5gtuq |
func square(n: Int) -> Int {
return n * n
}
let numbers = [1, 3, 5, 7]
let squares1a = numbers.map(square) | 1,136Apply a callback to an array
| 17swift
| 0ovs6 |
import scala.collection.mutable.ListBuffer
import scala.util.Random
object BalancedBrackets extends App {
val random = new Random()
def generateRandom: List[String] = {
import scala.util.Random._
val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_)
(1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList
}
def generate(n: Int): List[String] = {
val base = "["*n+"]"*n
var lb = ListBuffer[String]()
base.permutations.foreach(s=>lb+=s)
lb.toList.sorted
}
def checkBalance(brackets: String):Boolean = {
def balI(brackets: String, depth: Int):Boolean = {
if (brackets == "") depth == 0
else brackets(0) match {
case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1))
case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1))
case _ => false
}
}
balI(brackets, 0)
}
println("arbitrary random order:")
generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
println("\n"+"check all permutations of given length:")
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
} | 1,129Balanced brackets
| 16scala
| rj6gn |
my %hash = (
key1 => 'val1',
'key-2' => 2,
three => -238.83,
4 => 'val3',
);
my %hash = (
'key1', 'val1',
'key-2', 2,
'three', -238.83,
4, 'val3',
); | 1,137Associative array/Creation
| 2perl
| t37fg |
import Foundation
func isBal(str: String) -> Bool {
var count = 0
return!str.characters.contains { ($0 == "[" ? ++count: --count) < 0 } && count == 0
} | 1,129Balanced brackets
| 17swift
| v5d2r |
$array = array();
$array = [];
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']);
echo($array['moo']);
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo']));
echo(array_key_exists('foo', $array)); | 1,137Associative array/Creation
| 12php
| kpfhv |
null | 1,129Balanced brackets
| 20typescript
| ex5aq |
hash = dict()
hash = dict(red=, green=, blue=)
hash = { 'key1':1, 'key2':2, }
value = hash[key] | 1,137Associative array/Creation
| 3python
| z6jtt |
> env <- new.env()
> env[["x"]] <- 123
> env[["x"]] | 1,137Associative array/Creation
| 13r
| nf4i2 |
hash={}
hash[666]='devil'
hash[777]
hash[666] | 1,137Associative array/Creation
| 14ruby
| 6mk3t |
use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
olympic_medals.insert("United States", (1072, 859, 749));
olympic_medals.insert("Soviet Union", (473, 376, 355));
olympic_medals.insert("Great Britain", (246, 276, 284));
olympic_medals.insert("Germany", (252, 260, 270));
println!("{:?}", olympic_medals);
} | 1,137Associative array/Creation
| 15rust
| y9b68 |
null | 1,137Associative array/Creation
| 16scala
| c2a93 |
REM CREATE a TABLE TO associate KEYS WITH VALUES
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
REM INSERT a KEY VALUE Pair
INSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');.
REM Retrieve a KEY VALUE pair
SELECT aa.value_column FROM associative_array aa WHERE aa.key_column = 'KEY'; | 1,137Associative array/Creation
| 19sql
| v5x2y |
null | 1,137Associative array/Creation
| 17swift
| 3yhz2 |
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf(, x);
return -1;
}
return fib_i(x);
}
long fib_i(long n)
{
printf();
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf(, x, fib(x));
printf();
fib_i(3);
return 0;
} | 1,138Anonymous recursion
| 5c
| v5w2o |
const char *freq = ;
int char_to_idx[128];
struct word {
const char *w;
struct word *next;
};
union node {
union node *down[10];
struct word *list[10];
};
int deranged(const char *s1, const char *s2)
{
int i;
for (i = 0; s1[i]; i++)
if (s1[i] == s2[i]) return 0;
return 1;
}
int count_letters(const char *s, unsigned char *c)
{
int i, len;
memset(c, 0, 26);
for (len = i = 0; s[i]; i++) {
if (s[i] < 'a' || s[i] > 'z')
return 0;
len++, c[char_to_idx[(unsigned char)s[i]]]++;
}
return len;
}
const char * insert(union node *root, const char *s, unsigned char *cnt)
{
int i;
union node *n;
struct word *v, *w = 0;
for (i = 0; i < 25; i++, root = n) {
if (!(n = root->down[cnt[i]]))
root->down[cnt[i]] = n = calloc(1, sizeof(union node));
}
w = malloc(sizeof(struct word));
w->w = s;
w->next = root->list[cnt[25]];
root->list[cnt[25]] = w;
for (v = w->next; v; v = v->next) {
if (deranged(w->w, v->w))
return v->w;
}
return 0;
}
int main(int c, char **v)
{
int i, j = 0;
char *words;
struct stat st;
int fd = open(c < 2 ? : v[1], O_RDONLY);
if (fstat(fd, &st) < 0) return 1;
words = malloc(st.st_size);
read(fd, words, st.st_size);
close(fd);
union node root = {{0}};
unsigned char cnt[26];
int best_len = 0;
const char *b1, *b2;
for (i = 0; freq[i]; i++)
char_to_idx[(unsigned char)freq[i]] = i;
for (i = j = 0; i < st.st_size; i++) {
if (words[i] != '\n') continue;
words[i] = '\0';
if (i - j > best_len) {
count_letters(words + j, cnt);
const char *match = insert(&root, words + j, cnt);
if (match) {
best_len = i - j;
b1 = words + j;
b2 = match;
}
}
j = ++i;
}
if (best_len) printf(, b1, b2);
return 0;
} | 1,139Anagrams/Deranged anagrams
| 5c
| 9lbm1 |
const gchar *hello = ;
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), );
g_signal_connect(G_OBJECT(win), , gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, );
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), , G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
} | 1,140Animation
| 5c
| mchys |
(defn fib [n]
(when (neg? n)
(throw (new IllegalArgumentException "n should be > 0")))
(loop [n n, v1 1, v2 1]
(if (< n 2)
v2
(recur (dec n) v2 (+ v1 v2))))) | 1,138Anonymous recursion
| 6clojure
| rj8g2 |
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a += 6400;
while (a >= 6400) a -= 6400;
return a;
}
double normalize2rad(double a) {
while (a < 0) a += TWO_PI;
while (a >= TWO_PI) a -= TWO_PI;
return a;
}
double deg2grad(double a) {return a * 10 / 9;}
double deg2mil(double a) {return a * 160 / 9;}
double deg2rad(double a) {return a * PI / 180;}
double grad2deg(double a) {return a * 9 / 10;}
double grad2mil(double a) {return a * 16;}
double grad2rad(double a) {return a * PI / 200;}
double mil2deg(double a) {return a * 9 / 160;}
double mil2grad(double a) {return a / 16;}
double mil2rad(double a) {return a * PI / 3200;}
double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;} | 1,141Angles (geometric), normalization and conversion
| 5c
| 4rw5t |
(->> (slurp "unixdict.txt")
(re-seq #"\w+")
(group-by sort)
vals
(filter second)
(remove #(some true? (apply map = %)))
(sort-by #(count (first %)))
last
prn) | 1,139Anagrams/Deranged anagrams
| 6clojure
| u4wvi |
(import '[javax.swing JFrame JLabel])
(import '[java.awt.event MouseAdapter])
(def text "Hello World! ")
(def text-ct (count text))
(def rotations
(vec
(take text-ct
(map #(apply str %)
(partition text-ct 1 (cycle text))))))
(def pos (atom 0))
(def dir (atom 1))
(def label (JLabel. text))
(.addMouseListener label
(proxy [MouseAdapter] []
(mouseClicked [evt] (swap! dir -))))
(defn animator []
(while true
(Thread/sleep 100)
(swap! pos #(-> % (+ @dir) (mod text-ct)))
(.setText label (rotations @pos))))
(doto (JFrame.)
(.add label)
(.pack)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))
(future-call animator) | 1,140Animation
| 6clojure
| v5a2f |
import 'package:flutter/material.dart';
import 'dart:async' show Timer;
void main() {
var timer = const Duration( milliseconds: 75 ); | 1,140Animation
| 18dart
| fz5dz |