code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
<?php function a() { static $i = 0; print ++$i . ; a(); } a();
841Find limit of recursion
12php
qzax3
int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf(, base); for (i = 0; i < count; i++) { int t = turn(base, i); printf(, t); } printf(); } void turnCount(int base, int count) { int *cnt = calloc(base, sizeof(int)); int i, minTurn, maxTurn, portion; if (NULL == cnt) { printf(); return; } for (i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } minTurn = INT_MAX; maxTurn = INT_MIN; portion = 0; for (i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(, base); if (0 == minTurn) { printf(, portion); } else if (minTurn == maxTurn) { printf(, minTurn); } else { printf(, minTurn, maxTurn); } free(cnt); } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf(); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
856Fairshare between two and more
5c
35kza
max_it = 13 max_it_j = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 a = 0.0 print for i in range(2, max_it + 1): a = a1 + (a1 - a2) / d1 for j in range(1, max_it_j + 1): x = 0.0 y = 0.0 for k in range(1, (1 << i) + 1): y = 1.0 - 2.0 * y * x x = a - x * x a = a - x / y d = (a1 - a2) / (a - a1) print(.format(i, d)) d1 = d a2 = a1 a1 = a
848Feigenbaum constant calculation
3python
s3jq9
fn main() { let exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"]; let filenames = [ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", ]; println!("extenstions: {:?}\n", exts); for filename in filenames.iter() { let check = exts.iter().any(|ext| { filename .to_lowercase() .ends_with(&format!(".{}", ext.to_lowercase())) }); println!("{:20} {}", filename, check); } }
847File extension is in extensions list
15rust
wfre4
def isExt(fileName: String, extensions: List[String]): Boolean = { extensions.map { _.toLowerCase }.exists { fileName.toLowerCase endsWith "." + _ } }
847File extension is in extensions list
16scala
s3hqo
file.info(filename)$mtime shell("copy /b /v filename +,,>nul") shell("touch -m filename")
844File modification time
13r
rwlgj
package main import "fmt" func main() { for i := 1; i <= 100; i++ { switch { case i%15==0: fmt.Println("FizzBuzz") case i%3==0: fmt.Println("Fizz") case i%5==0: fmt.Println("Buzz") default: fmt.Println(i) } } }
835FizzBuzz
0go
d2zne
package main import ( "fmt" "math" )
851Fibonacci word
0go
edva6
package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() { line := s.Text() switch { case line == "": continue case line[0] != '>': if !headerFound { fmt.Println("missing header") return } fmt.Print(line) case headerFound: fmt.Println() fallthrough default: fmt.Printf("%s: ", line[1:]) headerFound = true } } if headerFound { fmt.Println() } if err := s.Err(); err != nil { fmt.Println(err) } }
854FASTA format
0go
8y40g
void farey(int n) { typedef struct { int d, n; } frac; frac f1 = {0, 1}, f2 = {1, n}, t; int k; printf(, 0, 1, 1, n); while (f2.n > 1) { k = (n + f1.n) / f2.n; t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n }; printf(, f2.d, f2.n); } putchar('\n'); } typedef unsigned long long ull; ull *cache; size_t ccap; ull farey_len(int n) { if (n >= ccap) { size_t old = ccap; if (!ccap) ccap = 16; while (ccap <= n) ccap *= 2; cache = realloc(cache, sizeof(ull) * ccap); memset(cache + old, 0, sizeof(ull) * (ccap - old)); } else if (cache[n]) return cache[n]; ull len = (ull)n*(n + 3) / 2; int p, q = 0; for (p = 2; p <= n; p = q) { q = n/(n/p) + 1; len -= farey_len(n/p) * (q - p); } cache[n] = len; return len; } int main(void) { int n; for (n = 1; n <= 11; n++) { printf(, n); farey(n); } for (n = 100; n <= 1000; n += 100) printf(, n, farey_len(n)); n = 10000000; printf(, n, farey_len(n)); return 0; }
857Farey sequence
5c
rwog7
import sys print(sys.getrecursionlimit())
841Find limit of recursion
3python
2kmlz
module Main where import Control.Monad import Data.List import Data.Monoid import Text.Printf entropy :: (Ord a) => [a] -> Double entropy = sum . map (\c -> (c *) . logBase 2 $ 1.0 / c) . (\cs -> let { sc = sum cs } in map (/ sc) cs) . map (fromIntegral . length) . group . sort fibonacci :: (Monoid m) => m -> m -> [m] fibonacci a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) (a,b) main :: IO () main = do printf "%2s%10s%17s%s\n" "N" "length" "entropy" "word" zipWithM_ (\i v -> let { l = length v } in printf "%2d%10d%.15f%s\n" i l (entropy v) (if l > 40 then "..." else v)) [1..38::Int] (take 37 $ fibonacci "1" "0")
851Fibonacci word
8haskell
35ezj
import Data.List ( groupBy ) parseFasta :: FilePath -> IO () parseFasta fileName = do file <- readFile fileName let pairedFasta = readFasta $ lines file mapM_ (\(name, code) -> putStrLn $ name ++ ": " ++ code) pairedFasta readFasta :: [String] -> [(String, String)] readFasta = pair . map concat . groupBy (\x y -> notName x && notName y) where notName :: String -> Bool notName = (/=) '>' . head pair :: [String] -> [(String, String)] pair [] = [] pair (x: y: xs) = (drop 1 x, y): pair xs
854FASTA format
8haskell
lhqch
package main import ( "fmt" "math/big" ) func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.Set(&a[0]) } func main() {
852Faulhaber's formula
0go
anl1f
This uses the `factor` function from the `coreutils` library that comes standard with most GNU/Linux, BSD, and Unix systems. https: https:
849Fermat numbers
14ruby
64q3t
def main maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 puts for i in 2 .. maxIt a = a1 + (a1 - a2) / d1 for j in 1 .. maxItJ x = 0.0 y = 0.0 for k in 1 .. 1 << i y = 1.0 - 2.0 * y * x x = a - x * x end a = a - x / y end d = (a1 - a2) / (a - a1) print % [i, d] d1 = d a2 = a1 a1 = a end end main()
848Feigenbaum constant calculation
14ruby
8yk01
object Feigenbaum1 extends App { val (max_it, max_it_j) = (13, 10) var (a1, a2, d1, a) = (1.0, 0.0, 3.2, 0.0) println(" i d") var i: Int = 2 while (i <= max_it) { a = a1 + (a1 - a2) / d1 for (_ <- 0 until max_it_j) { var (x, y) = (0.0, 0.0) for (_ <- 0 until 1 << i) { y = 1.0 - 2.0 * y * x x = a - x * x } a -= x / y } val d: Double = (a1 - a2) / (a - a1) printf("%2d %.8f\n", i, d) d1 = d a2 = a1 a1 = a i += 1 } }
848Feigenbaum constant calculation
16scala
dlang
modtime = File.mtime('filename') File.utime(actime, mtime, 'path') File.utime(File.atime('path'), mtime, 'path') File.utime(nil, nil, 'path')
844File modification time
14ruby
pogbh
def fibonacci_word(n) words = [, ] (n-1).times{ words << words[-1] + words[-2] } words[n] end def print_fractal(word) area = Hash.new() x = y = 0 dx, dy = 0, -1 area[[x,y]] = word.each_char.with_index(1) do |c,n| area[[x+dx, y+dy]] = dx.zero?? : x, y = x+2*dx, y+2*dy area[[x, y]] = dx,dy = n.even?? [dy,-dx]: [-dy,dx] if c== end (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax) for y in ymin..ymax puts (xmin..xmax).map{|x| area[[x,y]]}.join end end word = fibonacci_word(16) print_fractal(word)
846Fibonacci word/fractal
14ruby
ygo6n
null
846Fibonacci word/fractal
15rust
mriya
options("expressions") options(expressions = 10000) recurse <- function(x) { print(x) recurse(x+1) } recurse(0)
841Find limit of recursion
13r
mrzy4
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
854FASTA format
9java
35pzg
const fs = require("fs"); const readline = require("readline"); const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); } const fname = args[0]; const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: false, }); let sep = ""; readInterface.on("line", (line) => { if (line.startsWith(">")) { process.stdout.write(sep); sep = "\n"; process.stdout.write(line.substring(1) + ": "); } else { process.stdout.write(line); } }); readInterface.on("close", () => process.stdout.write("\n"));
854FASTA format
10javascript
cjx9j
package main import ( "fmt" "math/big" ) func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } }
855Faulhaber's triangle
0go
2kql7
import java.util.stream.IntStream class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) } private static class Frac implements Comparable<Frac> { private long num private long denom public static final Frac ZERO = new Frac(0, 1) public static final Frac ONE = new Frac(1, 1) Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero") long nn = n long dd = d if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd } long g = Math.abs(gcd(nn, dd)) if (g > 1) { nn /= g dd /= g } num = nn denom = dd } Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom) } Frac negative() { return new Frac(-num, denom) } Frac minus(Frac rhs) { return this + -rhs } Frac multiply(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom) } @Override int compareTo(Frac o) { double diff = toDouble() - o.toDouble() return Double.compare(diff, 0.0) } @Override boolean equals(Object obj) { return null != obj && obj instanceof Frac && this == (Frac) obj } @Override String toString() { if (denom == 1) { return Long.toString(num) } return String.format("%d/%d", num, denom) } private double toDouble() { return (double) num / denom } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero") Frac[] a = new Frac[n + 1] Arrays.fill(a, Frac.ZERO) for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1) for (int j = m; j >= 1; --j) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1) } }
852Faulhaber's formula
7groovy
hs6j9
struct DivisorGen { curr: u64, last: u64, } impl Iterator for DivisorGen { type Item = u64; fn next(&mut self) -> Option<u64> { self.curr += 2u64; if self.curr < self.last{ None } else { Some(self.curr) } } } fn divisor_gen(num: u64) -> DivisorGen { DivisorGen { curr: 0u64, last: (num / 2u64) + 1u64 } } fn is_prime(num: u64) -> bool{ if num == 2 || num == 3 { return true; } else if num% 2 == 0 || num% 3 == 0 || num <= 1{ return false; }else{ for i in divisor_gen(num){ if num% i == 0{ return false; } } } return true; } fn main() { let fermat_closure = |i: u32| -> u64 {2u64.pow(2u32.pow(i + 1u32))}; let mut f_numbers: Vec<u64> = Vec::new(); println!("First 4 Fermat numbers:"); for i in 0..4 { let f = fermat_closure(i) + 1u64; f_numbers.push(f); println!("F{}: {}", i, f); } println!("Factor of the first four numbers:"); for f in f_numbers.iter(){ let is_prime: bool = f% 4 == 1 && is_prime(*f); let not_or_not = if is_prime {" "} else {" not "}; println!("{} is{}prime", f, not_or_not); } }
849Fermat numbers
15rust
ygs68
import scala.collection.mutable import scala.collection.mutable.ListBuffer object FermatNumbers { def main(args: Array[String]): Unit = { println("First 10 Fermat numbers:") for (i <- 0 to 9) { println(f"F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") for (i <- 0 to 12) { println(f"F[$i] = ${getString(getFactors(i, fermat(i)))}") } } private val TWO = BigInt(2) def fermat(n: Int): BigInt = { TWO.pow(math.pow(2.0, n).intValue()) + 1 } def getString(factors: List[BigInt]): String = { if (factors.size == 1) { return s"${factors.head} (PRIME)" } factors.map(a => a.toString) .map(a => if (a.startsWith("-")) "(C" + a.replace("-", "") + ")" else a) .reduce((a, b) => a + " * " + b) } val COMPOSITE: mutable.Map[Int, String] = scala.collection.mutable.Map( 9 -> "5529", 10 -> "6078", 11 -> "1037", 12 -> "5488", 13 -> "2884" ) def getFactors(fermatIndex: Int, n: BigInt): List[BigInt] = { var n2 = n var factors = new ListBuffer[BigInt] var loop = true while (loop) { if (n2.isProbablePrime(100)) { factors += n2 loop = false } else { if (COMPOSITE.contains(fermatIndex)) { val stop = COMPOSITE(fermatIndex) if (n2.toString.startsWith(stop)) { factors += -n2.toString().length loop = false } } if (loop) { val factor = pollardRhoFast(n2) if (factor == 0) { factors += n2 loop = false } else { factors += factor n2 = n2 / factor } } } } factors.toList } def pollardRhoFast(n: BigInt): BigInt = { var x = BigInt(2) var y = BigInt(2) var z = BigInt(1) var d = BigInt(1) var count = 0 var loop = true while (loop) { x = pollardRhoG(x, n) y = pollardRhoG(pollardRhoG(y, n), n) d = (x - y).abs z = (z * d) % n count += 1 if (count == 100) { d = z.gcd(n) if (d != 1) { loop = false } else { z = BigInt(1) count = 0 } } } println(s" Pollard rho try factor $n") if (d == n) { return 0 } d } def pollardRhoG(x: BigInt, n: BigInt): BigInt = ((x * x) + 1) % n }
849Fermat numbers
16scala
cjo93
import Foundation func feigenbaum(iterations: Int = 13) { var a = 0.0 var a1 = 1.0 var a2 = 0.0 var d = 0.0 var d1 = 3.2 print(" i d") for i in 2...iterations { a = a1 + (a1 - a2) / d1 for _ in 1...10 { var x = 0.0 var y = 0.0 for _ in 1...1<<i { y = 1.0 - 2.0 * y * x x = a - x * x } a -= x / y } d = (a1 - a2) / (a - a1) d1 = d (a1, a2) = (a, a1) print(String(format: "%2d %.8f", i, d)) } } feigenbaum()
848Feigenbaum constant calculation
17swift
06hs6
use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; if let Ok(time) = metadata.accessed() { println!("{:?}", time); } else { println!("Not supported on this platform"); } Ok(()) }
844File modification time
15rust
1irpu
import java.io.File import java.util.Date object FileModificationTime extends App { def test(file: File) { val (t, init) = (file.lastModified(), s"The following ${if (file.isDirectory()) "directory" else "file"} called ${file.getPath()}") println(init + (if (t == 0) " does not exist." else " was modified at " + new Date(t).toInstant())) println(init + (if (file.setLastModified(System.currentTimeMillis())) " was modified to current time." else " does not exist.")) println(init + (if (file.setLastModified(t)) " was reset to previous time." else " does not exist.")) }
844File modification time
16scala
wfhes
def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1) def turnLeft(c: Char): Char = c match { case 'R' => 'U' case 'U' => 'L' case 'L' => 'D' case 'D' => 'R' } def turnRight(c: Char): Char = c match { case 'R' => 'D' case 'D' => 'L' case 'L' => 'U' case 'U' => 'R' } def directions(xss: List[(Char,Char)], current: Char = 'R'): List[Char] = xss match { case Nil => current :: Nil case x :: xs => x._1 match { case '1' => current :: directions(xs, current) case '0' => x._2 match { case 'E' => current :: directions(xs, turnLeft(current)) case 'O' => current :: directions(xs, turnRight(current)) } } } def buildIt(xss: List[Char], old: Char = 'X', count: Int = 1): List[String] = xss match { case Nil => s"$old$count" :: Nil case x :: xs if x == old => buildIt(xs,old,count+1) case x :: xs => s"$old$count" :: buildIt(xs,x) } def convertToLine(s: String, c: Int): String = (s.head, s.tail) match { case ('R',n) => s"l ${c * n.toInt} 0" case ('U',n) => s"l 0 ${-c * n.toInt}" case ('L',n) => s"l ${-c * n.toInt} 0" case ('D',n) => s"l 0 ${c * n.toInt}" } def drawSVG(xStart: Int, yStart: Int, width: Int, height: Int, fibWord: String, lineMultiplier: Int, color: String): String = { val xs = fibWord.zipWithIndex.map{case (c,i) => (c, if(c == '1') '_' else i % 2 match{case 0 => 'E'; case 1 => 'O'})}.toList val fractalPath = buildIt(directions(xs)).tail.map(convertToLine(_,lineMultiplier)) s"""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-
846Fibonacci word/fractal
16scala
lhfcq
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d%10d%s%n", ++i, word.length (), entropy ( word ) ); } } }
851Fibonacci word
9java
i9hos
null
854FASTA format
11kotlin
nc7ij
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res } func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only%d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") } func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d:%2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With%d people:%s\n", base, t) } }
856Fairshare between two and more
0go
b8zkh
import java.math.MathContext import java.util.stream.LongStream class FaulhabersTriangle { private static final MathContext MC = new MathContext(256) private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) } private static class Frac implements Comparable<Frac> { private long num private long denom public static final Frac ZERO = new Frac(0, 1) Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero") long nn = n long dd = d if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd } long g = Math.abs(gcd(nn, dd)) if (g > 1) { nn /= g dd /= g } num = nn denom = dd } Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom) } Frac negative() { return new Frac(-num, denom) } Frac minus(Frac rhs) { return this + -rhs } Frac multiply(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom) } @Override int compareTo(Frac o) { double diff = toDouble() - o.toDouble() return Double.compare(diff, 0.0) } @Override boolean equals(Object obj) { return null != obj && obj instanceof Frac && this == (Frac) obj } @Override String toString() { if (denom == 1) { return Long.toString(num) } return String.format("%d/%d", num, denom) } double toDouble() { return (double) num / denom } BigDecimal toBigDecimal() { return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC) } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero") Frac[] a = new Frac[n + 1] Arrays.fill(a, Frac.ZERO) for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1) for (int j = m; j >= 1; --j) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1) } }
855Faulhaber's triangle
7groovy
yg16o
import Data.Ratio ((%), numerator, denominator) import Data.List (intercalate, transpose) import Data.Bifunctor (bimap) import Data.Char (isSpace) import Data.Monoid ((<>)) import Data.Bool (bool) faulhaber :: [[Rational]] faulhaber = tail $ scanl (\rs n -> let xs = zipWith ((*) . (n %)) [2 ..] rs in 1 - sum xs: xs) [] [0 ..] polynomials :: [[(String, String)]] polynomials = fmap ((ratioPower =<<) . reverse . flip zip [1 ..]) faulhaber main :: IO () main = (putStrLn . unlines . expressionTable . take 10) polynomials expressionTable :: [[(String, String)]] -> [String] expressionTable ps = let cols = transpose (fullTable ps) in expressionRow <$> zip [0 ..] (transpose $ zipWith (\(lw, rw) col -> fmap (bimap (justifyLeft lw ' ') (justifyLeft rw ' ')) col) (colWidths cols) cols) ratioPower :: (Rational, Integer) -> [(String, String)] ratioPower (nd, j) = let (num, den) = ((,) . numerator <*> denominator) nd sn | num == 0 = [] | (j /= 1) = ("n^" <> show j) | otherwise = "n" sr | num == 0 = [] | den == 1 && num == 1 = [] | den == 1 = show num <> "n" | otherwise = intercalate "/" [show num, show den] s = sr <> sn in bool [(sn, sr)] [] (null s) fullTable :: [[(String, String)]] -> [[(String, String)]] fullTable xs = let lng = maximum $ length <$> xs in (<>) <*> (flip replicate ([], []) . (-) lng . length) <$> xs justifyLeft :: Int -> Char -> String -> String justifyLeft n c s = take n (s <> replicate n c) expressionRow :: (Int, [(String, String)]) -> String expressionRow (i, row) = concat [ show i , " -> " , foldr (\s a -> concat [s, bool " + " " " (blank a || head a == '-'), a]) [] (polyTerm <$> row) ] polyTerm :: (String, String) -> String polyTerm (l, r) | blank l || blank r = l <> r | head r == '-' = concat ["- ", l, " * ", tail r] | otherwise = intercalate " * " [l, r] blank :: String -> Bool blank = all isSpace colWidths :: [[(String, String)]] -> [(Int, Int)] colWidths = fmap (foldr (\(ls, rs) (lMax, rMax) -> (max (length ls) lMax, max (length rs) rMax)) (0, 0)) unsignedLength :: String -> Int unsignedLength xs = let l = length xs in bool (bool l (l - 1) ('-' == head xs)) 0 (0 == l)
852Faulhaber's formula
8haskell
zu1t0
sub common_prefix { my $sep = shift; my $paths = join "\0", map { $_.$sep } @_; $paths =~ /^ ( [^\0]* ) $sep [^\0]* (?: \0 \1 $sep [^\0]* )* $/x; return $1; }
843Find common directory path
2perl
rw2gd
1.upto(100) { i -> println "${i% 3? '': 'Fizz'}${i% 5? '': 'Buzz'}" ?: i }
835FizzBuzz
7groovy
0yish
null
851Fibonacci word
10javascript
zuat2
local file = io.open("input.txt","r") local data = file:read("*a") file:close() local output = {} local key = nil
854FASTA format
1lua
dljnq
double PI; typedef double complex cplx; void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2); for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } } void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i]; _fft(buf, out, n, 1); } void show(const char * s, cplx buf[]) { printf(, s); for (int i = 0; i < 8; i++) if (!cimag(buf[i])) printf(, creal(buf[i])); else printf(, creal(buf[i]), cimag(buf[i])); } int main() { PI = atan2(1, 1) * 4; cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0}; show(, buf); fft(buf, 8); show(, buf); return 0; }
858Fast Fourier transform
5c
8y204
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap) thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..] baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( sum $ unfoldr ( bool Nothing . Just . swap . flip quotRem base <*> (0 <) ) n ) base main :: IO () main = putStrLn $ fTable ( "First 25 fairshare terms " <> "for a given number of players:\n" ) show ( ('[':) . (<> "]") . intercalate "," . fmap show ) (take 25 . thueMorse) [2, 3, 5, 11] fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String fTable s xShow fxShow f xs = unlines $ s: fmap ( ((<>) . justifyRight w ' ' . xShow) <*> ((" -> " <>) . fxShow . f) ) xs where w = maximum (length . xShow <$> xs) justifyRight :: Int -> Char -> String -> String justifyRight n c = (drop . length) <*> (replicate n c <>)
856Fairshare between two and more
8haskell
dlrn4
import Data.Ratio (Ratio, denominator, numerator, (%)) faulhaber :: Int -> Rational -> Rational faulhaber p n = sum $ zipWith ((*) . (n ^)) [1 ..] (faulhaberTriangle !! p) faulhaberTriangle :: [[Rational]] faulhaberTriangle = tail $ scanl ( \rs n -> let xs = zipWith ((*) . (n %)) [2 ..] rs in 1 - sum xs: xs ) [] [0 ..] main :: IO () main = do let triangle = take 10 faulhaberTriangle widths = maxWidths triangle mapM_ putStrLn [ unlines ( (justifyRatio widths 8 ' ' =<<) <$> triangle ), (show . numerator) (faulhaber 17 1000) ] justifyRatio :: (Int, Int) -> Int -> Char -> Rational -> String justifyRatio (wn, wd) n c nd = go $ [numerator, denominator] <*> [nd] where w = max n (wn + wd + 2) go [num, den] | 1 == den = center w c (show num) | otherwise = let (q, r) = quotRem (w - 1) 2 in concat [ justifyRight q c (show num), "/", justifyLeft (q + r) c (show den) ] justifyLeft :: Int -> a -> [a] -> [a] justifyLeft n c s = take n (s <> replicate n c) justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = (drop . length) <*> (replicate n c <>) center :: Int -> a -> [a] -> [a] center n c s = let (q, r) = quotRem (n - length s) 2 pad = replicate q c in concat [pad, s, pad, replicate r c] maxWidths :: [[Rational]] -> (Int, Int) maxWidths xss = let widest f xs = maximum $ fmap (length . show . f) xs in ((,) . widest numerator <*> widest denominator) $ concat xss
855Faulhaber's triangle
8haskell
anm1g
int * anynacci (int *seedArray, int howMany) { int *result = malloc (howMany * sizeof (int)); int i, j, initialCardinality; for (i = 0; seedArray[i] != 0; i++); initialCardinality = i; for (i = 0; i < initialCardinality; i++) result[i] = seedArray[i]; for (i = initialCardinality; i < howMany; i++) { result[i] = 0; for (j = i - initialCardinality; j < i; j++) result[i] += result[j]; } return result; } int main () { int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 }; int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), *lucas = anynacci(luca, 10); int i; printf (); for (i = 0; i < 10; i++) printf (, fibonacci[i], tribonacci[i], tetranacci[i], lucas[i]); return 0; }
859Fibonacci n-step number sequences
5c
s39q5
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
843Find common directory path
12php
dlsn8
def recurse x puts x recurse(x+1) end recurse(0)
841Find limit of recursion
14ruby
upcvz
my $size1 = -s 'input.txt'; my $size2 = -s '/input.txt';
845File size
2perl
4am5d
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
850File input/output
0go
s3rqa
content = new File('input.txt').text new File('output.txt').write(content)
850File input/output
7groovy
anv1p
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base%d =%s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) {
856Fairshare between two and more
9java
s32q0
import java.util.Arrays; import java.util.stream.IntStream; public class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; private long denom; public static final Frac ZERO = new Frac(0, 1); public static final Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero"); long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.abs(gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); } public Frac unaryMinus() { return new Frac(-num, denom); } public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); } public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); } @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); } @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; } @Override public String toString() { if (denom == 1) { return Long.toString(num); } return String.format("%d/%d", num, denom); } private double toDouble() { return (double) num / denom; } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero"); Frac[] a = new Frac[n + 1]; Arrays.fill(a, Frac.ZERO); for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; --j) { a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1)); } }
852Faulhaber's formula
9java
om78d
fn recurse(n: i32) { println!("depth: {}", n); recurse(n + 1) } fn main() { recurse(0); }
841Find limit of recursion
15rust
51luq
def recurseTest(i:Int):Unit={ try{ recurseTest(i+1) } catch { case e:java.lang.StackOverflowError => println("Recursion depth on this system is " + i + ".") } } recurseTest(0)
841Find limit of recursion
16scala
rwugn
fizzbuzz :: Int -> String fizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x main :: IO () main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]
835FizzBuzz
8haskell
5arug
<?php echo filesize('input.txt'), ; echo filesize('/input.txt'), ; ?>
845File size
12php
i9eov
main = readFile "input.txt" >>= writeFile "output.txt"
850File input/output
8haskell
970mo
null
851Fibonacci word
11kotlin
qz4x1
int isPrime(int n){ if (n%2==0) return n==2; if (n%3==0) return n==3; int d=5; while(d*d<=n){ if(n%d==0) return 0; d+=2; if(n%d==0) return 0; d+=4;} return 1;} main() {int i,d,p,r,q=929; if (!isPrime(q)) return 1; r=q; while(r>0) r<<=1; d=2*q+1; do { for(p=r, i= 1; p; p<<= 1){ i=((long long)i * i) % d; if (p < 0) i *= 2; if (i > d) i -= d;} if (i != 1) d += 2*q; else break; } while(1); printf(, q, d);}
860Factors of a Mersenne number
5c
oml80
(() => { 'use strict';
856Fairshare between two and more
10javascript
ncgiy
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; private long denom; public static final Frac ZERO = new Frac(0, 1); public Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero"); long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.abs(gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); } public Frac unaryMinus() { return new Frac(-num, denom); } public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); } public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); } @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); } @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; } @Override public String toString() { if (denom == 1) { return Long.toString(num); } return String.format("%d/%d", num, denom); } public double toDouble() { return (double) num / denom; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC); } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero"); Frac[] a = new Frac[n + 1]; Arrays.fill(a, Frac.ZERO); for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; --j) { a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1)); } }
855Faulhaber's triangle
9java
jqf7c
null
851Fibonacci word
1lua
s3gq8
my $fasta_example = <<'END_FASTA_EXAMPLE'; >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED END_FASTA_EXAMPLE my $num_newlines = 0; while ( < $fasta_example > ) { if (/\A\>(.*)/) { print "\n" x $num_newlines, $1, ': '; } else { $num_newlines = 1; print; } }
854FASTA format
2perl
7xfrh
fun turn(base: Int, n: Int): Int { var sum = 0 var n2 = n while (n2 != 0) { val re = n2 % base n2 /= base sum += re } return sum % base } fun fairShare(base: Int, count: Int) { print(String.format("Base%2d:", base)) for (i in 0 until count) { val t = turn(base, i) print(String.format("%2d", t)) } println() } fun turnCount(base: Int, count: Int) { val cnt = IntArray(base) { 0 } for (i in 0 until count) { val t = turn(base, i) cnt[t]++ } var minTurn = Int.MAX_VALUE var maxTurn = Int.MIN_VALUE var portion = 0 for (i in 0 until base) { val num = cnt[i] if (num > 0) { portion++ } if (num < minTurn) { minTurn = num } if (num > maxTurn) { maxTurn = num } } print(" With $base people: ") when (minTurn) { 0 -> { println("Only $portion have a turn") } maxTurn -> { println(minTurn) } else -> { println("$minTurn or $maxTurn") } } } fun main() { fairShare(2, 25) fairShare(3, 25) fairShare(5, 25) fairShare(11, 25) println("How many times does each get a turn in 50000 iterations?") turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) }
856Fairshare between two and more
11kotlin
any13
(() => {
855Faulhaber's triangle
10javascript
1iyp7
null
852Faulhaber's formula
11kotlin
xtuws
(defn nacci [init] (letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))] (s))) (let [show (fn [name init] (println "first 20" name (take 20 (nacci init))))] (show "Fibonacci" [1 1]) (show "Tribonacci" [1 1 2]) (show "Tetranacci" [1 1 2 4]) (show "Lucas" [2 1]))
859Fibonacci n-step number sequences
6clojure
ncuik
import os size = os.path.getsize('input.txt') size = os.path.getsize('/input.txt')
845File size
3python
ge94h
function turn(base, n) local sum = 0 while n ~= 0 do local re = n % base n = math.floor(n / base) sum = sum + re end return sum % base end function fairShare(base, count) io.write(string.format("Base%2d:", base)) for i=1,count do local t = turn(base, i - 1) io.write(string.format("%2d", t)) end print() end function turnCount(base, count) local cnt = {} for i=1,base do cnt[i - 1] = 0 end for i=1,count do local t = turn(base, i - 1) if cnt[t] ~= nil then cnt[t] = cnt[t] + 1 else cnt[t] = 1 end end local minTurn = count local maxTurn = -count local portion = 0 for _,num in pairs(cnt) do if num > 0 then portion = portion + 1 end if num < minTurn then minTurn = num end if maxTurn < num then maxTurn = num end end io.write(string.format(" With%d people: ", base)) if minTurn == 0 then print(string.format("Only%d have a turn", portion)) elseif minTurn == maxTurn then print(minTurn) else print(minTurn .. " or " .. maxTurn) end end function main() fairShare(2, 25) fairShare(3, 25) fairShare(5, 25) fairShare(11, 25) print("How many times does each get a turn in 50000 iterations?") turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end main()
856Fairshare between two and more
1lua
edmac
function binomial(n,k) if n<0 or k<0 or n<k then return -1 end if n==0 or k==0 then return 1 end local num = 1 for i=k+1,n do num = num * i end local denom = 1 for i=2,n-k do denom = denom * i end return num / denom end function gcd(a,b) while b ~= 0 do local temp = a % b a = b b = temp end return a end function makeFrac(n,d) local result = {} if d==0 then result.num = 0 result.denom = 0 return result end if n==0 then d = 1 elseif d < 0 then n = -n d = -d end local g = math.abs(gcd(n, d)) if g>1 then n = n / g d = d / g end result.num = n result.denom = d return result end function negateFrac(f) return makeFrac(-f.num, f.denom) end function subFrac(lhs, rhs) return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom) end function multFrac(lhs, rhs) return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom) end function equalFrac(lhs, rhs) return (lhs.num == rhs.num) and (lhs.denom == rhs.denom) end function lessFrac(lhs, rhs) return (lhs.num * rhs.denom) < (rhs.num * lhs.denom) end function printFrac(f) io.write(f.num) if f.denom ~= 1 then io.write("/"..f.denom) end return nil end function bernoulli(n) if n<0 then return {num=0, denom=0} end local a = {} for m=0,n do a[m] = makeFrac(1, m+1) for j=m,1,-1 do a[j-1] = multFrac(subFrac(a[j-1], a[j]), makeFrac(j, 1)) end end if n~=1 then return a[0] end return negateFrac(a[0]) end function faulhaber(p) io.write(p..": ") local q = makeFrac(1, p+1) local sign = -1 for j=0,p do sign = -1 * sign local coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)) if not equalFrac(coeff, makeFrac(0, 1)) then if j==0 then if not equalFrac(coeff, makeFrac(1, 1)) then if equalFrac(coeff, makeFrac(-1, 1)) then io.write("-") else printFrac(coeff) end end else if equalFrac(coeff, makeFrac(1, 1)) then io.write(" + ") elseif equalFrac(coeff, makeFrac(-1, 1)) then io.write(" - ") elseif lessFrac(makeFrac(0, 1), coeff) then io.write(" + ") printFrac(coeff) else io.write(" - ") printFrac(negateFrac(coeff)) end end local pwr = p + 1 - j if pwr>1 then io.write("n^"..pwr) else io.write("n") end end end print() return nil end
852Faulhaber's formula
1lua
qz5x0
var n = 1 func recurse() { print(n) n += 1 recurse() } recurse()
841Find limit of recursion
17swift
vb92r
sizeinwd <- file.info('input.txt')[["size"]] sizeinroot <- file.info('/input.txt')[["size"]]
845File size
13r
vb327
import io FASTA='''\ >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED''' infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s:%s'% keyval for keyval in fasta_parse(infile)))
854FASTA format
3python
jqt7p
(ns mersennenumber (:gen-class)) (defn m* [p q m] " Computes (p*q) mod m " (mod (*' p q) m)) (defn power "modular exponentiation (i.e. b^e mod m" [b e m] (loop [b b, e e, x 1] (if (zero? e) x (if (even? e) (recur (m* b b m) (quot e 2) x) (recur (m* b b m) (quot e 2) (m* b x m)))))) (defn divides? [k n] " checks if k divides n " (= (rem n k) 0)) (defn is-prime? [n] " checks if n is prime " (cond (< n 2) false (= n 2) true (= 0 (mod n 2)) false :else (empty? (filter #(divides? % n) (take-while #(<= (* % %) n) (range 2 n)))))) (def MAX-K 16384) (defn trial-factor [p k] " check if k satisfies 2*k*P + 1 divides 2^p - 1 " (let [q (+ (* 2 p k) 1) mq (mod q 8)] (cond (not (is-prime? q)) nil (and (not= 1 mq) (not= 7 mq)) nil (= 1 (power 2 p q)) q :else nil))) (defn m-factor [p] " searches for k-factor " (some #(trial-factor p %) (range 16384))) (defn -main [p] (if-not (is-prime? p) (format "M%d = 2^%d - 1 exponent is not prime" p p) (if-let [factor (m-factor p)] (format "M%d = 2^%d - 1 is composite with factor%d" p p factor) (format "M%d = 2^%d - 1 is prime" p p)))) (doseq [p [2,3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929] :let [s (-main p)]] (println s))
860Factors of a Mersenne number
6clojure
tv4fv
use strict; use warnings; use Math::AnyNum qw(sum polymod); sub fairshare { my($b, $n) = @_; sprintf '%3d'x$n, map { sum ( polymod($_, $b, $b )) % $b } 0 .. $n-1; } for (<2 3 5 11>) { printf "%3s:%s\n", $_, fairshare($_, 25); }
856Fairshare between two and more
2perl
97amn
null
855Faulhaber's triangle
11kotlin
518ua
>>> import os >>> os.path.commonpath(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) '/home/user1/tmp'
843Find common directory path
3python
7xvrm
get_common_dir <- function(paths, delim = "/") { path_chunks <- strsplit(paths, delim) i <- 1 repeat({ current_chunk <- sapply(path_chunks, function(x) x[i]) if(any(current_chunk!= current_chunk[1])) break i <- i + 1 }) paste(path_chunks[[1]][seq_len(i - 1)], collapse = delim) } paths <- c( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members') get_common_dir(paths)
843Find common directory path
13r
519uy
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
850File input/output
9java
tvaf9
library("seqinr") data <- c(">Rosetta_Example_1","THERECANBENOSPACE",">Rosetta_Example_2","THERECANBESEVERAL","LINESBUTTHEYALLMUST","BECONCATENATED") fname <- "rosettacode.fasta" f <- file(fname,"w+") writeLines(data,f) close(f) fasta <- read.fasta(file = fname, as.string = TRUE, seqtype = "AA") for (aline in fasta) { cat(attr(aline, 'Annot'), ":", aline, "\n") }
854FASTA format
13r
4ai5y
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b))% b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f)
856Fairshare between two and more
3python
cje9q
function binomial(n,k) if n<0 or k<0 or n<k then return -1 end if n==0 or k==0 then return 1 end local num = 1 for i=k+1,n do num = num * i end local denom = 1 for i=2,n-k do denom = denom * i end return num / denom end function gcd(a,b) while b ~= 0 do local temp = a % b a = b b = temp end return a end function makeFrac(n,d) local result = {} if d==0 then result.num = 0 result.denom = 0 return result end if n==0 then d = 1 elseif d < 0 then n = -n d = -d end local g = math.abs(gcd(n, d)) if g>1 then n = n / g d = d / g end result.num = n result.denom = d return result end function negateFrac(f) return makeFrac(-f.num, f.denom) end function subFrac(lhs, rhs) return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom) end function multFrac(lhs, rhs) return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom) end function equalFrac(lhs, rhs) return (lhs.num == rhs.num) and (lhs.denom == rhs.denom) end function lessFrac(lhs, rhs) return (lhs.num * rhs.denom) < (rhs.num * lhs.denom) end function printFrac(f) local str = tostring(f.num) if f.denom ~= 1 then str = str.."/"..f.denom end for i=1, 7 - string.len(str) do io.write(" ") end io.write(str) return nil end function bernoulli(n) if n<0 then return {num=0, denom=0} end local a = {} for m=0,n do a[m] = makeFrac(1, m+1) for j=m,1,-1 do a[j-1] = multFrac(subFrac(a[j-1], a[j]), makeFrac(j, 1)) end end if n~=1 then return a[0] end return negateFrac(a[0]) end function faulhaber(p) local q = makeFrac(1, p+1) local sign = -1 local coeffs = {} for j=0,p do sign = -1 * sign coeffs[p-j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)) end for j=0,p do printFrac(coeffs[j]) end print() return nil end
855Faulhaber's triangle
1lua
4ao5c
var fso = new ActiveXObject("Scripting.FileSystemObject"); var ForReading = 1, ForWriting = 2; var f_in = fso.OpenTextFile('input.txt', ForReading); var f_out = fso.OpenTextFile('output.txt', ForWriting, true);
850File input/output
10javascript
mrsyv
package main import "fmt" type frac struct{ num, den int } func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) } func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } } func main() {
857Farey sequence
0go
nc4i1
size = File.size('input.txt') size = File.size('/input.txt')
845File size
14ruby
7xlri
def fasta_format(strings) out, text = [], strings.split().each do |line| if line[0] == '>' out << text unless text.empty? text = line[1..-1] + else text << line end end out << text unless text.empty? end data = <<'EOS' >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED EOS puts fasta_format(data)
854FASTA format
14ruby
k03hg
use std::env; use std::io::{BufReader, Lines}; use std::io::prelude::*; use std::fs::File; fn main() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).unwrap(); for line in FastaIter::new(f) { println!("{}", line); } } struct FastaIter<T> { buffer_lines: Lines<BufReader<T>>, current_name: Option<String>, current_sequence: String } impl<T: Read> FastaIter<T> { fn new(file: T) -> FastaIter<T> { FastaIter { buffer_lines: BufReader::new(file).lines(), current_name: None, current_sequence: String::new() } } } impl<T: Read> Iterator for FastaIter<T> { type Item = String; fn next(&mut self) -> Option<String> { while let Some(l) = self.buffer_lines.next() { let line = l.unwrap(); if line.starts_with(">") { if self.current_name.is_some() { let mut res = String::new(); res.push_str(self.current_name.as_ref().unwrap()); res.push_str(": "); res.push_str(&self.current_sequence); self.current_name = Some(String::from(&line[1..])); self.current_sequence.clear(); return Some(res); } else { self.current_name = Some(String::from(&line[1..])); self.current_sequence.clear(); } continue; } self.current_sequence.push_str(line.trim()); } if self.current_name.is_some() { let mut res = String::new(); res.push_str(self.current_name.as_ref().unwrap()); res.push_str(": "); res.push_str(&self.current_sequence); self.current_name = None; self.current_sequence.clear(); self.current_sequence.shrink_to_fit(); return Some(res); } None } }
854FASTA format
15rust
b86kx
import Data.List (unfoldr, mapAccumR) import Data.Ratio ((%), denominator, numerator) import Text.Printf (PrintfArg, printf) farey :: Integer -> [Rational] farey n = 0: unfoldr step (0, 1, 1, n) where step (a, b, c, d) | c > n = Nothing | otherwise = let k = (n + b) `quot` d in Just (c %d, (c, d, k * c - a, k * d - b)) fareys :: ([Rational] -> a) -> [Integer] -> [(Integer, a)] fareys fn ns = snd $ mapAccumR prune (farey $ last ns) ns where prune rs n = let rs'' = filter ((<= n) . denominator) rs in (rs'', (n, fn rs'')) fprint :: (PrintfArg b) => String -> [(Integer, b)] -> IO () fprint fmt = mapM_ (uncurry $ printf fmt) showFracs :: [Rational] -> String showFracs = unwords . map (concat . (<*>) [show . numerator, const "/", show . denominator] . pure) main :: IO () main = do putStrLn "Farey Sequences\n" fprint "%2d%s\n" $ fareys showFracs [1 .. 11] putStrLn "\nSequence Lengths\n" fprint "%4d%d\n" $ fareys length [100,200 .. 1000]
857Farey sequence
8haskell
upqv2
require 'abbrev' dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members ) common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop common_directory = common_prefix.sub(%r{/[^/]*$}, '')
843Find common directory path
14ruby
hs5jx
use std::{env, fs, process}; use std::io::{self, Write}; use std::fmt::Display; fn main() { let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1)); let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2)); println!("Size of file.txt is {} bytes", metadata.len()); } #[inline] fn exit_err<T: Display>(msg: T, code: i32) ->! { writeln!(&mut io::stderr(), "Error: {}", msg).expect("Could not write to stdout"); process::exit(code) } }
845File size
15rust
jq272
import java.io.File object FileSize extends App { val name = "pg1661.txt" println(s"$name : ${new File(name).length()} bytes") println(s"/$name: ${new File(s"${File.separator}$name").length()} bytes") }
845File size
16scala
b85k6
null
850File input/output
11kotlin
omh8z
sub fiboword; { my ($a, $b, $count) = (1, 0, 0); sub fiboword { $count++; return $a if $count == 1; return $b if $count == 2; ($a, $b) = ($b, "$b$a"); return $b; } } sub entropy { my %c; $c{$_}++ for split //, my $str = shift; my $e = 0; for (values %c) { my $p = $_ / length $str; $e -= $p * log $p; } return $e / log 2; } my $count; while ($count++ < 37) { my $word = fiboword; printf "%5d\t%10d\t%.8e\t%s\n", $count, length($word), entropy($word), $count > 9 ? '' : $word }
851Fibonacci word
2perl
vbi20
import java.io.File import java.util.Scanner object ReadFastaFile extends App { val sc = new Scanner(new File("test.fasta")) var first = true while (sc.hasNextLine) { val line = sc.nextLine.trim if (line.charAt(0) == '>') { if (first) first = false else println() printf("%s: ", line.substring(1)) } else print(line) } println("~~~+~~~") }
854FASTA format
16scala
an91n
import java.util.TreeSet; public class Farey{ private static class Frac implements Comparable<Frac>{ int num; int den; public Frac(int num, int den){ this.num = num; this.den = den; } @Override public String toString(){ return num + "/" + den; } @Override public int compareTo(Frac o){ return Double.compare((double)num / den, (double)o.num / o.den); } } public static TreeSet<Frac> genFarey(int i){ TreeSet<Frac> farey = new TreeSet<Frac>(); for(int den = 1; den <= i; den++){ for(int num = 0; num <= den; num++){ farey.add(new Frac(num, den)); } } return farey; } public static void main(String[] args){ for(int i = 1; i <= 11; i++){ System.out.println("F" + i + ": " + genFarey(i)); } for(int i = 100; i <= 1000; i += 100){ System.out.println("F" + i + ": " + genFarey(i).size() + " members"); } } }
857Farey sequence
9java
mrpym
def turn(base, n) sum = 0 while n!= 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end def fairshare(base, count) print % [base] for i in 0 .. count - 1 do t = turn(base, i) print % [t] end print end def turnCount(base, count) cnt = Array.new(base, 0) for i in 0 .. count - 1 do t = turn(base, i) cnt[t] = cnt[t] + 1 end minTurn = base * count maxTurn = -1 portion = 0 for i in 0 .. base - 1 do if cnt[i] > 0 then portion = portion + 1 end if cnt[i] < minTurn then minTurn = cnt[i] end if cnt[i] > maxTurn then maxTurn = cnt[i] end end print % [base] if 0 == minTurn then print % portion elsif minTurn == maxTurn then print % [minTurn] else print % [minTurn, maxTurn] end end def main fairshare(2, 25) fairshare(3, 25) fairshare(5, 25) fairshare(11, 25) puts turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end main()
856Fairshare between two and more
14ruby
2kxlw
use std::path::{Path, PathBuf}; fn main() { let paths = [ Path::new("/home/user1/tmp/coverage/test"), Path::new("/home/user1/tmp/covert/operator"), Path::new("/home/user1/tmp/coven/members"), ]; match common_path(&paths) { Some(p) => println!("The common path is: {:#?}", p), None => println!("No common paths found"), } } fn common_path<I, P>(paths: I) -> Option<PathBuf> where I: IntoIterator<Item = P>, P: AsRef<Path>, { let mut iter = paths.into_iter(); let mut ret = iter.next()?.as_ref().to_path_buf(); for path in iter { if let Some(r) = common(ret, path.as_ref()) { ret = r; } else { return None; } } Some(ret) } fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> { let a = a.as_ref().components(); let b = b.as_ref().components(); let mut ret = PathBuf::new(); let mut found = false; for (one, two) in a.zip(b) { if one == two { ret.push(one); found = true; } else { break; } } if found { Some(ret) } else { None } }
843Find common directory path
15rust
k04h5
null
857Farey sequence
11kotlin
tv7f0
struct Digits { rest: usize, base: usize, } impl Iterator for Digits { type Item = usize; fn next(&mut self) -> Option<usize> { if self.rest == 0 { return None; } let (digit, rest) = (self.rest% self.base, self.rest / self.base); self.rest = rest; Some(digit) } } fn digits(num: usize, base: usize) -> Digits { Digits { rest: num, base: base } } struct FairSharing { participants: usize, index: usize, } impl Iterator for FairSharing { type Item = usize; fn next(&mut self) -> Option<usize> { let digit_sum: usize = digits(self.index, self.participants).sum(); let selected = digit_sum% self.participants; self.index += 1; Some(selected) } } fn fair_sharing(participants: usize) -> FairSharing { FairSharing { participants: participants, index: 0 } } fn main() { for i in vec![2, 3, 5, 7] { println!("{}: {:?}", i, fair_sharing(i).take(25).collect::<Vec<usize>>()); } }
856Fairshare between two and more
15rust
vbq2t
use 5.010; use List::Util qw(sum); use Math::BigRat try => 'GMP'; use ntheory qw(binomial bernfrac); sub faulhaber_triangle { my ($p) = @_; map { Math::BigRat->new(bernfrac($_)) * binomial($p, $_) / $p } reverse(0 .. $p-1); } foreach my $p (1 .. 10) { say map { sprintf("%6s", $_) } faulhaber_triangle($p); } my $p = 17; my $n = Math::BigInt->new(1000); my @r = faulhaber_triangle($p+1); say "\n", sum(map { $r[$_] * $n**($_ + 1) } 0 .. $
855Faulhaber's triangle
2perl
om48x
use 5.014; use Math::Algebra::Symbols; sub bernoulli_number { my ($n) = @_; return 0 if $n > 1 && $n % 2; my @A; for my $m (0 .. $n) { $A[$m] = symbols(1) / ($m + 1); for (my $j = $m ; $j > 0 ; $j--) { $A[$j - 1] = $j * ($A[$j - 1] - $A[$j]); } } return $A[0]; } sub binomial { my ($n, $k) = @_; return 1 if $k == 0 || $n == $k; binomial($n - 1, $k - 1) + binomial($n - 1, $k); } sub faulhaber_s_formula { my ($p) = @_; my $formula = 0; for my $j (0 .. $p) { $formula += binomial($p + 1, $j) * bernoulli_number($j) * symbols('n')**($p + 1 - $j); } (symbols(1) / ($p + 1) * $formula) =~ s/\$n/n/gr =~ s/\*\*/^/gr =~ s/\*/ /gr; } foreach my $i (0 .. 9) { say "$i: ", faulhaber_s_formula($i); }
852Faulhaber's formula
2perl
2k8lf