code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use std::env; fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument"); assert_ne!(rows, 0, "rows were zero"); assert_ne!(co...
986Create a two-dimensional array at runtime
15rust
he2j2
object Array2D{ def main(args: Array[String]): Unit = { val x = Console.readInt val y = Console.readInt val a=Array.fill(x, y)(0) a(0)(0)=42 println("The number at (0, 0) is "+a(0)(0)) } }
986Create a two-dimensional array at runtime
16scala
pq5bj
def countChange(amount: Int, coins:List[Int]) = { val ways = Array.fill(amount + 1)(0) ways(0) = 1 coins.foreach (coin => for (j<-coin to amount) ways(j) = ways(j) + ways(j - coin) ) ways(amount) } countChange (15, List(1, 5, 10, 25))
989Count the coins
16scala
bxlk6
sub countSubstring { my $str = shift; my $sub = quotemeta(shift); my $count = () = $str =~ /$sub/g; return $count; } print countSubstring("the three truths","th"), "\n"; print countSubstring("ababababab","abab"), "\n";
992Count occurrences of a substring
2perl
qn5x6
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
991Count in factors
2perl
pqcb0
use HTML::Entities; sub row { my $elem = shift; my @cells = map {"<$elem>$_</$elem>"} split ',', shift; print '<tr>', @cells, "</tr>\n"; } my ($first, @rest) = map {my $x = $_; chomp $x; encode_entities $x} <STDIN>; print "<table>\n"; row @ARGV ? 'th' : 'td', $first; row 'td', $_ foreach @rest; pr...
987CSV to HTML translation
2perl
rpmgd
<?php echo substr_count(, ), PHP_EOL; echo substr_count(, ), PHP_EOL;
992Count occurrences of a substring
12php
v7o2v
import sys for n in xrange(sys.maxint): print oct(n)
993Count in octal
3python
zcptt
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
988Create a file
3python
kwlhf
f <- file("output.txt", "w") close(f) f <- file("/output.txt", "w") close(f) success <- dir.create("docs") success <- dir.create("/docs")
988Create a file
13r
rpygj
<?php $csv = <<<EOT Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! EOT;...
987CSV to HTML translation
12php
dyen8
class StdDevAccumulator def initialize @n, @sum, @sumofsquares = 0, 0.0, 0.0 end def <<(num) @n += 1 @sum += num @sumofsquares += num**2 self end def stddev Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 ) end def to_s stddev.to_s end end sd = StdDevAccumulator.new...
982Cumulative standard deviation
14ruby
mutyj
import BigInt func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt { let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count var table = [BigInt](repeating: 0, count: cycle) for x in 0..<coins.count { table[x] = 1 } var pos = coins.count for s in 1..<cents+1 { f...
989Count the coins
17swift
rp6gg
from functools import lru_cache primes = [2, 3, 5, 7, 11, 13, 17] @lru_cache(maxsize=2000) def pfactor(n): if n == 1: return [1] n2 = n for p in primes: if p <= n2: d, m = divmod(n, p) if m == 0: if d > 1: return [p] + pfacto...
991Count in factors
3python
1slpc
import Foundation print("Enter the dimensions of the array seperated by a space (width height): ") let fileHandle = NSFileHandle.fileHandleWithStandardInput() let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ") if let dims = dims where dims.count == 2...
986Create a two-dimensional array at runtime
17swift
71crq
n = 0 loop do puts % n n += 1 end for n in 0..Float::INFINITY puts n.to_s(8) end 0.upto(1/0.0) do |n| printf , n end 0.step do |n| puts format(, n) end
993Count in octal
14ruby
62a3t
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime!= 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) fo...
991Count in factors
13r
heyjj
pub struct CumulativeStandardDeviation { n: f64, sum: f64, sum_sq: f64 } impl CumulativeStandardDeviation { pub fn new() -> Self { CumulativeStandardDeviation { n: 0., sum: 0., sum_sq: 0. } } fn push(&mut self, x: f64) -> f64 { self.n...
982Cumulative standard deviation
15rust
95zmm
>>> .count() 3 >>> .count() 2
992Count occurrences of a substring
3python
sd4q9
fn main() { for i in 0..std::usize::MAX { println!("{:o}", i); } }
993Count in octal
15rust
yve68
['/', './'].each{|dir| Dir.mkdir(dir + 'docs') File.open(dir + 'output.txt', 'w') {} }
988Create a file
14ruby
pqvbh
csvtxt = '''\ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!\ ''' from...
987CSV to HTML translation
3python
719rm
count = function(haystack, needle) {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length") if (identical(v, -1L)) 0 else length(v)} print(count("hello", "l"))
992Count occurrences of a substring
13r
e82ad
Stream from 0 foreach (i => println(i.toOctalString))
993Count in octal
16scala
c4q93
use std::io::{self, Write}; use std::fs::{DirBuilder, File}; use std::path::Path; use std::{process,fmt}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME: &'static str = "docs"; fn main() { create(".").and(create("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn create<P>(root: P) ...
988Create a file
15rust
1supu
File <- "~/test.csv" Opened <- readLines(con = File) Size <- length(Opened) HTML <- "~/test.html" Table <- list() for(i in 1:Size) { Split <- unlist(strsplit(Opened[i],split = ",")) Table[i] <- paste0("<td>",Split,"</td>",collapse = "") Table[i] <- paste0("<tr>",Table[i],"</tr>") } Table[1] <- paste0("<tab...
987CSV to HTML translation
13r
5h3uy
import scala.math.sqrt object StddevCalc extends App { def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = num.div(ts.sum, num.fromInt(ts.size))
982Cumulative standard deviation
16scala
2rylb
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = o.on(, Integer, ) { |m| maximum = m } o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |...
991Count in factors
14ruby
e8vax
import java.io.File object CreateFile extends App { try { new File("output.txt").createNewFile() } catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") } try { new File(s"${File.separator}output.txt").createNewFile() } catch { case e: Exception => println(s"Exception caught: $...
988Create a file
16scala
woges
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; ...
991Count in factors
15rust
woue4
def countSubstrings str, subStr str.scan(subStr).length end p countSubstrings , p countSubstrings ,
992Count occurrences of a substring
14ruby
8tr01
import Foundation func octalSuccessor(value: String) -> String { if value.isEmpty { return "1" } else { let i = value.startIndex, j = value.endIndex.predecessor() switch (value[j]) { case "0": return value[i..<j] + "1" case "1": return value[i..<j] + "2" case "2": return va...
993Count in octal
17swift
3l1z2
object CountInFactors extends App { def primeFactors(n: Int): List[Int] = { def primeStream(s: LazyList[Int]): LazyList[Int] = { s.head #:: primeStream(s.tail filter { _ % s.head != 0 }) } val primes = primeStream(LazyList.from(2)) def factors(n: Int): List[Int] = primes.takeWh...
991Count in factors
16scala
sdgqo
fn main() { println!("{}","the three truths".matches("th").count()); println!("{}","ababababab".matches("abab").count()); }
992Count occurrences of a substring
15rust
oz783
import scala.annotation.tailrec def countSubstring(str1:String, str2:String):Int={ @tailrec def count(pos:Int, c:Int):Int={ val idx=str1 indexOf(str2, pos) if(idx == -1) c else count(idx+str2.size, c+1) } count(0,0) }
992Count occurrences of a substring
16scala
dykng
my @heading = qw(X Y Z); my $rows = 5; print '<table><thead><td>', (map { "<th>$_</th>" } @heading), "</thead><tbody>"; for (1 .. $rows) { print "<tr><th>$_</th>", (map { "<td>".int(rand(10000))."</td>" } @heading), "</tr>"; } print "</tbody></table>";
990Create an HTML table
2perl
zcetb
-- the minimal table CREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL); -- code modularity with view, we could have used a common table expression instead CREATE VIEW vteststd AS SELECT COUNT(n) AS cnt, SUM(n) AS tsum, SUM(POWER(n,2)) AS tsqr FROM teststd; -- you can of course put this code into...
982Cumulative standard deviation
19sql
5hcu3
extension BinaryInteger { @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 ...
991Count in factors
17swift
a021i
ruby csv2html.rb header
987CSV to HTML translation
14ruby
heljx
import Darwin class stdDev{ var n:Double = 0.0 var sum:Double = 0.0 var sum2:Double = 0.0 init(){ let testData:[Double] = [2,4,4,4,5,5,7,9]; for x in testData{ var a:Double = calcSd(x) println("value \(Int(x)) SD = \(a)"); } } func calcSd(x:D...
982Cumulative standard deviation
17swift
yvf6e
<?php $cols = array('', 'X', 'Y', 'Z'); $rows = 3; $html = '<html><body><table><colgroup>'; foreach($cols as $col) { $html .= '<col style= />'; } unset($col); $html .= '</colgroup><thead><tr>'; foreach($cols as $col) { $html .= ; } unset($col); $html .= '</tr></thead><tbody>'; for($r = 1; $r <= $rows; $r++) { $h...
990Create an HTML table
12php
bxck9
static INPUT: &'static str = "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his m...
987CSV to HTML translation
15rust
kw2h5
object CsvToHTML extends App { val header = <head> <title>CsvToHTML</title> <style type="text/css"> td {{background-color:#ddddff; }} thead td {{background-color:#ddffdd; text-align:center; }} </style> </head> val csv = """Character,Speech |The multitude,The messiah! Show us the messia...
987CSV to HTML translation
16scala
1s5pf
import Foundation func countSubstring(str: String, substring: String) -> Int { return str.components(separatedBy: substring).count - 1 } print(countSubstring(str: "the three truths", substring: "th")) print(countSubstring(str: "ababababab", substring: "abab"))
992Count occurrences of a substring
17swift
0fgs6
import random def rand9999(): return random.randint(1000, 9999) def tag(attr='', **kwargs): for tag, txt in kwargs.items(): return '<{tag}{attr}>{txt}</{tag}>'.format(**locals()) if __name__ == '__main__': header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n' rows = '\n'...
990Create an HTML table
3python
3lwzc
int main(){ char c; while ( (c=getchar()) != EOF ){ putchar(c); } return 0; }
994Copy stdin to stdout
5c
v702o
import 'dart:io'; void main() { var line = stdin.readLineSync(); stdout.write(line); }
994Copy stdin to stdout
18dart
yva65
def r rand(10000) end STDOUT << .tap do |html| html << [ ['X', 'Y', 'Z'], [r ,r ,r], [r ,r ,r], [r ,r ,r], [r ,r ,r] ].each_with_index do |row, index| html << html << html << row.map { |e| }.join html << end html << end
990Create an HTML table
14ruby
yvq6n
package main import ( "bufio" "io" "os" ) func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) for { b, err := r.ReadByte() if err == io.EOF { return } w.WriteByte(b) w.Flush() } }
994Copy stdin to stdout
0go
sduqa
class StdInToStdOut { static void main(args) { try (def reader = System.in.newReader()) { def line while ((line = reader.readLine()) != null) { println line } } } }
994Copy stdin to stdout
7groovy
a091p
extern crate rand; use rand::Rng; fn random_cell<R: Rng>(rng: &mut R) -> u32 {
990Create an HTML table
15rust
musya
main = interact id
994Copy stdin to stdout
8haskell
95wmo
import java.util.Scanner; public class CopyStdinToStdout { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in);) { String s; while ( (s = scanner.nextLine()).compareTo("") != 0 ) { System.out.println(s); } } ...
994Copy stdin to stdout
9java
t9kf9
process.stdin.resume(); process.stdin.pipe(process.stdout);
994Copy stdin to stdout
10javascript
mueyv
object TableGenerator extends App { val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33)) def generateTable(data: List[List[Any]]) = { <table> {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}. map(row => <tr> {row.m...
990Create an HTML table
16scala
lgocq
fun main() { var c: Int do { c = System.`in`.read() System.out.write(c) } while (c >= 0) }
994Copy stdin to stdout
11kotlin
ozg8z
lua -e 'for x in io.lines() do print(x) end'
994Copy stdin to stdout
1lua
i3rot
perl -pe ''
994Copy stdin to stdout
2perl
gbn4e
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
994Copy stdin to stdout
3python
rpdgq
Rscript -e 'cat(readLines(file("stdin")))'
994Copy stdin to stdout
13r
uj8vx
use std::io; fn main() { io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()); }
994Copy stdin to stdout
15rust
hezj2
object CopyStdinToStdout extends App { io.Source.fromInputStream(System.in).getLines().foreach(println) }
994Copy stdin to stdout
16scala
pqybj
typedef struct{ int num,den; }fraction; fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {3142857...
995Continued fraction/Arithmetic/Construct from rational number
5c
95em1
void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom) { int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 }; int64_t x, d, n = 1; int i, neg = 0; if (md <= 1) { *denom = 1; *num = (int64_t) f; return; } if (f < 0) { neg = 1; f = -f; } while (f != floor(f)) { n <<= 1; f *= 2; } d = f; for (i ...
996Convert decimal number to rational
5c
mu1ys
(defn r2cf [n d] (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d)))))) (def demo '((1 2) (3 1) (23 8) (13 11) (22 7) (-151 77) (14142 10000) (141421 100000) (1414214 1000000) (14142136 10000000) ...
995Continued fraction/Arithmetic/Construct from rational number
6clojure
uj0vi
user=> (rationalize 0.1) 1/10 user=> (rationalize 0.9054054) 4527027/5000000 user=> (rationalize 0.518518) 259259/500000 user=> (rationalize Math/PI) 3141592653589793/1000000000000000
996Convert decimal number to rational
6clojure
v7q2f
package cf import ( "fmt" "strings" )
995Continued fraction/Arithmetic/Construct from rational number
0go
e89a6
import Data.Ratio ((%)) real2cf :: (RealFrac a, Integral b) => a -> [b] real2cf x = let (i, f) = properFraction x in i: if f == 0 then [] else real2cf (1 / f) main :: IO () main = mapM_ print [ real2cf (13 % 11) , take 20 $ real2cf (sqrt 2) ]
995Continued fraction/Arithmetic/Construct from rational number
8haskell
3lbzj
import java.util.Iterator; import java.util.List; import java.util.Map; public class ConstructFromRationalNumber { private static class R2cf implements Iterator<Integer> { private int num; private int den; R2cf(int num, int den) { this.num = num; this.den = den; ...
995Continued fraction/Arithmetic/Construct from rational number
9java
i3gos
package main import ( "fmt" "math/big" ) func main() { for _, d := range []string{"0.9054054", "0.518518", "0.75"} { if r, ok := new(big.Rat).SetString(d); ok { fmt.Println(d, "=", r) } else { fmt.Println(d, "invalid decimal number") } } }
996Convert decimal number to rational
0go
a0y1f
null
995Continued fraction/Arithmetic/Construct from rational number
11kotlin
qn2x1
Number.metaClass.mixin RationalCategory [ 0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111 ].each{ printf "%30.27f%s\n", it, it as Rational }
996Convert decimal number to rational
7groovy
hefj9
Prelude> map (\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75] [67 % 74,14 % 27,3 % 4] Prelude> [0.9054054, 0.518518, 0.75] :: [Rational] [4527027 % 5000000,259259 % 500000,3 % 4] Prelude> map (fst . head . Numeric.readFloat) ["0.9054054", "0.518518", "0.75"] :: [Rational] [4527027 % 5000000,259259 % 50...
996Convert decimal number to rational
8haskell
zcht0
import org.apache.commons.math3.fraction.BigFraction; public class Test { public static void main(String[] args) { double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536}; for (double d : n) System.out.printf(...
996Convert decimal number to rational
9java
oz58d
(() => { 'use strict'; const main = () => showJSON( map(
996Convert decimal number to rational
10javascript
t9jfm
$|=1; sub rc2f { my($num, $den) = @_; return sub { return unless $den; my $q = int($num/$den); ($num, $den) = ($den, $num - $q*$den); $q; }; } sub rcshow { my $sub = shift; print "["; my $n = $sub->(); print "$n" if defined $n; print "; $n" while defined($n =...
995Continued fraction/Arithmetic/Construct from rational number
2perl
v7s20
null
996Convert decimal number to rational
11kotlin
xicws
def r2cf(n1,n2): while n2: n1, (t1, n2) = n2, divmod(n1, n2) yield t1 print(list(r2cf(1,2))) print(list(r2cf(3,1))) print(list(r2cf(23,8))) print(list(r2cf(13,11))) print(list(r2cf(22,7))) print(list(r2cf(14142,10000))) print(list(r2cf(141421,100000))) print(list(r2cf(1414214,1000...
995Continued fraction/Arithmetic/Construct from rational number
3python
uj0vd
for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do local n, d, dmax, eps = 1, 1, 1e7, 1e-15 while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end print(string.format("%15.13f
996Convert decimal number to rational
1lua
qnlx0
def r2cf(n1,n2) while n2 > 0 n1, (t1, n2) = n2, n1.divmod(n2) yield t1 end end
995Continued fraction/Arithmetic/Construct from rational number
14ruby
4ko5p
struct R2cf { n1: i64, n2: i64 }
995Continued fraction/Arithmetic/Construct from rational number
15rust
gbi4o
sub gcd { my ($m, $n) = @_; ($m, $n) = ($n, $m % $n) while $n; return $m } sub rat_machine { my $n = shift; my $denom = 1; while ($n != int $n) { $n *= 2; $denom <<= 1; } ...
996Convert decimal number to rational
2perl
2rxlf
int main() { size_t len; char src[] = ; char dst1[80], dst2[80]; char *dst3, *ref; strcpy(dst1, src); len = strlen(src); if (len >= sizeof dst2) { fputs(, stderr); exit(1); } memcpy(dst2, src, len + 1); dst3 = strdup(src); if (dst3 == NULL) { perror(); exit(1); } ref = src; memse...
997Copy a string
5c
4k05t
function asRational($val, $tolerance = 1.e-6) { if ($val == (int) $val) { return $val; } $h1=1; $h2=0; $k1=0; $k2=1; $b = 1 / $val; do { $b = 1 / $b; $a = floor($b); $aux = $h1; $h1 = $a * $h1 + $h2; $h2 = $aux; $aux = $k...
996Convert decimal number to rational
12php
sd2qs
(let [s "hello" s1 s] (println s s1))
997Copy a string
6clojure
hedjr
>>> from fractions import Fraction >>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100)) 0.9054054 67/74 0.518518 14/27 0.75 3/4 >>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d)) 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 >>>
996Convert decimal number to rational
3python
v7q29
ratio<-function(decimal){ denominator=1 while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){ denominator=denominator+1 } str=paste(decimal*denominator,"/",sep="") str=paste(str,denominator,sep="") return(str) }
996Convert decimal number to rational
13r
95amg
> '0.9054054 0.518518 0.75'.split.each { |d| puts % [d, Rational(d)] } 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 => [, , ]
996Convert decimal number to rational
14ruby
5h0uj
extern crate rand; extern crate num; use num::Integer; use rand::Rng; fn decimal_to_rational (mut n: f64) -> [isize;2] {
996Convert decimal number to rational
15rust
4k85u
import org.apache.commons.math3.fraction.BigFraction object Number2Fraction extends App { val n = Array(0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536) for (d <- n) println(f"$d%-12s: ${new BigFraction(d, 0.00000002D, 10000)}%s") }
996Convert decimal number to rational
16scala
71nr9
char* seconds2string(unsigned long seconds) { int i; const unsigned long s = 1; const unsigned long m = 60 * s; const unsigned long h = 60 * m; const unsigned long d = 24 * h; const unsigned long w = 7 * d; const unsigned long coeff[5] = { w, d, h, m, s }; const char units[5][4] = {...
998Convert seconds to compound duration
5c
5hquk
type eatable interface { eat() }
999Constrained genericity
0go
2ral7
class Eatable a where eat :: a -> String
999Constrained genericity
8haskell
a0z1g
package main import ( "fmt" "rcu" ) const LIMIT = 999999 var primes = rcu.Primes(LIMIT) func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) || (di...
1,000Consecutive primes with ascending or descending differences
0go
bxnkh
typedef double (*coeff_func)(unsigned n); double calc(coeff_func f_a, coeff_func f_b, unsigned expansions) { double a, b, r; a = b = r = 0.0; unsigned i; for (i = expansions; i > 0; i--) { a = f_a(i); b = f_b(i); r = b / (a + r); } a = f_a(0); return a + r; } double sqrt2_a(unsigned n) { return n ? ...
1,001Continued fraction
5c
rpqg7
(require '[clojure.string:as string]) (def seconds-in-minute 60) (def seconds-in-hour (* 60 seconds-in-minute)) (def seconds-in-day (* 24 seconds-in-hour)) (def seconds-in-week (* 7 seconds-in-day)) (defn seconds->duration [seconds] (let [weeks ((juxt quot rem) seconds seconds-in-week) wk (first week...
998Convert seconds to compound duration
6clojure
jai7m
interface Eatable { void eat(); }
999Constrained genericity
9java
jao7c
null
999Constrained genericity
11kotlin
5hxua
import Data.Numbers.Primes (primes) consecutives equiv = filter ((> 1) . length) . go [] where go r [] = [r] go [] (h: t) = go [h] t go (y: ys) (h: t) | y `equiv` h = go (h: y: ys) t | otherwise = (y: ys): go [h] t maximumBy g (h: t) = foldr f h t where f r x = if g r < g x then x el...
1,000Consecutive primes with ascending or descending differences
8haskell
dyun4
function findcps(primelist, fcmp) local currlist = {primelist[1]} local longlist, prevdiff = currlist, 0 for i = 2, #primelist do local diff = primelist[i] - primelist[i-1] if fcmp(diff, prevdiff) then currlist[#currlist+1] = primelist[i] if #currlist > #longlist then longlist = currli...
1,000Consecutive primes with ascending or descending differences
1lua
e8zac