code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
int main(){ int sum = 0, i, j; int try_max = 0; int count_list[3] = {1,0,0}; for(i=2; i <= 20000; i++){ try_max = i/2; sum = 1; for(j=2; j<try_max; j++){ if (i % j) continue; try_max = i/j; sum += j; if (j != try_max) sum += try_max; } if (sum < i){ count_list[de]++; continue; } if (sum > i){ count_list[ab]++; continue; } count_list[pe]++; } printf( ,count_list[de]); printf( ,count_list[pe]); printf( ,count_list[ab]); return 0; }
1,161Abundant, deficient and perfect number classifications
5c
08bst
(ns rosettacode.align-columns (:require [clojure.contrib.string:as str])) (def data "Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.") (def table (map #(str/split #"\$" %) (str/split-lines data))) (defn col-width [n table] (reduce max (map #(try (count (nth % n)) (catch Exception _ 0)) table))) (defn spaces [n] (str/repeat n " ")) (defn add-padding "if the string is too big turncate it, else return a string with padding" [string width justification] (if (>= (count string) width) (str/take width string) (let [pad-len (int (- width (count string))) half-pad-len (int (/ pad-len 2))] (case justification :right (str (spaces pad-len) string) :left (str string (spaces pad-len)) :center (str (spaces half-pad-len) string (spaces (- pad-len half-pad-len))))))) (defn aligned-table "get the width of each column, then generate a new table with propper padding for eath item" ([table justification] (let [col-widths (map #(+ 2 (col-width % table)) (range (count(first table))))] (map (fn [row] (map #(add-padding %1 %2 justification) row col-widths)) table)))) (defn print-table [table] (do (println) (print (str/join "" (flatten (interleave table (repeat "\n"))))))) (print-table (aligned-table table:center))
1,160Align columns
6clojure
ymi6b
use strict; use 5.10.0; package Integrator; use threads; use threads::shared; sub new { my $cls = shift; my $obj = bless { t => 0, sum => 0, ref $cls ? %$cls : (), stop => 0, tid => 0, func => shift, }, ref $cls || $cls; share($obj->{sum}); share($obj->{stop}); $obj->{tid} = async { my $upd = 0.1; while (!$obj->{stop}) { { my $f = $obj->{func}; my $t = $obj->{t}; $obj->{sum} += ($f->($t) + $f->($t + $upd))* $upd/ 2; $obj->{t} += $upd; } select(undef, undef, undef, $upd); } }; $obj } sub output { shift->{sum} } sub delete { my $obj = shift; $obj->{stop} = 1; $obj->{tid}->join; } sub setinput { my $obj = shift; $obj->delete; $obj->new(shift); } package main; my $x = Integrator->new(sub { sin(atan2(1, 1) * 8 * .5 * shift) }); sleep(2); say "sin after 2 seconds: ", $x->output; $x = $x->setinput(sub {0}); select(undef, undef, undef, .5); say "0 after .5 seconds: ", $x->output; $x->delete;
1,157Active object
2perl
cl39a
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length%i'% slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to%i'% new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s:%r'% aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s:%r'% aliquot(n))
1,151Aliquot sequence classifications
3python
g774h
null
1,153AKS test for primes
11kotlin
v5v21
from proper_divisors import proper_divs def amicable(rangemax=20000): n2divsum = {n: sum(proper_divs(n)) for n in range(1, rangemax + 1)} for num, divsum in n2divsum.items(): if num < divsum and divsum <= rangemax and n2divsum[divsum] == num: yield num, divsum if __name__ == '__main__': for num, divsum in amicable(): print('Amicable pair:%i and%i With proper divisors:\n %r\n %r' % (num, divsum, sorted(proper_divs(num)), sorted(proper_divs(divsum))))
1,144Amicable pairs
3python
c279q
def accumulator = { Number n -> def value = n; { it = 0 -> value += it} }
1,159Accumulator factory
7groovy
081sh
null
1,153AKS test for primes
1lua
u4uvl
require additive_primes = Prime.lazy.select{|prime| prime.digits.sum.prime? } N = 500 res = additive_primes.take_while{|n| n < N}.to_a puts res.join() puts
1,154Additive primes
14ruby
gr54q
import Control.Monad.ST import Data.STRef accumulator :: (Num a) => a -> ST s (a -> ST s a) accumulator sum0 = do sum <- newSTRef sum0 return $ \n -> do modifySTRef sum (+ n) readSTRef sum main :: IO () main = print foo where foo = runST $ do x <- accumulator 1 x 5 accumulator 3 x 2.3
1,159Accumulator factory
8haskell
54mug
fn main() { let limit = 500; let column_w = limit.to_string().len() + 1; let mut pms = Vec::with_capacity(limit / 2 - limit / 3 / 2 - limit / 5 / 3 / 2 + 1); let mut count = 0; for u in (2..3).chain((3..limit).step_by(2)) { if pms.iter().take_while(|&&p| p * p <= u).all(|&p| u % p != 0) { pms.push(u); let dgs = std::iter::successors(Some(u), |&n| (n > 9).then(|| n / 10)).map(|n| n % 10); if pms.binary_search(&dgs.sum()).is_ok() { print!("{}{u:column_w$}", if count % 10 == 0 { "\n" } else { "" }); count += 1; } } } println!("\n---\nFound {count} additive primes less than {limit}"); }
1,154Additive primes
15rust
r74g5
divisors <- function (n) { Filter( function (m) 0 == n%% m, 1:(n/2) ) } table = sapply(1:19999, function (n) sum(divisors(n)) ) for (n in 1:19999) { m = table[n] if ((m > n) && (m < 20000) && (n == table[m])) cat(n, " ", m, "\n") }
1,144Amicable pairs
13r
6m53e
use strict; use warnings; use constant EXIT_FAILURE => 1; use constant EXIT_SUCCESS => 0; sub amb { exit(EXIT_FAILURE) if !@_; for my $word (@_) { my $pid = fork; die $! unless defined $pid; return $word if !$pid; my $wpid = waitpid $pid, 0; die $! unless $wpid == $pid; exit(EXIT_SUCCESS) if $? == EXIT_SUCCESS; } exit(EXIT_FAILURE); } sub joined { my ($join_a, $join_b) = @_; substr($join_a, -1) eq substr($join_b, 0, 1); } my $w1 = amb(qw(the that a)); my $w2 = amb(qw(frog elephant thing)); my $w3 = amb(qw(walked treaded grows)); my $w4 = amb(qw(slowly quickly)); amb() unless joined $w1, $w2; amb() unless joined $w2, $w3; amb() unless joined $w3, $w4; print "$w1 $w2 $w3 $w4\n"; exit(EXIT_SUCCESS);
1,148Amb
2perl
fzyd7
from time import time, sleep from threading import Thread class Integrator(Thread): 'continuously integrate a function `K`, at each `interval` seconds' def __init__(self, K=lambda t:0, interval=1e-4): Thread.__init__(self) self.interval = interval self.K = K self.S = 0.0 self.__run = True self.start() def run(self): interval = self.interval start = time() t0, k0 = 0, self.K(0) while self.__run: sleep(interval) t1 = time() - start k1 = self.K(t1) self.S += (k1 + k0)*(t1 - t0)/2.0 t0, k0 = t1, k1 def join(self): self.__run = False Thread.join(self) if __name__ == : from math import sin, pi ai = Integrator(lambda t: sin(pi*t)) sleep(2) print(ai.S) ai.K = lambda t: 0 sleep(0.5) print(ai.S)
1,157Active object
3python
l26cv
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "sort" ) func main() { r, err := http.Get("http:
1,152Anagrams
0go
6my3p
def fib(n) raise RangeError, if n < 0 (fib2 = proc { |m| m < 2? m: fib2[m - 1] + fib2[m - 2] })[n] end
1,138Anonymous recursion
14ruby
jki7x
public class Accumulator
1,159Accumulator factory
9java
9cfmu
(defn pad-class [n] (let [divs (filter #(zero? (mod n %)) (range 1 n)) divs-sum (reduce + divs)] (cond (< divs-sum n):deficient (= divs-sum n):perfect (> divs-sum n):abundant))) (def pad-classes (map pad-class (map inc (range)))) (defn count-classes [n] (let [classes (take n pad-classes)] {:perfect (count (filter #(= %:perfect) classes)) :abundant (count (filter #(= %:abundant) classes)) :deficient (count (filter #(= %:deficient) classes))}))
1,161Abundant, deficient and perfect number classifications
6clojure
dfwnb
import Foundation func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n% 2 == 0 { return n == 2 } if n% 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n% p == 0 { return false } p += 2 if n% p == 0 { return false } p += 4 } return true } func digitSum(_ num: Int) -> Int { var sum = 0 var n = num while n > 0 { sum += n% 10 n /= 10 } return sum } let limit = 500 print("Additive primes less than \(limit):") var count = 0 for n in 1..<limit { if isPrime(digitSum(n)) && isPrime(n) { count += 1 print(String(format: "%3d", n), terminator: count% 10 == 0? "\n": " ") } } print("\n\(count) additive primes found.")
1,154Additive primes
17swift
4gu5g
from prime_decomposition import decompose from itertools import islice, count try: from functools import reduce except: pass def almostprime(n, k=2): d = decompose(n) try: terms = [next(d) for i in range(k)] return reduce(int.__mul__, terms, 1) == n except: return False if __name__ == '__main__': for k in range(1,6): print('%i:%r'% (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
1,147Almost prime
3python
nf6iz
def words = new URL('http:
1,152Anagrams
7groovy
dtfn3
fn fib(n: i64) -> Option<i64> {
1,138Anonymous recursion
15rust
hbnj2
function accumulator(sum) { return function(n) { return sum += n; } } var x = accumulator(1); x(5); console.log(accumulator(3).toString() + '<br>'); console.log(x(2.3));
1,159Accumulator factory
10javascript
u5yvb
#![feature(mpsc_select)] extern crate num; extern crate schedule_recv; use num::traits::Zero; use num::Float; use schedule_recv::periodic_ms; use std::f64::consts::PI; use std::ops::Mul; use std::sync::mpsc::{self, SendError, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; pub type Actor<S> = Sender<Box<Fn(u32) -> S + Send>>; pub type ActorResult<S> = Result<(), SendError<Box<Fn(u32) -> S + Send>>>;
1,157Active object
15rust
u59vj
object ActiveObject { class Integrator { import java.util._ import scala.actors.Actor._ case class Pulse(t: Double) case class Input(k: Double => Double) case object Output case object Bye val timer = new Timer(true) var k: Double => Double = (_ => 0.0) var s: Double = 0.0 var t0: Double = 0.0 val handler = actor { loop { react { case Pulse(t1) => s += (k(t1) + k(t0)) * (t1 - t0) / 2.0; t0 = t1 case Input(k) => this.k = k case Output => reply(s) case Bye => timer.cancel; exit } } } timer.scheduleAtFixedRate(new TimerTask { val start = System.currentTimeMillis def run { handler ! Pulse((System.currentTimeMillis - start) / 1000.0) } }, 0, 10)
1,157Active object
16scala
gr24i
findfactors <- function(n) { d <- c() div <- 2; nxt <- 3; rest <- n while( rest != 1 ) { while( rest%%div == 0 ) { d <- c(d, div) rest <- floor(rest / div) } div <- nxt nxt <- nxt + 2 } d } almost_primes <- function(n = 10, k = 5) { res <- matrix(NA, nrow = k, ncol = n) rownames(res) <- paste("k = ", 1:k, sep = "") colnames(res) <- rep("", n) for (i in 1:k) { tmp <- 1 while (any(is.na(res[i, ]))) { if (length(findfactors(tmp)) == i) { res[i, which.max(is.na(res[i, ]))] <- tmp } tmp <- tmp + 1 } } print(res) }
1,147Almost prime
13r
0ofsg
import Data.List groupon f x y = f x == f y main = do f <- readFile "./../Puzzels/Rosetta/unixdict.txt" let words = lines f wix = groupBy (groupon fst) . sort $ zip (map sort words) words mxl = maximum $ map length wix mapM_ (print . map snd) . filter ((==mxl).length) $ wix
1,152Anagrams
8haskell
jkh7g
def Y[A, B](f: (A B) (A B)): A B = f(Y(f))(_) def fib(n: Int): Option[Int] = if (n < 0) None else Some(Y[Int, Int](f i if (i < 2) 1 else f(i - 1) + f(i - 2))(n)) -2 to 5 map (n (n, fib(n))) foreach println
1,138Anonymous recursion
16scala
patbj
null
1,159Accumulator factory
11kotlin
z38ts
def aliquot(n, maxlen=16, maxterm=2**47) return , [0] if n == 0 s = [] while (s << n).size <= maxlen and n < maxterm n = n.proper_divisors.inject(0,:+) if s.include?(n) case n when s[0] case s.size when 1 then return , s when 2 then return , s else return , s end when s[-1] then return , s else return , s end elsif n == 0 then return , s << 0 end end return , s end for n in 1..10 puts % aliquot(n) end puts for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080] puts % aliquot(n) end
1,151Aliquot sequence classifications
14ruby
7hhri
null
1,157Active object
17swift
2vylj
#[derive(Debug)] enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating } fn classify_aliquot(num: i64) -> (AliquotType, Vec<i64>) { let limit = 1i64 << 47;
1,151Aliquot sequence classifications
15rust
jkk72
function acc(init) init = init or 0 return function(delta) init = init + (delta or 0) return init end end
1,159Accumulator factory
1lua
36ozo
def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = { val sum = properDivisors(n).sum if (sum == 0) ("terminate", list ::: List(sum)) else if (step >= 16 || sum > 140737488355328L) ("non-term", list) else { list.indexOf(sum) match { case -1 => createAliquotSeq(sum, step + 1, list ::: List(sum)) case 0 => if (step == 0) ("perfect", list ::: List(sum)) else if (step == 1) ("amicable", list ::: List(sum)) else ("sociable-" + (step + 1), list ::: List(sum)) case index => if (step == index) ("aspiring", list ::: List(sum)) else ("cyclic-" + (step - index + 1), list ::: List(sum)) } } } val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080L) val result = numbers.map(i => createAliquotSeq(i, 0, List(i))) result foreach { v => println(f"${v._2.head}%14d ${v._1}%10s [${v._2 mkString " "}]" ) }
1,151Aliquot sequence classifications
16scala
b11k6
require 'prime' def almost_primes(k=2) return to_enum(:almost_primes, k) unless block_given? 1.step {|n| yield n if n.prime_division.sum( &:last ) == k } end (1..5).each{|k| puts almost_primes(k).take(10).join()}
1,147Almost prime
14ruby
fzmdr
import java.net.*; import java.io.*; import java.util.*; public class WordsOfEqChars { public static void main(String[] args) throws IOException { URL url = new URL("http:
1,152Anagrams
9java
u45vv
import itertools as _itertools class Amb(object): def __init__(self): self._names2values = {} self._func = None self._valueiterator = None self._funcargnames = None def __call__(self, arg=None): if hasattr(arg, '__code__'): globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals argv = arg.__code__.co_varnames[:arg.__code__.co_argcount] for name in argv: if name not in self._names2values: assert name in globls, \ % name self._names2values[name] = globls[name] valuesets = [self._names2values[name] for name in argv] self._valueiterator = _itertools.product(*valuesets) self._func = arg self._funcargnames = argv return self elif arg is not None: arg = frozenset(arg) return arg else: return self._nextinsearch() def _nextinsearch(self): arg = self._func globls = arg.__globals__ argv = self._funcargnames found = False for values in self._valueiterator: if arg(*values): found = True for n, v in zip(argv, values): globls[n] = v break if not found: raise StopIteration return values def __iter__(self): return self def __next__(self): return self() next = __next__ if __name__ == '__main__': if True: amb = Amb() print() x = amb(range(1,11)) y = amb(range(1,11)) z = amb(range(1,11)) for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ): print ('%s%s%s'% (x, y, z)) if True: amb = Amb() print() w1 = amb([, , ]) w2 = amb([, , ]) w3 = amb([, , ]) w4 = amb([, ]) for _dummy in amb( lambda w1, w2, w3, w4: \ w1[-1] == w2[0] and \ w2[-1] == w3[0] and \ w3[-1] == w4[0] ): print ('%s%s%s%s'% (w1, w2, w3, w4)) if True: amb = Amb() print( ) x = amb([1, 2, 3]) y = amb([4, 5, 6]) for _dummy in amb( lambda x, y: x * y != 8 ): print ('%s%s'% (x, y))
1,148Amb
3python
t3mfw
extension BinaryInteger { @inlinable public func factors(sorted: Bool = true) -> [Self] { let maxN = Self(Double(self).squareRoot()) var res = Set<Self>() for factor in stride(from: 1, through: maxN, by: 1) where self% factor == 0 { res.insert(factor) res.insert(self / factor) } return sorted? res.sorted(): Array(res) } } struct SeqClass: CustomStringConvertible { var seq: [Int] var desc: String var description: String { return "\(desc): \(seq)" } } func classifySequence(k: Int, threshold: Int = 1 << 47) -> SeqClass { var last = k var seq = [k] while true { last = last.factors().dropLast().reduce(0, +) seq.append(last) let n = seq.count if last == 0 { return SeqClass(seq: seq, desc: "Terminating") } else if n == 2 && last == k { return SeqClass(seq: seq, desc: "Perfect") } else if n == 3 && last == k { return SeqClass(seq: seq, desc: "Amicable") } else if n >= 4 && last == k { return SeqClass(seq: seq, desc: "Sociable[\(n - 1)]") } else if last == seq[n - 2] { return SeqClass(seq: seq, desc: "Aspiring") } else if seq.dropFirst().dropLast(2).contains(last) { return SeqClass(seq: seq, desc: "Cyclic[\(n - 1 - seq.firstIndex(of: last)!)]") } else if n == 16 || last > threshold { return SeqClass(seq: seq, desc: "Non-terminating") } } fatalError() } for i in 1...10 { print("\(i): \(classifySequence(k: i))") } print() for i in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] { print("\(i): \(classifySequence(k: i))") } print() print("\(15355717786080): \(classifySequence(k: 15355717786080))")
1,151Aliquot sequence classifications
17swift
rjjgg
fn is_kprime(n: u32, k: u32) -> bool { let mut primes = 0; let mut f = 2; let mut rem = n; while primes < k && rem > 1{ while (rem% f) == 0 && rem > 1{ rem /= f; primes += 1; } f += 1; } rem == 1 && primes == k } struct KPrimeGen { k: u32, n: u32, } impl Iterator for KPrimeGen { type Item = u32; fn next(&mut self) -> Option<u32> { self.n += 1; while!is_kprime(self.n, self.k) { self.n += 1; } Some(self.n) } } fn kprime_generator(k: u32) -> KPrimeGen { KPrimeGen {k: k, n: 1} } fn main() { for k in 1..6 { println!("{}: {:?}", k, kprime_generator(k).take(10).collect::<Vec<_>>()); } }
1,147Almost prime
15rust
t39fd
def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match { case (n, k, _) if n == 1 => k == 0 case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d) case (_, _, _) => isKPrime(n, k, d + 1) } def kPrimeStream(k: Int): Stream[Int] = { def loop(n: Int): Stream[Int] = if (isKPrime(n, k)) n #:: loop(n+ 1) else loop(n + 1) loop(2) } for (k <- 1 to 5) { println( s"$k: [${ kPrimeStream(k).take(10) mkString " " }]" ) }
1,147Almost prime
16scala
6m231
var fs = require('fs'); var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n'); var i, item, max = 0, anagrams = {}; for (i = 0; i < words.length; i += 1) { var key = words[i].split('').sort().join(''); if (!anagrams.hasOwnProperty(key)) {
1,152Anagrams
10javascript
7hjrd
h = {} (1..20_000).each{|n| h[n] = n.proper_divisors.sum } h.select{|k,v| h[v] == k && k < v}.each do |key,val| puts end
1,144Amicable pairs
14ruby
2uhlw
checkSentence <- function(sentence){ for (index in 1:(length(sentence)-1)){ first.word <- sentence[index] second.word <- sentence[index+1] last.letter <- substr(first.word, nchar(first.word), nchar(first.word)) first.letter <- substr(second.word, 1, 1) if (last.letter!= first.letter){ return(FALSE) } } return(TRUE) } amb <- function(sets){ all.paths <- apply(expand.grid(sets), 2, as.character) all.paths.list <- split(all.paths, 1:nrow(all.paths)) winners <- all.paths.list[sapply(all.paths.list, checkSentence)] return(winners) }
1,148Amb
13r
idzo5
fn sum_of_divisors(val: u32) -> u32 { (1..val/2+1).filter(|n| val% n == 0) .fold(0, |sum, n| sum + n) } fn main() { let iter = (1..20_000).map(|i| (i, sum_of_divisors(i))) .filter(|&(i, div_sum)| i > div_sum); for (i, sum1) in iter { if sum_of_divisors(sum1) == i { println!("{} {}", i, sum1); } } }
1,144Amicable pairs
15rust
v5k2t
use strict; use warnings; use Math::BigInt; sub binomial { Math::BigInt->new(shift)->bnok(shift) } sub binprime { my $p = shift; return 0 unless $p >= 2; for (1 .. ($p>>1)) { return 0 if binomial($p,$_) % $p } 1; } sub coef { my($n,$e) = @_; return $n unless $e; $n = "" if $n==1; $e==1 ? "${n}x" : "${n}x^$e"; } sub binpoly { my $p = shift; join(" ", coef(1,$p), map { join("",("+","-")[($p-$_)&1]," ",coef(binomial($p,$_),$_)) } reverse 0..$p-1 ); } print "expansions of (x-1)^p:\n"; print binpoly($_),"\n" for 0..9; print "Primes to 80: [", join(",", grep { binprime($_) } 2..80), "]\n";
1,153AKS test for primes
2perl
0o0s4
struct KPrimeGen: Sequence, IteratorProtocol { let k: Int private(set) var n: Int private func isKPrime() -> Bool { var primes = 0 var f = 2 var rem = n while primes < k && rem > 1 { while rem% f == 0 && rem > 1 { rem /= f primes += 1 } f += 1 } return rem == 1 && primes == k } mutating func next() -> Int? { n += 1 while!isKPrime() { n += 1 } return n } } for k in 1..<6 { print("\(k): \(Array(KPrimeGen(k: k, n: 1).lazy.prefix(10)))") }
1,147Almost prime
17swift
dtynh
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1)) println( result mkString ", " )
1,144Amicable pairs
16scala
4r150
null
1,147Almost prime
20typescript
5ghu4
let fib: Int -> Int = { func f(n: Int) -> Int { assert(n >= 0, "fib: no negative numbers") return n < 2? 1: f(n-1) + f(n-2) } return f }() print(fib(8))
1,138Anonymous recursion
17swift
7horq
require class Amb class ExhaustedError < RuntimeError; end def initialize @fail = proc { fail ExhaustedError, } end def choose(*choices) prev_fail = @fail callcc { |sk| choices.each { |choice| callcc { |fk| @fail = proc { @fail = prev_fail fk.call(:fail) } if choice.respond_to? :call sk.call(choice.call) else sk.call(choice) end } } @fail.call } end def failure choose end def assert(cond) failure unless cond end end A = Amb.new w1 = A.choose(, , ) w2 = A.choose(, , ) w3 = A.choose(, , ) w4 = A.choose(, ) A.choose() unless w1[-1] == w2[0] A.choose() unless w2[-1] == w3[0] A.choose() unless w3[-1] == w4[0] puts w1, w2, w3, w4
1,148Amb
14ruby
3ycz7
import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL import kotlin.math.max fun main() { val url = URL("http:
1,152Anagrams
11kotlin
9lcmh
use std::ops::Add; struct Amb<'a> { list: Vec<Vec<&'a str>>, } fn main() { let amb = Amb { list: vec![ vec!["the", "that", "a"], vec!["frog", "elephant", "thing"], vec!["walked", "treaded", "grows"], vec!["slowly", "quickly"], ], }; match amb.do_amb(0, 0 as char) { Some(text) => println!("{}", text), None => println!("Nothing found"), } } impl<'a> Amb<'a> { fn do_amb(&self, level: usize, last_char: char) -> Option<String> { if self.list.is_empty() { panic!("No word list"); } if self.list.len() <= level { return Some(String::new()); } let mut res = String::new(); let word_list = &self.list[level]; for word in word_list { if word.chars().next().unwrap() == last_char || last_char == 0 as char { res = res.add(word).add(" "); let answ = self.do_amb(level + 1, word.chars().last().unwrap()); match answ { Some(x) => { res = res.add(&x); return Some(res); } None => res.clear(), } } } None } }
1,148Amb
15rust
6ml3l
import func Darwin.sqrt func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) } func properDivs(n: Int) -> [Int] { if n == 1 { return [] } var result = [Int]() for div in filter (1...sqrt(n), { n% $0 == 0 }) { result.append(div) if n/div!= div && n/div!= n { result.append(n/div) } } return sorted(result) } func sumDivs(n:Int) -> Int { struct Cache { static var sum = [Int:Int]() } if let sum = Cache.sum[n] { return sum } let sum = properDivs(n).reduce(0) { $0 + $1 } Cache.sum[n] = sum return sum } func amicable(n:Int, m:Int) -> Bool { if n == m { return false } if sumDivs(n)!= m || sumDivs(m)!= n { return false } return true } var pairs = [(Int, Int)]() for n in 1 ..< 20_000 { for m in n+1 ... 20_000 { if amicable(n, m) { pairs.append(n, m) println("\(n, m)") } } }
1,144Amicable pairs
17swift
lvjc2
object Amb { def amb(wss: List[List[String]]): Option[String] = { def _amb(ws: List[String], wss: List[List[String]]): Option[String] = wss match { case Nil => ((Some(ws.head): Option[String]) /: ws.tail)((a, w) => a match { case Some(x) => if (x.last == w.head) Some(x + " " + w) else None case None => None }) case ws1 :: wss1 => ws1.flatMap(w => _amb(w :: ws, wss1)).headOption } _amb(Nil, wss.reverse) } def main(args: Array[String]) { println(amb(List(List("the", "that", "a"), List("frog", "elephant", "thing"), List("walked", "treaded", "grows"), List("slowly", "quickly")))) } }
1,148Amb
16scala
9lum5
sub accumulator { my $sum = shift; sub { $sum += shift } } my $x = accumulator(1); $x->(5); accumulator(3); print $x->(2.3), "\n";
1,159Accumulator factory
2perl
bp4k4
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
1,160Align columns
0go
jh27d
def expand_x_1(n): c =1 for i in range(n c = c*(n-i) yield c def aks(p): if p==2: return True for i in expand_x_1(p): if i% p: return False return True
1,153AKS test for primes
3python
8i80o
function sort(word) local bytes = {word:byte(1, -1)} table.sort(bytes) return string.char(table.unpack(bytes)) end
1,152Anagrams
1lua
c2l92
<?php function accumulator($start){ return create_function('$x','static $v='.$start.';return $v+=$x;'); } $acc = accumulator(5); echo $acc(5), ; echo $acc(10), ; ?>
1,159Accumulator factory
12php
6yi3g
int ackermann(int m, int n) { if (!m) return n + 1; if (!n) return ackermann(m - 1, 1); return ackermann(m - 1, ackermann(m, n - 1)); } int main() { int m, n; for (m = 0; m <= 4; m++) for (n = 0; n < 6 - m; n++) printf(, m, n, ackermann(m, n)); return 0; }
1,162Ackermann function
5c
dfenv
def alignColumns = { align, rawText -> def lines = rawText.tokenize('\n') def words = lines.collect { it.tokenize(/\$/) } def maxLineWords = words.collect {it.size()}.max() words = words.collect { line -> line + [''] * (maxLineWords - line.size()) } def columnWidths = words.transpose().collect{ column -> column.collect { it.size() }.max() } def justify = [ Right : { width, string -> string.padLeft(width) }, Left : { width, string -> string.padRight(width) }, Center: { width, string -> string.center(width) } ] def padAll = { pad, colWidths, lineWords -> [colWidths, lineWords].transpose().collect { pad(it) + ' ' } } words.each { padAll(justify[align], columnWidths, it).each { print it }; println() } }
1,160Align columns
7groovy
54yuv
AKS<-function(p){ i<-2:p-1 l<-unique(factorial(p) / (factorial(p-i) * factorial(i))) if(all(l%%p==0)){ print(noquote("It is prime.")) }else{ print(noquote("It isn't prime.")) } }
1,153AKS test for primes
13r
xsxw2
import Data.List (unfoldr, transpose) import Control.Arrow (second) dat = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" ++ "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" ++ "column$are$separated$by$at$least$one$space.\n" ++ "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" ++ "justified,$right$justified,$or$center$justified$within$its$column.\n" brkdwn = takeWhile (not . null) . unfoldr (Just . second (drop 1) . span ('$' /=)) format j ls = map (unwords . zipWith align colw) rows where rows = map brkdwn $ lines ls colw = map (maximum . map length) . transpose $ rows align cw w = case j of 'c' -> replicate l ' ' ++ w ++ replicate r ' ' 'r' -> replicate dl ' ' ++ w 'l' -> w ++ replicate dl ' ' where dl = cw - length w (l, r) = (dl `div` 2, dl - l)
1,160Align columns
8haskell
oia8p
>>> def accumulator(sum): def f(n): f.sum += n return f.sum f.sum = sum return f >>> x = accumulator(1) >>> x(5) 6 >>> x(2.3) 8.3000000000000007 >>> x = accumulator(1) >>> x(5) 6 >>> x(2.3) 8.3000000000000007 >>> x2 = accumulator(3) >>> x2(5) 8 >>> x2(3.3) 11.300000000000001 >>> x(0) 8.3000000000000007 >>> x2(0) 11.300000000000001
1,159Accumulator factory
3python
p1gbm
require 'polynomial' def x_minus_1_to_the(p) return Polynomial.new(-1,1)**p end def prime?(p) return false if p < 2 (x_minus_1_to_the(p) - Polynomial.from_string()).coefs.all?{|n| n%p==0} end 8.times do |n| puts end puts , 50.times.select {|n| prime? n}.join(',')
1,153AKS test for primes
14ruby
idioh
accumulatorFactory <- function(init) { currentSum <- init function(add) { currentSum <<- currentSum + add currentSum } }
1,159Accumulator factory
13r
jhv78
fn aks_coefficients(k: usize) -> Vec<i64> { let mut coefficients = vec![0i64; k + 1]; coefficients[0] = 1; for i in 1..(k + 1) { coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{ let old = coefficients[j]; coefficients[j] = old - prev; old }); } coefficients } fn is_prime(p: usize) -> bool { if p < 2 { false } else { let c = aks_coefficients(p); (1..p / 2 + 1).all(|i| c[i]% p as i64 == 0) } } fn main() { for i in 0..8 { println!("{}: {:?}", i, aks_coefficients(i)); } for i in (1..=50).filter(|&i| is_prime(i)) { print!("{} ", i); } }
1,153AKS test for primes
15rust
nfni4
package main import "fmt" func pfacSum(i int) int { sum := 0 for p := 1; p <= i/2; p++ { if i%p == 0 { sum += p } } return sum } func main() { var d, a, p = 0, 0, 0 for i := 1; i <= 20000; i++ { j := pfacSum(i) if j < i { d++ } else if j == i { p++ } else { a++ } } fmt.Printf("There are%d deficient numbers between 1 and 20000\n", d) fmt.Printf("There are%d abundant numbers between 1 and 20000\n", a) fmt.Printf("There are%d perfect numbers between 1 and 20000\n", p) }
1,161Abundant, deficient and perfect number classifications
0go
u53vt
def powerMin1(n: BigInt) = if (n % 2 == 0) BigInt(1) else BigInt(-1) val pascal = (( Vector(Vector(BigInt(1))) /: (1 to 50)) { (rows, i) => val v = rows.head val newVector = ((1 until v.length) map (j => powerMin1(j+i) * (v(j-1).abs + v(j).abs)) ).toVector (powerMin1(i) +: newVector :+ powerMin1(i+v.length)) +: rows }).reverse def poly2String(poly: Vector[BigInt]) = ((0 until poly.length) map { i => (i, poly(i)) match { case (0, c) => c.toString case (_, c) => (if (c >= 0) "+" else "-") + (if (c == 1) "x" else c.abs + "x") + (if (i == 1) "" else "^" + i) } }) mkString "" def isPrime(n: Int) = { val poly = pascal(n) poly.slice(1, poly.length - 1).forall(i => i % n == 0) } for(i <- 0 to 7) { println( f"(x-1)^$i = ${poly2String( pascal(i) )}" ) } val primes = (2 to 50).filter(isPrime) println println(primes mkString " ")
1,153AKS test for primes
16scala
t3tfb
(defn ackermann [m n] (cond (zero? m) (inc n) (zero? n) (ackermann (dec m) 1) :else (ackermann (dec m) (ackermann m (dec n)))))
1,162Ackermann function
6clojure
6y03q
def dpaCalc = { factors -> def n = factors.pop() def fSum = factors.sum() fSum < n ? 'deficient' : fSum > n ? 'abundant' : 'perfect' } (1..20000).inject([deficient:0, perfect:0, abundant:0]) { map, n -> map[dpaCalc(factorize(n))]++ map } .each { e -> println e }
1,161Abundant, deficient and perfect number classifications
7groovy
9cnm4
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ColumnAligner { private List<String[]> words = new ArrayList<>(); private int columns = 0; private List<Integer> columnWidths = new ArrayList<>(); public ColumnAligner(String s) { String[] lines = s.split("\\n"); for (String line : lines) { processInputLine(line); } } public ColumnAligner(List<String> lines) { for (String line : lines) { processInputLine(line); } } private void processInputLine(String line) { String[] lineWords = line.split("\\$"); words.add(lineWords); columns = Math.max(columns, lineWords.length); for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i >= columnWidths.size()) { columnWidths.add(word.length()); } else { columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); } } } interface AlignFunction { String align(String s, int length); } public String alignLeft() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.rightPad(s, length); } }); } public String alignRight() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.leftPad(s, length); } }); } public String alignCenter() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.center(s, length); } }); } private String align(AlignFunction a) { StringBuilder result = new StringBuilder(); for (String[] lineWords : words) { for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i == 0) { result.append("|"); } result.append(a.align(word, columnWidths.get(i)) + "|"); } result.append("\n"); } return result.toString(); } public static void main(String args[]) throws IOException { if (args.length < 1) { System.out.println("Usage: ColumnAligner file [left|right|center]"); return; } String filePath = args[0]; String alignment = "left"; if (args.length >= 2) { alignment = args[1]; } ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); switch (alignment) { case "left": System.out.print(ca.alignLeft()); break; case "right": System.out.print(ca.alignRight()); break; case "center": System.out.print(ca.alignCenter()); break; default: System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); break; } } }
1,160Align columns
9java
wxjej
def accumulator(sum) lambda {|n| sum += n} end x = accumulator(1) x.call(5) accumulator(3) puts x.call(2.3)
1,159Accumulator factory
14ruby
ae71s
divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] classOf :: (Integral a) => a -> Ordering classOf n = compare (sum $ divisors n) n main :: IO () main = do let classes = map classOf [1 .. 20000 :: Int] printRes w c = putStrLn $ w ++ (show . length $ filter (== c) classes) printRes "deficient: " LT printRes "perfect: " EQ printRes "abundant: " GT
1,161Abundant, deficient and perfect number classifications
8haskell
wx7ed
var justification="center", input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column."], x,y,cols,max,cols=0,diff,left,right String.prototype.repeat=function(n){return new Array(1 + parseInt(n)).join(this);} for(x=0;x<input.length;x++) { input[x]=input[x].split("$"); if(input[x].length>cols) cols=input[x].length; } for(x=0;x<cols;x++) { max=0; for(y=0;y<input.length;y++) if(input[y][x]&&max<input[y][x].length) max=input[y][x].length; for(y=0;y<input.length;y++) if(input[y][x]) { diff=(max-input[y][x].length)/2; left=" ".repeat(Math.floor(diff)); right=" ".repeat(Math.ceil(diff)); if(justification=="left") {right+=left;left=""} if(justification=="right") {left+=right;right=""} input[y][x]=left+input[y][x]+right; } } for(x=0;x<input.length;x++) input[x]=input[x].join(" "); input=input.join("\n"); document.write(input);
1,160Align columns
10javascript
8o10l
null
1,159Accumulator factory
15rust
ewjaj
def AccumulatorFactory[N](n: N)(implicit num: Numeric[N]) = { import num._ var acc = n (inc: N) => { acc = acc + inc acc } }
1,159Accumulator factory
16scala
qsbxw
import java.util.stream.LongStream; public class NumberClassifications { public static void main(String[] args) { int deficient = 0; int perfect = 0; int abundant = 0; for (long i = 1; i <= 20_000; i++) { long sum = properDivsSum(i); if (sum < i) deficient++; else if (sum == i) perfect++; else abundant++; } System.out.println("Deficient: " + deficient); System.out.println("Perfect: " + perfect); System.out.println("Abundant: " + abundant); } public static long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n != i && n % i == 0).sum(); } }
1,161Abundant, deficient and perfect number classifications
9java
kbvhm
func polynomialCoeffs(n: Int) -> [Int] { var result = [Int](count: n+1, repeatedValue: 0) result[0]=1 for i in 1 ..< n/2+1 {
1,153AKS test for primes
17swift
ono8k
for (var dpa=[1,0,0], n=2; n<=20000; n+=1) { for (var ds=0, d=1, e=n/2+1; d<e; d+=1) if (n%d==0) ds+=d dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1 } document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' )
1,161Abundant, deficient and perfect number classifications
10javascript
ewrao
func makeAccumulator(var sum: Double) -> Double -> Double { return { sum += $0 return sum } } let x = makeAccumulator(1) x(5) let _ = makeAccumulator(3) println(x(2.3))
1,159Accumulator factory
17swift
1arpt
import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths enum class AlignFunction { LEFT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + s.length + 's').format(s)) }, RIGHT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + l + 's').format(s)) }, CENTER { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + ((l + s.length) / 2) + 's').format(s)) }; abstract operator fun invoke(s: String, l: Int): String } class ColumnAligner(val lines: List<String>) { operator fun invoke(a: AlignFunction) : String { var result = "" for (lineWords in words) { for (i in lineWords.indices) { if (i == 0) result += '|' result += a(lineWords[i], column_widths[i]) result += '|' } result += '\n' } return result } private val words = arrayListOf<Array<String>>() private val column_widths = arrayListOf<Int>() init { lines.forEach { val lineWords = java.lang.String(it).split("\\$") words += lineWords for (i in lineWords.indices) { if (i >= column_widths.size) { column_widths += lineWords[i].length } else { column_widths[i] = Math.max(column_widths[i], lineWords[i].length) } } } } } fun main(args: Array<String>) { if (args.isEmpty()) { println("Usage: ColumnAligner file [L|R|C]") return } val ca = ColumnAligner(Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8)) val alignment = if (args.size >= 2) args[1] else "L" when (alignment) { "L" -> print(ca(AlignFunction.LEFT)) "R" -> print(ca(AlignFunction.RIGHT)) "C" -> print(ca(AlignFunction.CENTER)) else -> System.err.println("Error! Unknown alignment: " + alignment) } }
1,160Align columns
11kotlin
bp5kb
null
1,161Abundant, deficient and perfect number classifications
11kotlin
grm4d
local tWord = {}
1,160Align columns
1lua
p14bw
use List::Util 'max'; my @words = split "\n", do { local( @ARGV, $/ ) = ( 'unixdict.txt' ); <> }; my %anagram; for my $word (@words) { push @{ $anagram{join '', sort split '', $word} }, $word; } my $count = max(map {scalar @$_} values %anagram); for my $ana (values %anagram) { print "@$ana\n" if @$ana == $count; }
1,152Anagrams
2perl
wqxe6
int A(int m, int n) => m==0? n+1: n==0? A(m-1,1): A(m-1,A(m,n-1)); main() { print(A(0,0)); print(A(1,0)); print(A(0,1)); print(A(2,2)); print(A(2,3)); print(A(3,3)); print(A(3,4)); print(A(3,5)); print(A(4,0)); }
1,162Ackermann function
18dart
s0hq6
function sumDivs (n) if n < 2 then return 0 end local sum, sr = 1, math.sqrt(n) for d = 2, sr do if n % d == 0 then sum = sum + d if d ~= sr then sum = sum + n / d end end end return sum end local a, d, p, Pn = 0, 0, 0 for n = 1, 20000 do Pn = sumDivs(n) if Pn > n then a = a + 1 end if Pn < n then d = d + 1 end if Pn == n then p = p + 1 end end print("Abundant:", a) print("Deficient:", d) print("Perfect:", p)
1,161Abundant, deficient and perfect number classifications
1lua
r79ga
<?php $words = explode(, file_get_contents('http: foreach ($words as $word) { $chars = str_split($word); sort($chars); $anagram[implode($chars)][] = $word; } $best = max(array_map('count', $anagram)); foreach ($anagram as $ana) if (count($ana) == $best) print_r($ana); ?>
1,152Anagrams
12php
lv2cj
use ntheory qw/divisor_sum/; my @type = <Perfect Abundant Deficient>; say join "\n", map { sprintf "%2d%s", $_, $type[divisor_sum($_)-$_ <=> $_] } 1..12; my %h; $h{divisor_sum($_)-$_ <=> $_}++ for 1..20000; say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}";
1,161Abundant, deficient and perfect number classifications
2perl
ndeiw
>>> import urllib.request >>> from collections import defaultdict >>> words = urllib.request.urlopen('http: >>> anagram = defaultdict(list) >>> for word in words: anagram[tuple(sorted(word))].append( word ) >>> count = max(len(ana) for ana in anagram.values()) >>> for ana in anagram.values(): if len(ana) >= count: print ([x.decode() for x in ana])
1,152Anagrams
3python
xsqwr
words <- readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") word_group <- sapply( strsplit(words, split=""), function(x) paste(sort(x), collapse="") ) counts <- tapply(words, word_group, length) anagrams <- tapply(words, word_group, paste, collapse=", ") table(counts) counts 1 2 3 4 5 22263 1111 155 31 6 anagrams[counts == max(counts)] abel acert "abel, able, bale, bela, elba" "caret, carte, cater, crate, trace" aegln aeglr "angel, angle, galen, glean, lange" "alger, glare, lager, large, regal" aeln eilv "elan, lane, lean, lena, neal" "evil, levi, live, veil, vile"
1,152Anagrams
13r
1eapn
use strict ; die "Call: perl columnaligner.pl <inputfile> <printorientation>!\n" unless @ARGV == 2 ; die "last argument must be one of center, left or right!\n" unless $ARGV[ 1 ] =~ /center|left|right/ ; sub printLines( $$$ ) ; open INFILE , "<" , "$ARGV[ 0 ]" or die "Can't open $ARGV[ 0 ]!\n" ; my @lines = <INFILE> ; close INFILE ; chomp @lines ; my @fieldwidths = map length, split /\$/ , $lines[ 0 ] ; foreach my $i ( 1..$ my @words = split /\$/ , $lines[ $i ] ; foreach my $j ( 0..$ if ( $j <= $ if ( length $words[ $j ] > $fieldwidths[ $j ] ) { $fieldwidths[ $j ] = length $words[ $j ] ; } } else { push @fieldwidths, length $words[ $j ] ; } } } printLine( $_ , $ARGV[ 1 ] , \@fieldwidths ) foreach @lines ; sub printLine { my $line = shift ; my $orientation = shift ; my $widthref = shift ; my @words = split /\$/, $line ; foreach my $k ( 0..$ my $printwidth = $widthref->[ $k ] + 1 ; if ( $orientation eq 'center' ) { $printwidth++ ; } if ( $orientation eq 'left' ) { print $words[ $k ] ; print " " x ( $printwidth - length $words[ $k ] ) ; } elsif ( $orientation eq 'right' ) { print " " x ( $printwidth - length $words[ $k ] ) ; print $words[ $k ] ; } elsif ( $orientation eq 'center' ) { my $left = int( ( $printwidth - length $words[ $k ] ) / 2 ) ; my $right = $printwidth - length( $words[ $k ] ) - $left ; print " " x $left ; print $words[ $k ] ; print " " x $right ; } } print "\n" ; }
1,160Align columns
2perl
6yo36
>>> from proper_divisors import proper_divs >>> from collections import Counter >>> >>> rangemax = 20000 >>> >>> def pdsum(n): ... return sum(proper_divs(n)) ... >>> def classify(n, p): ... return 'perfect' if n == p else 'abundant' if p > n else 'deficient' ... >>> classes = Counter(classify(n, pdsum(n)) for n in range(1, 1 + rangemax)) >>> classes.most_common() [('deficient', 15043), ('abundant', 4953), ('perfect', 4)] >>>
1,161Abundant, deficient and perfect number classifications
3python
dfwn1
require(numbers); propdivcls <- function(n) { V <- sapply(1:n, Sigma, proper = TRUE); c1 <- c2 <- c3 <- 0; for(i in 1:n){ if(V[i]<i){c1 = c1 +1} else if(V[i]==i){c2 = c2 +1} else{c3 = c3 +1} } cat(" *** Between 1 and ", n, ":\n"); cat(" * ", c1, "deficient numbers\n"); cat(" * ", c2, "perfect numbers\n"); cat(" * ", c3, "abundant numbers\n"); } propdivcls(20000);
1,161Abundant, deficient and perfect number classifications
13r
8op0x
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode(, $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields)? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields)? $fields[$col] : , $maxwidth, ' ', $justtype); unset($fields); } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . ; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
1,160Align columns
12php
1agpq
require 'open-uri' anagram = Hash.new {|hash, key| hash[key] = []} URI.open('http: words = f.read.split for word in words anagram[word.split('').sort] << word end end count = anagram.values.map {|ana| ana.length}.max anagram.each_value do |ana| if ana.length >= count p ana end end
1,152Anagrams
14ruby
s80qw
res = (1 .. 20_000).map{|n| n.proper_divisors.sum <=> n }.tally puts
1,161Abundant, deficient and perfect number classifications
14ruby
tzqf2
fn main() {
1,161Abundant, deficient and perfect number classifications
15rust
z3sto
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) def classifier(i: Int) = properDivisors(i).sum compare i val groups = (1 to 20000).groupBy( classifier ) println("Deficient: " + groups(-1).length) println("Abundant: " + groups(1).length) println("Perfect: " + groups(0).length + " (" + groups(0).mkString(",") + ")")
1,161Abundant, deficient and perfect number classifications
16scala
ymo63
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead,BufReader}; use std::borrow::ToOwned; extern crate unicode_segmentation; use unicode_segmentation::{UnicodeSegmentation}; fn main () { let file = BufReader::new(File::open("unixdict.txt").unwrap()); let mut map = HashMap::new(); for line in file.lines() { let s = line.unwrap();
1,152Anagrams
15rust
0o8sl