code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
-- set up list 1
CREATE TABLE L1 (VALUE INTEGER);
INSERT INTO L1 VALUES (1);
INSERT INTO L1 VALUES (2);
-- set up list 2
CREATE TABLE L2 (VALUE INTEGER);
INSERT INTO L2 VALUES (3);
INSERT INTO L2 VALUES (4);
-- get the product
SELECT * FROM L1, L2; | 1,058Cartesian product of two or more lists
| 19sql
| es4au |
cats1 :: [Integer]
cats1 =
(div . product . (enumFromTo . (2 +) <*> (2 *)))
<*> (product . enumFromTo 1) <$> [0 ..]
cats2 :: [Integer]
cats2 =
1:
fmap
(\n -> sum (zipWith (*) (reverse (take n cats2)) cats2))
[1 ..]
cats3 :: [Integer]
cats3 =
scanl
(\c n -> c * 2 * (2 * n - 1) `div` succ n)
1
[1 ..]
main :: IO ()
main = mapM_ (print . take 15) [cats1, cats2, cats3] | 1,068Catalan numbers
| 8haskell
| zm7t0 |
(require '[clojure.string:only [join]:refer [join]])
(def day-row "Su Mo Tu We Th Fr Sa")
(def col-width (count day-row))
(defn month-to-word
"Translate a month from 0 to 11 into its word representation."
[month]
((vec (.getMonths (new java.text.DateFormatSymbols))) month))
(defn month [date]
(.get date (java.util.Calendar/MONTH)))
(defn total-days-in-month [date]
(.getActualMaximum date (java.util.Calendar/DAY_OF_MONTH)))
(defn first-weekday [date]
(.get date (java.util.Calendar/DAY_OF_WEEK)))
(defn normal-date-string
"Returns a formatted list of strings of the days of the month."
[date]
(map #(join " " %)
(partition 7
(concat
(repeat (dec (first-weekday date)) " ")
(map #(format "%2s" %)
(range 1 (inc (total-days-in-month date))))
(repeat (- 42 (total-days-in-month date)
(dec (first-weekday date)) ) " ")))))
(defn oct-1582-string
"Returns a formatted list of strings of the days of the month of October 1582."
[date]
(map #(join " " %)
(partition 7
(concat
(repeat (dec (first-weekday date)) " ")
(map #(format "%2s" %)
(concat (range 1 5)
(range 15 (inc (total-days-in-month date)))))
(repeat (- 42
(count (concat (range 1 5)
(range 15
(inc (total-days-in-month date)))))
(dec (first-weekday date)) ) " ")))))
(defn center-string
"Returns a string that is WIDTH long with STRING centered in it."
[string width]
(let [pad (- width (count string))
lpad (quot pad 2)
rpad (- pad (quot pad 2))]
(if (<= pad 0)
string
(str (apply str (repeat lpad " "))
string
(apply str (repeat rpad " "))))))
(defn calc-columns
"Calculates the number of columns given the width in CHARACTERS and the
MARGIN SIZE."
[characters margin-size]
(loop [cols 0 excess characters ]
(if (>= excess col-width)
(recur (inc cols) (- excess (+ margin-size col-width)))
cols)))
(defn month-vector
"Returns a vector with the month name, day-row and days
formatted for printing."
[date]
(vec (concat
(vector (center-string (month-to-word (month date)) col-width))
(vector day-row)
(if (and (= 1582 (.get date (java.util.Calendar/YEAR)))
(= 9 (month date)))
(oct-1582-string date)
(normal-date-string date)))))
(defn year-vector [date]
"Returns a 2d vector of all the months in the year of DATE."
(loop [m [] c (month date)]
(if (= c 11 )
(conj m (month-vector date))
(recur (conj m (month-vector date))
(do (.add date (java.util.Calendar/MONTH ) 1)
(month date))))))
(defn print-months
"Prints the months to standard output with NCOLS and MARGIN."
[ v ncols margin]
(doseq [r (range (Math/ceil (/ 12 ncols)))]
(do (doseq [i (range 8)]
(do (doseq [c (range (* r ncols) (* (+ r 1) ncols))
:while (< c 12)]
(printf (str (apply str (repeat margin " ")) "%s")
(get-in v [c i])))
(println)))
(println))))
(defn print-cal
"(print-cal [year [width [margin]]])
Prints out the calendar for a given YEAR with WIDTH characters wide and
with MARGIN spaces between months."
([]
(print-cal 1969 80 2))
([year]
(print-cal year 80 2))
([year width]
(print-cal year width 2))
([year width margin]
(assert (>= width (count day-row)) "Width should be more than 20.")
(assert (> margin 0) "Margin needs to be more than 0.")
(let [date (new java.util.GregorianCalendar year 0 1)
column-count (calc-columns width margin)
total-size (+ (* column-count (count day-row))
(* (dec column-count) margin))]
(println (center-string "[Snoopy Picture]" total-size))
(println (center-string (str year) total-size))
(println)
(print-months (year-vector date) column-count margin)))) | 1,081Calendar
| 6clojure
| 8di05 |
class Example
def initialize
@private_data =
end
private
def hidden_method
end
end
example = Example.new
p example.private_methods(false)
p example.send(:hidden_method)
p example.instance_variables
p example.instance_variable_get:@private_data
p example.instance_variable_set:@private_data, 42
p example.instance_variable_get:@private_data | 1,076Break OO privacy
| 14ruby
| 392z7 |
class Example(private var name: String) {
override def toString = s"Hello, I am $name"
}
object BreakPrivacy extends App {
val field = classOf[Example].getDeclaredField("name")
field.setAccessible(true)
val foo = new Example("Erik")
println(field.get(foo))
field.set(foo, "Edith")
println(foo)
} | 1,076Break OO privacy
| 16scala
| 9v4m5 |
public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static void main(String[] args) {
long fact = 1;
double e = 2.0;
int n = 2;
double e0;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.abs(e - e0) >= EPSILON);
System.out.printf("e =%.15f\n", e);
}
} | 1,072Calculating the value of e
| 9java
| si6q0 |
<?PHP
ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
JANUARY FEBRUARY MARCH APRIL MAY JUNE
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
31 30
JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
; | 1,074Calendar - for "REAL" programmers
| 12php
| jpx7z |
p (1..10).inject(:+)
p (1..20).inject(:lcm) | 1,061Catamorphism
| 14ruby
| 7b3ri |
public class BraceExpansion {
public static void main(String[] args) {
for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
System.out.println();
expand(s);
}
}
public static void expand(String s) {
expandR("", s, "");
}
private static void expandR(String pre, String s, String suf) {
int i1 = -1, i2 = 0;
String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " ");
StringBuilder sb = null;
outer:
while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
i2 = i1 + 1;
sb = new StringBuilder(s);
for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
char c = noEscape.charAt(i2);
depth = (c == '{') ? ++depth : depth;
depth = (c == '}') ? --depth : depth;
if (c == ',' && depth == 1) {
sb.setCharAt(i2, '\u0000');
} else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
break outer;
}
}
if (i1 == -1) {
if (suf.length() > 0)
expandR(pre + s, suf, "");
else
System.out.printf("%s%s%s%n", pre, s, suf);
} else {
for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
}
}
} | 1,078Brace expansion
| 9java
| x8owy |
struct Example {
var notSoSecret = "Hello!"
private var secret = 42
}
let e = Example()
let mirror = Mirror(reflecting: e)
if let secret = mirror.children.filter({ $0.label == "secret" }).first?.value {
print("Value of the secret is \(secret)")
} | 1,076Break OO privacy
| 17swift
| zmltu |
import Foundation
private let stx = "\u{2}"
private let etx = "\u{3}"
func bwt(_ str: String) -> String? {
guard!str.contains(stx),!str.contains(etx) else {
return nil
}
let ss = stx + str + etx
let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()
return String(table.map({str in str.last!}))
}
func ibwt(_ str: String) -> String? {
let len = str.count
var table = Array(repeating: "", count: len)
for _ in 0..<len {
for i in 0..<len {
table[i] = String(str[str.index(str.startIndex, offsetBy: i)]) + table[i]
}
table.sort()
}
for row in table where row.hasSuffix(etx) {
return String(row.dropFirst().dropLast())
}
return nil
}
func readableBwt(_ str: String) -> String {
return str.replacingOccurrences(of: "\u{2}", with: "^").replacingOccurrences(of: "\u{3}", with: "|")
}
let testCases = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u{2}ABC\u{3}"
]
for test in testCases {
let b = bwt(test)?? "error"
let c = ibwt(b)?? "error"
print("\(readableBwt(test)) -> \(readableBwt(b)) -> \(readableBwt(c))")
} | 1,071Burrows–Wheeler transform
| 17swift
| nz2il |
(() => {
"use strict"; | 1,072Calculating the value of e
| 10javascript
| nzliy |
use warnings;
use strict;
use v5.10;
my @candidates = grep {not /0 | (\d) .* \1 /x} 1234 .. 9876;
sub read_score($) {
(my $guess) = @_;
for (;;) {
say "My guess: $guess (from ", 0+@candidates, " possibilities)";
if (<> =~ / ^ \h* (?<BULLS> \d) \h* (?<COWS> \d) \h* $ /x and
$+{BULLS} + $+{COWS} <= 4) {
return ($+{BULLS}, $+{COWS});
}
say "Please specify the number of bulls and the number of cows";
}
}
sub score_correct($$$$) {
my ($a, $b, $bulls, $cows) = @_;
my $exact = () = grep {substr($a, $_, 1) eq substr($b, $_, 1)} 0 .. 3;
my $loose = () = $a =~ /[$b]/g;
return $bulls == $exact && $cows == $loose - $exact;
}
do {
my $guess = @candidates[rand @candidates];
my ($bulls, $cows) = read_score $guess;
@candidates = grep {score_correct $_, $guess, $bulls, $cows} @candidates;
} while (@candidates > 1);
say(@candidates?
"Your secret number is @candidates":
"I think you made a mistake with your scoring"); | 1,073Bulls and cows/Player
| 2perl
| ka0hc |
fn main() {
println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n));
println!("Product: {}", (1..10).fold(1, |acc, n| acc * n));
let chars = ['a', 'b', 'c', 'd', 'e'];
println!("Concatenation: {}",
chars.iter().map(|&c| (c as u8 + 1) as char).collect::<String>());
} | 1,061Catamorphism
| 15rust
| jp672 |
(function () {
'use strict' | 1,078Brace expansion
| 10javascript
| oft86 |
(ns bulls-and-cows)
(defn bulls [guess solution]
(count (filter true? (map = guess solution))))
(defn cows [guess solution]
(-
(count (filter (set solution) guess))
(bulls guess solution)))
(defn valid-input?
"checks whether the string is a 4 digit number with unique digits"
[user-input]
(if (re-seq #"^(?!.*(\d).*\1)\d{4}$" user-input)
true
false))
(defn enter-guess []
"Let the user enter a guess. Verify the input. Repeat until valid.
returns a list of digits enters by the user (# # # #)"
(println "Enter your guess: ")
(let [guess (read-line)]
(if (valid-input? guess)
(map #(Character/digit % 10) guess)
(recur))))
(defn bulls-and-cows []
"generate a random 4 digit number from the list of (1 ... 9): no repeating digits
player tries to guess the number with bull and cows rules gameplay"
(let [solution ( take 4 (shuffle (range 1 10)))]
(println "lets play some bulls and cows!")
(loop [guess (enter-guess)]
(println (bulls guess solution) " bulls and " (cows guess solution) " cows.")
(if (not= guess solution)
(recur (enter-guess))
(println "You have won!")))))
(bulls-and-cows) | 1,082Bulls and cows
| 6clojure
| 574uz |
import ctypes
libc = ctypes.CDLL()
libc.strcmp(, )
libc.strcmp(, ) | 1,070Call a foreign-language function
| 3python
| jp87p |
object Main extends App {
val a = Seq(1, 2, 3, 4, 5)
println(s"Array : ${a.mkString(", ")}")
println(s"Sum : ${a.sum}")
println(s"Difference : ${a.reduce { (x, y) => x - y }}")
println(s"Product : ${a.product}")
println(s"Minimum : ${a.min}")
println(s"Maximum : ${a.max}")
} | 1,061Catamorphism
| 16scala
| be9k6 |
func + <T>(el: T, arr: [T]) -> [T] {
var ret = arr
ret.insert(el, at: 0)
return ret
}
func cartesianProduct<T>(_ arrays: [T]...) -> [[T]] {
guard let head = arrays.first else {
return []
}
let first = Array(head)
func pel(
_ el: T,
_ ll: [[T]],
_ a: [[T]] = []
) -> [[T]] {
switch ll.count {
case 0:
return a.reversed()
case _:
let tail = Array(ll.dropFirst())
let head = ll.first!
return pel(el, tail, el + head + a)
}
}
return arrays.reversed()
.reduce([first], {res, el in el.flatMap({ pel($0, res) }) })
.map({ $0.dropLast(first.count) })
}
print(cartesianProduct([1, 2], [3, 4]))
print(cartesianProduct([3, 4], [1, 2]))
print(cartesianProduct([1, 2], []))
print(cartesianProduct([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))
print(cartesianProduct([1, 2, 3], [30], [500, 100]))
print(cartesianProduct([1, 2, 3], [], [500, 100]) | 1,058Cartesian product of two or more lists
| 17swift
| 7bmrq |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CatlanNumbers {
public static void main(String[] args) {
Catlan f1 = new Catlan1();
Catlan f2 = new Catlan2();
Catlan f3 = new Catlan3();
System.out.printf(" Formula 1 Formula 2 Formula 3%n");
for ( int n = 0 ; n <= 15 ; n++ ) {
System.out.printf("C(%2d) =%,12d %,12d %,12d%n", n, f1.catlin(n), f2.catlin(n), f3.catlin(n));
}
}
private static interface Catlan {
public BigInteger catlin(long n);
}
private static class Catlan1 implements Catlan { | 1,068Catalan numbers
| 9java
| ofv8d |
null | 1,078Brace expansion
| 11kotlin
| pwxb6 |
<html><head><title>Catalan</title></head>
<body><pre id='x'></pre><script type="application/javascript">
function disp(x) {
var e = document.createTextNode(x + '\n');
document.getElementById('x').appendChild(e);
}
var fc = [], c2 = [], c3 = [];
function fact(n) { return fc[n] ? fc[n] : fc[n] = (n ? n * fact(n - 1) : 1); }
function cata1(n) { return Math.floor(fact(2 * n) / fact(n + 1) / fact(n) + .5); }
function cata2(n) {
if (n == 0) return 1;
if (!c2[n]) {
var s = 0;
for (var i = 0; i < n; i++) s += cata2(i) * cata2(n - i - 1);
c2[n] = s;
}
return c2[n];
}
function cata3(n) {
if (n == 0) return 1;
return c3[n] ? c3[n] : c3[n] = (4 * n - 2) * cata3(n - 1) / (n + 1);
}
disp(" meth1 meth2 meth3");
for (var i = 0; i <= 15; i++)
disp(i + '\t' + cata1(i) + '\t' + cata2(i) + '\t' + cata3(i));
</script></body></html> | 1,068Catalan numbers
| 10javascript
| tyrfm |
local function wrapEachItem(items, prefix, suffix)
local itemsWrapped = {}
for i, item in ipairs(items) do
itemsWrapped[i] = prefix .. item .. suffix
end
return itemsWrapped
end
local function getAllItemCombinationsConcatenated(aItems, bItems)
local combinations = {}
for _, a in ipairs(aItems) do
for _, b in ipairs(bItems) do
table.insert(combinations, a..b)
end
end
return combinations
end
local getItems | 1,078Brace expansion
| 1lua
| 1xqpo |
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math/rand"
"os"
)
const w = 400 | 1,079Brownian tree
| 0go
| qooxz |
null | 1,072Calculating the value of e
| 11kotlin
| aqd13 |
static VALUE
rc_strdup(VALUE obj, VALUE str_in)
{
VALUE str_out;
char *c, *d;
c = StringValueCStr(str_in);
d = strdup(c);
if (d == NULL)
rb_sys_fail(NULL);
str_out = rb_str_new_cstr(d);
free(d);
return str_out;
}
void
Init_rc_strdup(void)
{
VALUE mRosettaCode = rb_define_module();
rb_define_module_function(mRosettaCode, , rc_strdup, 1);
} | 1,070Call a foreign-language function
| 14ruby
| kaihg |
import Control.Monad
import Control.Monad.ST
import Data.STRef
import Data.Array.ST
import System.Random
import Bitmap
import Bitmap.BW
import Bitmap.Netpbm
main = do
g <- getStdGen
(t, _) <- stToIO $ drawTree (50, 50) (25, 25) 300 g
writeNetpbm "/tmp/tree.pbm" t
drawTree :: (Int, Int) -> (Int, Int) -> Int -> StdGen -> ST s (Image s BW, StdGen)
drawTree (width, height) start steps stdgen = do
img <- image width height off
setPix img (Pixel start) on
gen <- newSTRef stdgen
let
randomElem l = do
stdgen <- readSTRef gen
let (i, stdgen') = randomR (0, length l - 1) stdgen
writeSTRef gen stdgen'
return $ l !! i
newPoint = do
p <- randomElem border
c <- getPix img $ Pixel p
if c == off then return p else newPoint
wander p = do
next <- randomElem $ filter (inRange pointRange) $ adjacent p
c <- getPix img $ Pixel next
if c == on then setPix img (Pixel p) on else wander next
replicateM_ steps $ newPoint >>= wander
stdgen <- readSTRef gen
return (img, stdgen)
where pointRange = ((0, 0), (width - 1, height - 1))
adjacent (x, y) = [(x - 1, y - 1), (x, y - 1), (x + 1, y - 1),
(x - 1, y), (x + 1, y),
(x - 1, y + 1), (x, y + 1), (x + 1, y + 1)]
border = liftM2 (,) [0, width - 1] [0 .. height - 1] ++
liftM2 (,) [1 .. width - 2] [0, height - 1]
off = black
on = white | 1,079Brownian tree
| 8haskell
| m22yf |
void rot(int c, char *str)
{
int l = strlen(str);
const char* alpha_low = ;
const char* alpha_high = ;
char subst;
int idx;
int i;
for (i = 0; i < l; i++)
{
if( 0 == isalpha(str[i]) ) continue;
idx = (int) (tolower(str[i]) - 'a') + c) % 26;
if( isupper(str[i]) )
subst = alpha_high[idx];
else
subst = alpha_low[idx];
str[i] = subst;
}
}
int main(int argc, char** argv)
{
char str[] = ;
printf(, str);
caesar(str);
printf(, str);
decaesar(str);
printf(, str);
return 0;
} | 1,083Caesar cipher
| 5c
| l5lcy |
EPSILON = 1.0e-15;
fact = 1
e = 2.0
e0 = 0.0
n = 2
repeat
e0 = e
fact = fact * n
n = n + 1
e = e + 1.0 / fact
until (math.abs(e - e0) < EPSILON)
io.write(string.format("e =%.15f\n", e)) | 1,072Calculating the value of e
| 1lua
| esfac |
extern crate libc; | 1,070Call a foreign-language function
| 15rust
| benkx |
object JNIDemo {
try System.loadLibrary("JNIDemo")
private def callStrdup(s: String)
println(callStrdup("Hello World!"))
} | 1,070Call a foreign-language function
| 16scala
| aqt1n |
from itertools import permutations
from random import shuffle
try:
raw_input
except:
raw_input = input
try:
from itertools import izip
except:
izip = zip
digits = '123456789'
size = 4
def parse_score(score):
score = score.strip().split(',')
return tuple(int(s.strip()) for s in score)
def scorecalc(guess, chosen):
bulls = cows = 0
for g,c in izip(guess, chosen):
if g == c:
bulls += 1
elif g in chosen:
cows += 1
return bulls, cows
choices = list(permutations(digits, size))
shuffle(choices)
answers = []
scores = []
print (% size)
while True:
ans = choices[0]
answers.append(ans)
score = raw_input(
% (len(answers), size, ''.join(ans)))
score = parse_score(score)
scores.append(score)
found = score == (size, 0)
if found:
print ()
break
choices = [c for c in choices if scorecalc(c, ans) == score]
if not choices:
print ()
print (' ' +
'\n '.join(% (''.join(an),sc)
for an,sc in izip(answers, scores)))
break | 1,073Bulls and cows/Player
| 3python
| be8kr |
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums.reduce(0, +))
print(nums.reduce(1, *))
print(nums.reduce("", { $0 + String($1) })) | 1,061Catamorphism
| 17swift
| rkzgg |
sub brace_expand {
my $input = shift;
my @stack = ([my $current = ['']]);
while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) {
if ($1 eq '{') {
push @stack, [$current = ['']];
}
elsif ($1 eq ',' && @stack > 1) {
push @{$stack[-1]}, ($current = ['']);
}
elsif ($1 eq '}' && @stack > 1) {
my $group = pop @stack;
$current = $stack[-1][-1];
@{$group->[0]} = map { "{$_}" } @{$group->[0]} if @$group == 1;
@$current = map {
my $c = $_;
map { map { $c . $_ } @$_ } @$group;
} @$current;
}
else { $_ .= $1 for @$current; }
}
while (@stack > 1) {
my $right = pop @{$stack[-1]};
my $sep;
if (@{$stack[-1]}) { $sep = ',' }
else { $sep = '{'; pop @stack }
$current = $stack[-1][-1];
@$current = map {
my $c = $_;
map { $c . $sep . $_ } @$right;
} @$current;
}
return @$current;
} | 1,078Brace expansion
| 2perl
| yl26u |
package main
import "fmt"
func sameDigits(n, b int) bool {
f := n % b
n /= b
for n > 0 {
if n%b != f {
return false
}
n /= b
}
return true
}
func isBrazilian(n int) bool {
if n < 7 {
return false
}
if n%2 == 0 && n >= 8 {
return true
}
for b := 2; b < n-1; b++ {
if sameDigits(n, b) {
return true
}
}
return false
}
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
kinds := []string{" ", " odd ", " prime "}
for _, kind := range kinds {
fmt.Printf("First 20%sBrazilian numbers:\n", kind)
c := 0
n := 7
for {
if isBrazilian(n) {
fmt.Printf("%d ", n)
c++
if c == 20 {
fmt.Println("\n")
break
}
}
switch kind {
case " ":
n++
case " odd ":
n += 2
case " prime ":
for {
n += 2
if isPrime(n) {
break
}
}
}
}
}
n := 7
for c := 0; c < 100000; n++ {
if isBrazilian(n) {
c++
}
}
fmt.Println("The 100,000th Brazilian number:", n-1)
} | 1,080Brazilian numbers
| 0go
| 6c93p |
bullsAndCowsPlayer <- function()
{
guesses <- 1234:9876
guessDigits <- t(sapply(strsplit(as.character(guesses), ""), as.integer))
validGuesses <- guessDigits[apply(guessDigits, 1, function(x) length(unique(x)) == 4 && all(x != 0)), ]
repeat
{
remainingCasesCount <- nrow(validGuesses)
cat("Possibilities remaining:", remainingCasesCount)
guess <- validGuesses[sample(remainingCasesCount, 1), ]
guessAsOneNumber <- as.integer(paste(guess, collapse = ""))
bulls <- as.integer(readline(paste0("My guess is ", guessAsOneNumber, ". Bull score? [0-4] ")))
if(bulls == 4) return(paste0("Your number is ", guessAsOneNumber, ". I win!"))
cows <- as.integer(readline("Cow score? [0-4] "))
pseudoBulls <- function(x) sum(x == guess)
isGuessValid <- function(x) pseudoBulls(x) == bulls && sum(x %in% guess) - pseudoBulls(x) == cows && pseudoBulls(x) != 4
validGuesses <- validGuesses[apply(validGuesses, 1, isGuessValid), , drop = FALSE]
if(nrow(validGuesses) == 0) return("Error: Scoring problem?")
}
}
bullsAndCowsPlayer() | 1,073Bulls and cows/Player
| 13r
| 7bxry |
class Object
alias lowercase_method_missing method_missing
def method_missing(sym, *args, &block)
str = sym.to_s
if str == (down = str.downcase)
lowercase_method_missing sym, *args, &block
else
send down, *args, &block
end
end
def RESCUE(_BEGIN, _CLASS, _RESCUE)
begin _BEGIN.CALL
rescue _CLASS
_RESCUE.CALL; end
end
end
_PROGRAM = ARGV.SHIFT
_PROGRAM || ABORT()
LOAD($0 = _PROGRAM) | 1,074Calendar - for "REAL" programmers
| 14ruby
| zmvtw |
import Foundation
let hello = "Hello, World!"
let fromC = strdup(hello)
let backToSwiftString = String.fromCString(fromC) | 1,070Call a foreign-language function
| 17swift
| h1oj0 |
abstract class Catalan {
abstract operator fun invoke(n: Int) : Double
protected val m = mutableMapOf(0 to 1.0)
}
object CatalanI : Catalan() {
override fun invoke(n: Int): Double {
if (n !in m)
m[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
return m[n]!!
}
private fun fact(n: Int): Double {
if (n in facts)
return facts[n]!!
val f = n * fact(n -1)
facts[n] = f
return f
}
private val facts = mutableMapOf(0 to 1.0, 1 to 1.0, 2 to 2.0)
}
object CatalanR1 : Catalan() {
override fun invoke(n: Int): Double {
if (n in m)
return m[n]!!
var sum = 0.0
for (i in 0..n - 1)
sum += invoke(i) * invoke(n - 1 - i)
sum = Math.round(sum).toDouble()
m[n] = sum
return sum
}
}
object CatalanR2 : Catalan() {
override fun invoke(n: Int): Double {
if (n !in m)
m[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * invoke(n - 1)).toDouble()
return m[n]!!
}
}
fun main(args: Array<String>) {
val c = arrayOf(CatalanI, CatalanR1, CatalanR2)
for(i in 0..15) {
c.forEach { print("%9d".format(it(i).toLong())) }
println()
}
} | 1,068Catalan numbers
| 11kotlin
| x8mws |
import org.codehaus.groovy.GroovyBugError
class Brazilian {
private static final List<Integer> primeList = new ArrayList<>(Arrays.asList(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
))
static boolean isPrime(int n) {
if (n < 2) {
return false
}
for (Integer prime: primeList) {
if (n == prime) {
return true
}
if (n % prime == 0) {
return false
}
if (prime * prime > n) {
return true
}
}
BigInteger bi = BigInteger.valueOf(n)
return bi.isProbablePrime(10)
}
private static boolean sameDigits(int n, int b) {
int f = n % b
n = n.intdiv(b)
while (n > 0) {
if (n % b != f) {
return false
}
n = n.intdiv(b)
}
return true
}
private static boolean isBrazilian(int n) {
if (n < 7) return false
if (n % 2 == 0) return true
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true
}
}
return false
}
static void main(String[] args) {
for (String kind: Arrays.asList("", "odd ", "prime ")) {
boolean quiet = false
int bigLim = 99_999
int limit = 20
System.out.printf("First%d%sBrazilian numbers:\n", limit, kind)
int c = 0
int n = 7
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) System.out.printf("%d ", n)
if (++c == limit) {
System.out.println("\n")
quiet = true
}
}
if (quiet && "" != kind) continue
switch (kind) {
case "":
n++
break
case "odd ":
n += 2
break
case "prime ":
while (true) {
n += 2
if (isPrime(n)) break
}
break
default:
throw new GroovyBugError("Oops")
}
}
if ("" == kind) {
System.out.printf("The%dth Brazilian number is:%d\n\n", bigLim + 1, n)
}
}
}
} | 1,080Brazilian numbers
| 7groovy
| d3zn3 |
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.JFrame;
public class BrownianTree extends JFrame implements Runnable {
BufferedImage I;
private List<Particle> particles;
static Random rand = new Random();
public BrownianTree() {
super("Brownian Tree");
setBounds(100, 100, 400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
I.setRGB(I.getWidth() / 2, I.getHeight() / 2, 0xff00);
particles = new LinkedList<Particle>();
}
@Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
public void run() {
for (int i = 0; i < 20000; i++) {
particles.add(new Particle());
}
while (!particles.isEmpty()) {
for (Iterator<Particle> it = particles.iterator(); it.hasNext();) {
if (it.next().move()) {
it.remove();
}
}
repaint();
}
}
public static void main(String[] args) {
BrownianTree b = new BrownianTree();
b.setVisible(true);
new Thread(b).start();
}
private class Particle {
private int x, y;
private Particle() {
x = rand.nextInt(I.getWidth());
y = rand.nextInt(I.getHeight());
}
private boolean move() {
int dx = rand.nextInt(3) - 1;
int dy = rand.nextInt(3) - 1;
if ((x + dx < 0) || (y + dy < 0)
|| (y + dy >= I.getHeight()) || (x + dx >= I.getWidth())) {
return true;
}
x += dx;
y += dy;
if ((I.getRGB(x, y) & 0xff00) == 0xff00) {
I.setRGB(x - dx, y - dy, 0xff00);
return true;
}
return false;
}
}
} | 1,079Brownian tree
| 9java
| f66dv |
(defn encrypt-character [offset c]
(if (Character/isLetter c)
(let [v (int c)
base (if (>= v (int \a))
(int \a)
(int \A))
offset (mod offset 26)]
(char (+ (mod (+ (- v base) offset) 26)
base)))
c))
(defn encrypt [offset text]
(apply str (map #(encrypt-character offset %) text)))
(defn decrypt [offset text]
(encrypt (- 26 offset) text))
(let [text "The Quick Brown Fox Jumps Over The Lazy Dog."
enc (encrypt -1 text)]
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n")) | 1,083Caesar cipher
| 6clojure
| 4j45o |
function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode(, $lines) as $line ) {
printf(, $line);
foreach( getitem($line)[0] as $expansion ) {
printf(, $expansion);
}
} | 1,078Brace expansion
| 12php
| aqs12 |
import Data.Numbers.Primes (primes)
isBrazil :: Int -> Bool
isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])
monoDigit :: Int -> Int -> Bool
monoDigit n b =
let (q, d) = quotRem n b
in d ==
snd
(until
(uncurry (flip ((||) . (d /=)) . (0 ==)))
((`quotRem` b) . fst)
(q, d))
main :: IO ()
main =
mapM_
(\(s, xs) ->
(putStrLn . concat)
[ "First 20 "
, s
, " Brazilians:\n"
, show . take 20 $ filter isBrazil xs
, "\n"
])
[([], [1 ..]), ("odd", [1,3 ..]), ("prime", primes)] | 1,080Brazilian numbers
| 8haskell
| jpb7g |
function brownian(canvasId, messageId) {
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d"); | 1,079Brownian tree
| 10javascript
| yll6r |
package main
import (
"fmt"
"time"
)
const pageWidth = 80
func main() {
printCal(1969)
}
func printCal(year int) {
thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC)
var (
dayArr [12][7][6]int | 1,081Calendar
| 0go
| cu29g |
null | 1,079Brownian tree
| 11kotlin
| 8dd0q |
use bignum qw(e);
$e = 2;
$f = 1;
do {
$e0 = $e;
$n++;
$f *= 2*$n * (1 + 2*$n);
$e += (2*$n + 2) / $f;
} until ($e-$e0) < 1.0e-39;
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n"; | 1,072Calculating the value of e
| 2perl
| 9vjmn |
null | 1,068Catalan numbers
| 1lua
| qo9x0 |
import java.math.BigInteger;
import java.util.List;
public class Brazilian {
private static final List<Integer> primeList = List.of(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
);
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (Integer prime : primeList) {
if (n == prime) {
return true;
}
if (n % prime == 0) {
return false;
}
if (prime * prime > n) {
return true;
}
}
BigInteger bi = BigInteger.valueOf(n);
return bi.isProbablePrime(10);
}
private static boolean sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
private static boolean isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0) return true;
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
for (String kind : List.of("", "odd ", "prime ")) {
boolean quiet = false;
int bigLim = 99_999;
int limit = 20;
System.out.printf("First%d%sBrazilian numbers:\n", limit, kind);
int c = 0;
int n = 7;
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) System.out.printf("%d ", n);
if (++c == limit) {
System.out.println("\n");
quiet = true;
}
}
if (quiet && !"".equals(kind)) continue;
switch (kind) {
case "":
n++;
break;
case "odd ":
n += 2;
break;
case "prime ":
do {
n += 2;
} while (!isPrime(n));
break;
default:
throw new AssertionError("Oops");
}
}
if ("".equals(kind)) {
System.out.printf("The%dth Brazilian number is:%d\n\n", bigLim + 1, n);
}
}
}
} | 1,080Brazilian numbers
| 9java
| urgvv |
import qualified Data.Text as T
import Data.Time
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
import Data.List.Split (chunksOf)
import Data.List
data Day = Su | Mo | Tu | We | Th | Fr | Sa
deriving (Show, Eq, Ord, Enum)
data Month = January | February | March
| April | May | June
| July | August | September
| October | November | December
deriving (Show, Eq, Ord, Enum)
monthToInt :: Month -> Int
monthToInt = (+ 1) . fromEnum
dayFromDate :: Integer -> Month -> Int -> Int
dayFromDate year month day = day' `mod` 7
where (_, _, day') = toWeekDate $ fromGregorian year (monthToInt month) day
nSpaces :: Int -> T.Text
nSpaces n = T.replicate n (T.pack " ")
space :: T.Text
space = nSpaces 1
calMarginWidth = 3
calMargin :: T.Text
calMargin = nSpaces calMarginWidth
calWidth = 20
listMonth :: Integer -> Month -> [T.Text]
listMonth year month = [monthHeader, weekHeader] ++ weeks'
where
monthHeader = (T.center calWidth ' ') . T.pack $ show month
weekHeader = (T.intercalate space) $ map (T.pack . show) [(Su)..]
monthLength = toInteger $
gregorianMonthLength year $
monthToInt month
firstDay = dayFromDate year month 1
days = replicate firstDay (nSpaces 2) ++
map ((T.justifyRight 2 ' ') . T.pack . show) [1..monthLength]
weeks = map (T.justifyLeft calWidth ' ') $
map (T.intercalate space) $
chunksOf 7 days
weeks' = weeks ++ replicate (6 - length weeks) (nSpaces calWidth)
listCalendar :: Integer -> Int -> [[[T.Text]]]
listCalendar year calColumns = (chunksOf calColumns) . (map (listMonth year)) $
enumFrom January
calColFromCol :: Int -> Int
calColFromCol columns = c + if r >= calWidth then 1 else 0
where (c, r) = columns `divMod` (calWidth + calMarginWidth)
colFromCalCol :: Int -> Int
colFromCalCol calCol = calCol * calWidth + ((calCol - 1) * calMarginWidth)
center :: Int -> String -> String
center i a = T.unpack . (T.center i ' ') $ T.pack a
printCal :: [[[T.Text]]] -> IO ()
printCal = mapM_ f where
f c = mapM_ (putStrLn . T.unpack) rows
where rows = map (T.intercalate calMargin) $ transpose c
printCalendar :: Integer -> Int -> IO ()
printCalendar year columns =
if columns < 20
then putStrLn $ "Cannot print less than 20 columns"
else do
putStrLn $ center columns' "[Maybe Snoopy]"
putStrLn $ center columns' $ show year
putStrLn ""
printCal $ listCalendar year calcol'
where
calcol' = calColFromCol columns
columns' = colFromCalCol calcol' | 1,081Calendar
| 8haskell
| pwabt |
def getitem(s, depth=0):
out = []
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in '''~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}'''.split('\n'):
print .join([s] + getitem(s)[0]) + | 1,078Brace expansion
| 3python
| m2vyh |
size = 4
scores = []
guesses = []
puts
possible_guesses = [*'1'..'9'].permutation(size).to_a.shuffle
loop do
guesses << current_guess = possible_guesses.pop
print
scores << score = gets.split(',').map(&:to_i)
break (puts ) if score == [size,0]
possible_guesses.select! do |guess|
bulls = guess.zip(current_guess).count{|g,cg| g == cg}
cows = size - (guess - current_guess).size - bulls
[bulls, cows] == score
end
if possible_guesses.empty?
puts
guesses.zip(scores).each{|g, (b, c)| puts }
break
end
end | 1,073Bulls and cows/Player
| 14ruby
| 1xipw |
noArgs() | 1,077Call a function
| 0go
| ylv64 |
function SetSeed( f )
for i = 1, #f[1] do | 1,079Brownian tree
| 1lua
| off8h |
def allCombinations: Seq[List[Byte]] = {
(0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations)
}
def nextGuess(possible: Seq[List[Byte]]): List[Byte] = possible match {
case Nil => throw new IllegalStateException
case List(only) => only
case _ => possible(Random.nextInt(possible.size))
}
def doGuess(guess: List[Byte]): Pair[Int, Int] = {
println("My guess is " + guess);
val arr = readLine().split(' ').map(Integer.valueOf(_))
(arr(0), arr(1))
}
def testGuess(alt: List[Byte], guess: List[Byte]): Pair[Int, Int] = {
val bulls =alt.zip(guess).filter(p => p._1 == p._2).size
val cows = guess.filter(alt.contains(_)).size - bulls
(bulls, cows)
}
def play(possible: Seq[List[Byte]]): List[Byte] = {
val curGuess = nextGuess(possible)
val bc = doGuess(curGuess)
if (bc._1 == 4) { println("Ye-haw!"); curGuess }
else
play(possible.filter(p => testGuess(p, curGuess) == bc))
}
def main(args: Array[String]) {
play(allCombinations)
} | 1,073Bulls and cows/Player
| 16scala
| x8twg |
noArgs() | 1,077Call a function
| 7groovy
| f6mdn |
fun sameDigits(n: Int, b: Int): Boolean {
var n2 = n
val f = n % b
while (true) {
n2 /= b
if (n2 > 0) {
if (n2 % b != f) {
return false
}
} else {
break
}
}
return true
}
fun isBrazilian(n: Int): Boolean {
if (n < 7) return false
if (n % 2 == 0) return true
for (b in 2 until n - 1) {
if (sameDigits(n, b)) {
return true
}
}
return false
}
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun main() {
val bigLim = 99999
val limit = 20
for (kind in ",odd ,prime".split(',')) {
var quiet = false
println("First $limit ${kind}Brazilian numbers:")
var c = 0
var n = 7
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) print("%,d ".format(n))
if (++c == limit) {
print("\n\n")
quiet = true
}
}
if (quiet && kind != "") continue
when (kind) {
"" -> n++
"odd " -> n += 2
"prime" -> {
while (true) {
n += 2
if (isPrime(n)) break
}
}
}
}
if (kind == "") println("The%,dth Brazilian number is:%,d".format(bigLim + 1, n))
}
} | 1,080Brazilian numbers
| 11kotlin
| 9v2mh |
import math
e0 = 0
e = 2
n = 0
fact = 1
while(e-e0 > 1e-15):
e0 = e
n += 1
fact *= 2*n*(2*n+1)
e += (2.*n+2)/fact
print +str(e)
print +str(math.e)
print +str(math.e-e)
print +str(n) | 1,072Calculating the value of e
| 3python
| cuh9q |
multiply x y = x * y
multiply 10 20
twopi = 6.28
twopi () = 6.28
twopi :: Num a => () -> a
twopi ()
multiply_by_10 = (10 * )
map multiply_by_10 [1, 2, 3]
multiply_all_by_10 = map multiply_by_10
multiply_all_by_10 [1, 2, 3] | 1,077Call a function
| 8haskell
| h1eju |
def getitem(s, depth=0)
out = []
until s.empty?
c = s[0]
break if depth>0 and (c == ',' or c == '}')
if c == '{' and x = getgroup(s[1..-1], depth+1)
out = out.product(x[0]).map{|a,b| a+b}
s = x[1]
else
s, c = s[1..-1], c + s[1] if c == '\\' and s.size > 1
out, s = out.map{|a| a+c}, s[1..-1]
end
end
return out, s
end
def getgroup(s, depth)
out, comma = [], false
until s.empty?
g, s = getitem(s, depth)
break if s.empty?
out += g
case s[0]
when '}' then return (comma? out: out.map{|a| }), s[1..-1]
when ',' then comma, s = true, s[1..-1]
end
end
end
strs = <<'EOS'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
EOS
strs.each_line do |s|
puts s.chomp!
puts getitem(s)[0].map{|str| +str}
puts
end | 1,078Brace expansion
| 14ruby
| cu59k |
function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) then
return true
end
for b=2,n-2 do
if sameDigits(n,b) then
return true
end
end
return false
end
function isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
local d = 5
while d * d <= n do
if n % d == 0 then
return false
end
d = d + 2
if n % d == 0 then
return false
end
d = d + 4
end
return true
end
function main()
local kinds = {" ", " odd ", " prime "}
for i=1,3 do
print("First 20" .. kinds[i] .. "Brazillion numbers:")
local c = 0
local n = 7
while true do
if isBrazilian(n) then
io.write(n .. " ")
c = c + 1
if c == 20 then
print()
print()
break
end
end
if i == 1 then
n = n + 1
elseif i == 2 then
n = n + 2
elseif i == 3 then
repeat
n = n + 2
until isPrime(n)
end
end
end
end
main() | 1,080Brazilian numbers
| 1lua
| cuv92 |
import java.text.*;
import java.util.*;
public class CalendarTask {
public static void main(String[] args) {
printCalendar(1969, 3);
}
static void printCalendar(int year, int nCols) {
if (nCols < 1 || nCols > 12)
throw new IllegalArgumentException("Illegal column width.");
Calendar date = new GregorianCalendar(year, 0, 1);
int nRows = (int) Math.ceil(12.0 / nCols);
int offs = date.get(Calendar.DAY_OF_WEEK) - 1;
int w = nCols * 24;
String[] monthNames = new DateFormatSymbols(Locale.US).getMonths();
String[][] mons = new String[12][8];
for (int m = 0; m < 12; m++) {
String name = monthNames[m];
int len = 11 + name.length() / 2;
String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len);
mons[m][0] = String.format(format, name, "");
mons[m][1] = " Su Mo Tu We Th Fr Sa";
int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int d = 1; d < 43; d++) {
boolean isDay = d > offs && d <= offs + dim;
String entry = isDay ? String.format("%2s", d - offs) : " ";
if (d % 7 == 1)
mons[m][2 + (d - 1) / 7] = entry;
else
mons[m][2 + (d - 1) / 7] += entry;
}
offs = (offs + dim) % 7;
date.add(Calendar.MONTH, 1);
}
System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]");
System.out.printf("%" + (w / 2 + 4) + "s%n%n", year);
for (int r = 0; r < nRows; r++) {
for (int i = 0; i < 8; i++) {
for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++)
System.out.printf(" %s", mons[c][i]);
System.out.println();
}
System.out.println();
}
}
} | 1,081Calendar
| 9java
| rkjg0 |
class Caesar {
int _key;
Caesar(this._key);
int _toCharCode(String s) {
return s.charCodeAt(0);
}
String _fromCharCode(int ch) {
return new String.fromCharCodes([ch]);
}
String _process(String msg, int offset) {
StringBuffer sb=new StringBuffer();
for(int i=0;i<msg.length;i++) {
int ch=msg.charCodeAt(i);
if(ch>=_toCharCode('A')&&ch<=_toCharCode('Z')) {
sb.add(_fromCharCode(_toCharCode("A")+(ch-_toCharCode("A")+offset)%26));
}
else if(ch>=_toCharCode('a')&&ch<=_toCharCode('z')) {
sb.add(_fromCharCode(_toCharCode("a")+(ch-_toCharCode("a")+offset)%26));
} else {
sb.add(msg[i]);
}
}
return sb.toString();
}
String encrypt(String msg) {
return _process(msg, _key);
}
String decrypt(String msg) {
return _process(msg, 26-_key);
}
}
void trip(String msg) {
Caesar cipher=new Caesar(10);
String enc=cipher.encrypt(msg);
String dec=cipher.decrypt(enc);
print("\"$msg\" encrypts to:");
print("\"$enc\" decrypts to:");
print("\"$dec\"");
Expect.equals(msg,dec);
}
main() {
Caesar c2=new Caesar(2);
print(c2.encrypt("HI"));
Caesar c20=new Caesar(20);
print(c20.encrypt("HI")); | 1,083Caesar cipher
| 18dart
| 393zz |
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19))) | 1,072Calculating the value of e
| 13r
| 6cg3e |
const OPEN_CHAR: char = '{';
const CLOSE_CHAR: char = '}';
const SEPARATOR: char = ',';
const ESCAPE: char = '\\';
#[derive(Debug, PartialEq, Clone)]
enum Token {
Open,
Close,
Separator,
Payload(String),
Branches(Branches),
}
impl From<char> for Token {
fn from(ch: char) -> Token {
match ch {
OPEN_CHAR => Token::Open,
CLOSE_CHAR => Token::Close,
SEPARATOR => Token::Separator,
_ => panic!("Non tokenizable char!"),
}
}
}
#[derive(Debug, PartialEq, Clone)]
struct Branches {
tokens: Vec<Vec<Token>>,
}
impl Branches {
fn new() -> Branches {
Branches{
tokens: Vec::new(),
}
}
fn add_branch(&mut self, branch: Vec<Token>) {
self.tokens.push(branch);
}
fn from(tokens: &Vec<Token>) -> Branches {
let mut branches = Branches::new();
let mut tail = tokens.clone();
while let Some(pos) = tail.iter().position(|token| { *token == Token::Separator }) {
let mut rest = tail.split_off(pos);
branches.add_branch(tail);
rest.remove(0);
tail = rest;
}
branches.add_branch(tail);
branches
}
}
impl From<Branches> for Token {
fn from(branches: Branches) -> Token {
Token::Branches(branches)
}
}
impl From<Vec<Token>> for Branches {
fn from(tokens: Vec<Token>) -> Branches {
Branches::from(&tokens)
}
}
impl From<Token> for String {
fn from(token: Token) -> String {
match token {
Token::Branches(_) => panic!("Cannot convert to String!"),
Token::Payload(text) => text,
Token::Open => OPEN_CHAR.to_string(),
Token::Close => CLOSE_CHAR.to_string(),
Token::Separator => SEPARATOR.to_string(),
}
}
}
impl From<Branches> for Vec<String> {
fn from(branches: Branches) -> Vec<String> {
let Branches{ tokens: token_lines } = branches;
let mut vec: Vec<String> = Vec::new();
let braces = { if token_lines.len() == 1 { true } else { false } };
for tokens in token_lines {
let mut vec_string = output(tokens);
vec.append(&mut vec_string);
}
if braces {
vec.iter()
.map(|line| {
format!("{}{}{}", OPEN_CHAR, line, CLOSE_CHAR)
}).
collect::<Vec<String>>()
} else {
vec
}
}
}
impl From<Token> for Vec<String> {
fn from(token: Token) -> Vec<String> {
match token {
Token::Branches(branches) => {
branches.into()
},
_ => {
let frag: String = token.into();
vec![frag]
},
}
}
}
fn tokenize(string: &str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec::new();
let mut chars = string.chars();
let mut payload = String::new();
while let Some(ch) = chars.next() {
match ch {
OPEN_CHAR | SEPARATOR | CLOSE_CHAR => {
if payload.len() > 0 {
tokens.push(Token::Payload(payload));
}
payload = String::new();
if ch == CLOSE_CHAR {
let pos = tokens.iter().rposition(|token| *token == Token::Open);
if let Some(pos) = pos {
let branches: Branches = {
let mut to_branches = tokens.split_off(pos);
to_branches.remove(0);
to_branches
}.into();
tokens.push(branches.into());
} else {
tokens.push(ch.into());
}
} else {
tokens.push(ch.into());
}
},
ESCAPE => {
payload.push(ch);
if let Some(next_char) = chars.next() {
payload.push(next_char);
}
},
_ => payload.push(ch),
}
}
let payload = payload.trim_end();
if payload.len() > 0 {
tokens.push(Token::Payload(payload.into()));
}
tokens
}
fn output(tokens: Vec<Token>) -> Vec<String> {
let mut output: Vec<String> = vec![String::new()];
for token in tokens {
let mut aux: Vec<String> = Vec::new();
let strings: Vec<String> = token.into();
for root in &output {
for string in &strings {
aux.push({format!("{}{}", root, string)});
}
}
output = aux;
}
output
}
fn main() {
let mut input: String = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let tokens: Vec<Token> = tokenize(&input); | 1,078Brace expansion
| 15rust
| l54cc |
import collection.mutable.ListBuffer
case class State(isChild: Boolean, alts: ListBuffer[String], rem: List[Char])
def expand(s: String): Seq[String] = {
def parseGroup(s: State): State = s.rem match {
case Nil => s.copy(alts = ListBuffer("{" + s.alts.mkString(",")))
case ('{' | ',')::sp =>
val newS = State(true, ListBuffer(""), rem = sp)
val elem = parseElem(newS)
elem.rem match {
case Nil => elem.copy(alts = elem.alts.map(a => "{" + s.alts.map(_ + ",").mkString("") + a))
case elemrem => parseGroup(s.copy(alts = (s.alts ++= elem.alts), rem = elem.rem))
}
case '}'::sp =>
if (s.alts.isEmpty) s.copy(alts = ListBuffer("{}"), rem = sp)
else if(s.alts.length == 1) s.copy(alts = ListBuffer("{"+s.alts.head + "}"), rem = sp)
else s.copy(rem = sp)
case _ => throw new Exception("parseGroup should be called only with delimitors")
}
def parseElem(s: State): State = s.rem match {
case Nil => s
case '{'::sp =>
val ys = parseGroup(State(true, ListBuffer(), s.rem))
val newAlts = for { x <- s.alts; y <- ys.alts} yield x + y
parseElem(s.copy(alts = newAlts, rem = ys.rem))
case (',' | '}')::_ if s.isChild => s
case '\\'::c::sp => parseElem(s.copy(alts = s.alts.map(_ + '\\' + c), rem = sp))
case c::sp => parseElem(s.copy(alts = s.alts.map(_ + c), rem = sp))
}
parseElem(State(false, ListBuffer(""), s.toList)).alts
} | 1,078Brace expansion
| 16scala
| ur7v8 |
const printCenter = width =>
s => s.padStart(width / 2 + s.length / 2, ' ').padEnd(width);
const localeName = (locale, options) => {
const formatter = new Intl.DateTimeFormat(locale, options);
return date => formatter.format(date);
};
const addDay = (date, inc = 1) => {
const res = new Date(date.valueOf());
res.setDate(date.getDate() + inc);
return res;
}
const makeWeek = date => {
const month = date.getMonth();
let [wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
const line = Array(7).fill(' ').map((e, i) => {
if (i === wdi && m === month) {
const result = (md + '').padStart(2, ' ');
date = addDay(date);
[wdi, md, m] = [date.getUTCDay(), date.getDate(), date.getMonth()];
return result;
} else {
return e;
}
}).join(' ');
return [month !== m, date, line];
}
const cal = (year, locale = 'en-US', cols = 3, coll_space = 5) => {
const MONTH_LINES = 9; | 1,081Calendar
| 10javascript
| be1ki |
import java.io.PrintStream
import java.text.DateFormatSymbols
import java.text.MessageFormat
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Locale
internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) {
if (nCols < 1 || nCols > 12)
throw IllegalArgumentException("Illegal column width.")
val w = nCols * 24
val nRows = Math.ceil(12.0 / nCols).toInt()
val date = GregorianCalendar(year, 0, 1)
var offs = date.get(Calendar.DAY_OF_WEEK) - 1
val days = DateFormatSymbols(locale).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ")
val mons = Array(12) { Array(8) { "" } }
DateFormatSymbols(locale).months.slice(0..11).forEachIndexed { m, name ->
val len = 11 + name.length / 2
val format = MessageFormat.format("%{0}s%{1}s", len, 21 - len)
mons[m][0] = String.format(format, name, "")
mons[m][1] = days
val dim = date.getActualMaximum(Calendar.DAY_OF_MONTH)
for (d in 1..42) {
val isDay = d > offs && d <= offs + dim
val entry = if (isDay) String.format("%2s", d - offs) else " "
if (d % 7 == 1)
mons[m][2 + (d - 1) / 7] = entry
else
mons[m][2 + (d - 1) / 7] += entry
}
offs = (offs + dim) % 7
date.add(Calendar.MONTH, 1)
}
printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]")
printf("%" + (w / 2 + 4) + "s%n%n", year)
for (r in 0 until nRows) {
for (i in 0..7) {
var c = r * nCols
while (c < (r + 1) * nCols && c < 12) {
printf(" %s", mons[c][i])
c++
}
println()
}
println()
}
}
fun main(args: Array<String>) {
System.out.printCalendar(1969, 3, Locale.US)
} | 1,081Calendar
| 11kotlin
| vg521 |
fact = 1
e = 2
e0 = 0
n = 2
until (e - e0).abs < Float::EPSILON do
e0 = e
fact *= n
n += 1
e += 1.0 / fact
end
puts e | 1,072Calculating the value of e
| 14ruby
| 24blw |
myMethod() | 1,077Call a function
| 9java
| 57huf |
use strict;
use warnings;
use ntheory qw<is_prime>;
use constant Inf => 1e10;
sub is_Brazilian {
my($n) = @_;
return 1 if $n > 6 && 0 == $n%2;
LOOP: for (my $base = 2; $base < $n - 1; ++$base) {
my $digit;
my $nn = $n;
while (1) {
my $x = $nn % $base;
$digit //= $x;
next LOOP if $digit != $x;
$nn = int $nn / $base;
if ($nn < $base) {
return 1 if $digit == $nn;
next LOOP;
}
}
}
}
my $upto = 20;
print "First $upto Brazilian numbers:\n";
my $n = 0;
print do { $n < $upto ? (is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;
print "\n\nFirst $upto odd Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!($_%2) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;
print "\n\nFirst $upto prime Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!is_prime($_) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf; | 1,080Brazilian numbers
| 2perl
| w0se6 |
sub PI() { atan2(1,1) * 4 }
sub STEP() { .5 }
sub STOP_RADIUS() { 100 }
sub ATTRACT() { .2 }
my @particles = map([ map([], 0 .. 2 * STOP_RADIUS) ], 0 .. 2 * STOP_RADIUS);
push @{ $particles[STOP_RADIUS][STOP_RADIUS] }, [0, 0];
my $r_start = 3;
my $max_dist = 0;
sub dist2 {
my ($dx, $dy) = ($_[0][0] - $_[1][0], $_[0][1] - $_[1][1]);
$dx * $dx + $dy * $dy
}
sub move {
my $p = shift;
$p->[0] += 2 * $r_start while $p->[0] < -$r_start;
$p->[0] -= 2 * $r_start while $p->[0] > $r_start;
$p->[1] += 2 * $r_start while $p->[1] < -$r_start;
$p->[1] -= 2 * $r_start while $p->[1] > $r_start;
my ($ix, $iy) = (int($p->[0]), int($p->[1]));
my $dist = 2 * $r_start * $r_start;
my $nearest;
for ($ix - 1 .. $ix + 1) {
my $idx = STOP_RADIUS + $_;
next if $idx > 2 * STOP_RADIUS || $idx < 0;
my $xs = $particles[ $idx ];
for ($iy - 1 .. $iy + 1) {
my $idx = STOP_RADIUS + $_;
next if $idx > 2 * STOP_RADIUS || $idx < 0;
for (@{ $xs->[ $idx ] }) {
my $d = dist2($p, $_);
next if $d > 2;
next if $d > $dist;
$dist = $d;
$nearest = $_;
}
}
}
if ($nearest) {
my $displace = [ $p->[0] - $nearest->[0],
$p->[1] - $nearest->[1] ];
my $angle = atan2($displace->[1], $displace->[0]);
$p->[0] = $nearest->[0] + cos($angle);
$p->[1] = $nearest->[1] + sin($angle);
push @{$particles[$ix + STOP_RADIUS][$iy + STOP_RADIUS]}, [ @$p ];
$dist = sqrt dist2($p);
if ($dist + 10 > $r_start && $r_start < STOP_RADIUS + 10) {
$r_start = $dist + 10
}
if (int($dist + 1) > $max_dist) {
$max_dist = int($dist + 1);
return 3 if $max_dist >= STOP_RADIUS;
}
return 2;
}
my $angle = rand(2 * PI);
$p->[0] += STEP * cos($angle);
$p->[1] += STEP * sin($angle);
my $nudge;
if (sqrt(dist2($p, [0, 0])) > STOP_RADIUS + 1) {
$nudge = 1;
} else {
$nudge = STEP * ATTRACT;
}
if ($nudge) {
$angle = atan2($p->[1], $p->[0]);
$p->[0] -= $nudge * cos($angle);
$p->[1] -= $nudge * sin($angle);
}
return 1;
}
my $count;
PARTICLE: while (1) {
my $a = rand(2 * PI);
my $p = [ $r_start * cos($a), $r_start * sin($a) ];
while (my $m = move($p)) {
if ($m == 1) { next }
elsif ($m == 2) { $count++; last; }
elsif ($m == 3) { last PARTICLE }
else { last }
}
print STDERR "$count $max_dist/@{[int($r_start)]}/@{[STOP_RADIUS]}\r" unless $count% 7;
}
sub write_eps {
my $size = 128;
my $p = $size / (STOP_RADIUS * 1.05);
my $b = STOP_RADIUS * $p;
if ($p < 1) {
$size = STOP_RADIUS * 1.05;
$b = STOP_RADIUS;
$p = 1;
}
my $hp = $p / 2;
open OUT, ">", "test.eps";
print OUT <<"HEAD";
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 @{[$size*2, $size*2]}
$size $size translate
/l{ rlineto }def
/c{ $hp 0 360 arc fill }def
-$size -$size moveto
$size 2 mul 0 l
0 $size 2 mul l
-$size 2 mul 0 l
closepath
0 setgray fill
0 setlinewidth .1 setgray 0 0 $b 0 360 arc stroke
.8 setgray /TimesRoman findfont 16 scalefont setfont
-$size 10 add $size -16 add moveto
(Step = @{[STEP]} Attract = @{[ATTRACT]}) show
0 1 0 setrgbcolor newpath
HEAD
for (@particles) {
for (@$_) {
printf OUT "%.3g%.3g c ", map { $_ * $p } @$_ for @$_;
}
}
print OUT "\n%%EOF";
close OUT;
}
write_eps; | 1,079Brownian tree
| 2perl
| 4jj5d |
const EPSILON: f64 = 1e-15;
fn main() {
let mut fact: u64 = 1;
let mut e: f64 = 2.0;
let mut n: u64 = 2;
loop {
let e0 = e;
fact *= n;
n += 1;
e += 1.0 / fact as f64;
if (e - e0).abs() < EPSILON {
break;
}
}
println!("e = {:.15}", e);
} | 1,072Calculating the value of e
| 15rust
| vgp2t |
import scala.annotation.tailrec
object CalculateE extends App {
private val = 1.0e-15
@tailrec
def iter(fact: Long, : Double, n: Int, e0: Double): Double = {
val newFact = fact * n
val newE = + 1.0 / newFact
if (math.abs(newE - ) < )
else iter(newFact, newE, n + 1, )
}
println(f" = ${iter(1L, 2.0, 2, 0)}%.15f")
} | 1,072Calculating the value of e
| 16scala
| 4je50 |
var foo = function() { return arguments.length };
foo() | 1,077Call a function
| 10javascript
| jpa7n |
'''Brazilian numbers'''
from itertools import count, islice
def isBrazil(n):
'''True if n is a Brazilian number,
in the sense of OEIS:A125134.
'''
return 7 <= n and (
0 == n% 2 or any(
map(monoDigit(n), range(2, n - 1))
)
)
def monoDigit(n):
'''True if all the digits of n,
in the given base, are the same.
'''
def go(base):
def g(b, n):
(q, d) = divmod(n, b)
def p(qr):
return d != qr[1] or 0 == qr[0]
def f(qr):
return divmod(qr[0], b)
return d == until(p)(f)(
(q, d)
)[1]
return g(base, n)
return go
def main():
'''First 20 members each of:
OEIS:A125134
OEIS:A257521
OEIS:A085104
'''
for kxs in ([
(' ', count(1)),
(' odd ', count(1, 2)),
(' prime ', primes())
]):
print(
'First 20' + kxs[0] + 'Brazilians:\n' +
showList(take(20)(filter(isBrazil, kxs[1]))) + '\n'
)
def primes():
''' Non finite sequence of prime numbers.
'''
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(str(x) for x in xs) + ']'
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main() | 1,080Brazilian numbers
| 3python
| x80wr |
function print_cal(year)
local months={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
"JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}
local daysTitle="MO TU WE TH FR SA SU"
local daysPerMonth={31,28,31,30,31,30,31,31,30,31,30,31}
local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
if year%4==0 and year%100~=0 or year%400==0 then
daysPerMonth[2]=29
end
local sep=5
local monthwidth=daysTitle:len()
local calwidth=3*monthwidth+2*sep
function center(str, width)
local fill1=math.floor((width-str:len())/2)
local fill2=width-str:len()-fill1
return string.rep(" ",fill1)..str..string.rep(" ",fill2)
end
function makeMonth(name, skip,days)
local cal={
center(name,monthwidth),
daysTitle
}
local curday=1-skip
while #cal<9 do
line={}
for i=1,7 do
if curday<1 or curday>days then
line[i]=" "
else
line[i]=string.format("%2d",curday)
end
curday=curday+1
end
cal[#cal+1]=table.concat(line," ")
end
return cal
end
local calendar={}
for i,month in ipairs(months) do
local dpm=daysPerMonth[i]
calendar[i]=makeMonth(month, startday, dpm)
startday=(startday+dpm)%7
end
print(center("[SNOOPY]",calwidth),"\n")
print(center(" | 1,081Calendar
| 1lua
| ur4vl |
import Foundation
func calculateE(epsilon: Double = 1.0e-15) -> Double {
var fact: UInt64 = 1
var e = 2.0, e0 = 0.0
var n = 2
repeat {
e0 = e
fact *= UInt64(n)
n += 1
e += 1.0 / Double(fact)
} while fabs(e - e0) >= epsilon
return e
}
print(String(format: "e =%.15f\n", arguments: [calculateE()])) | 1,072Calculating the value of e
| 17swift
| l5kc2 |
null | 1,077Call a function
| 11kotlin
| cu498 |
package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`) | 1,082Bulls and cows
| 0go
| w0xeg |
sub factorial { my $f = 1; $f *= $_ for 2 .. $_[0]; $f; }
sub catalan {
my $n = shift;
factorial(2*$n) / factorial($n+1) / factorial($n);
}
print "$_\t@{[ catalan($_) ]}\n" for 0 .. 20; | 1,068Catalan numbers
| 2perl
| 24elf |
import pygame, sys, os
from pygame.locals import *
from random import randint
pygame.init()
MAXSPEED = 15
SIZE = 3
COLOR = (45, 90, 45)
WINDOWSIZE = 400
TIMETICK = 1
MAXPART = 50
freeParticles = pygame.sprite.Group()
tree = pygame.sprite.Group()
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption()
screen = pygame.display.get_surface()
class Particle(pygame.sprite.Sprite):
def __init__(self, vector, location, surface):
pygame.sprite.Sprite.__init__(self)
self.vector = vector
self.surface = surface
self.accelerate(vector)
self.add(freeParticles)
self.rect = pygame.Rect(location[0], location[1], SIZE, SIZE)
self.surface.fill(COLOR, self.rect)
def onEdge(self):
if self.rect.left <= 0:
self.vector = (abs(self.vector[0]), self.vector[1])
elif self.rect.top <= 0:
self.vector = (self.vector[0], abs(self.vector[1]))
elif self.rect.right >= WINDOWSIZE:
self.vector = (-abs(self.vector[0]), self.vector[1])
elif self.rect.bottom >= WINDOWSIZE:
self.vector = (self.vector[0], -abs(self.vector[1]))
def update(self):
if freeParticles in self.groups():
self.surface.fill((0,0,0), self.rect)
self.remove(freeParticles)
if pygame.sprite.spritecollideany(self, freeParticles):
self.accelerate((randint(-MAXSPEED, MAXSPEED),
randint(-MAXSPEED, MAXSPEED)))
self.add(freeParticles)
elif pygame.sprite.spritecollideany(self, tree):
self.stop()
else:
self.add(freeParticles)
self.onEdge()
if (self.vector == (0,0)) and tree not in self.groups():
self.accelerate((randint(-MAXSPEED, MAXSPEED),
randint(-MAXSPEED, MAXSPEED)))
self.rect.move_ip(self.vector[0], self.vector[1])
self.surface.fill(COLOR, self.rect)
def stop(self):
self.vector = (0,0)
self.remove(freeParticles)
self.add(tree)
def accelerate(self, vector):
self.vector = vector
NEW = USEREVENT + 1
TICK = USEREVENT + 2
pygame.time.set_timer(NEW, 50)
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == NEW and (len(freeParticles) < MAXPART):
Particle((randint(-MAXSPEED,MAXSPEED),
randint(-MAXSPEED,MAXSPEED)),
(randint(0, WINDOWSIZE), randint(0, WINDOWSIZE)),
screen)
elif event.type == TICK:
freeParticles.update()
half = WINDOWSIZE/2
tenth = WINDOWSIZE/10
root = Particle((0,0),
(randint(half-tenth, half+tenth),
randint(half-tenth, half+tenth)), screen)
root.stop()
while True:
input(pygame.event.get())
pygame.display.flip() | 1,079Brownian tree
| 3python
| ghh4h |
plotmat <- function(mat, fn, clr, ttl, dflg=0, psz=600) {
m <- nrow(mat); d <- 0;
X=NULL; Y=NULL;
pf = paste0(fn, ".png"); df = paste0(fn, ".dmp");
for (i in 1:m) {
for (j in 1:m) {if(mat[i,j]==0){next} else {d=d+1; X[d] <- i; Y[d] <- j;} }
};
cat(" *** Matrix(", m,"x",m,")", d, "DOTS\n");
if (dflg==1) {dump(c("X","Y"), df); cat(" *** Dump file:", df, "\n")};
plot(X,Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20);
dev.copy(png, filename=pf, width=psz, height=psz);
dev.off(); graphics.off();
}
plotv2 <- function(fn, clr, ttl, psz=600) {
cat(" *** START:", date(), "clr=", clr, "psz=", psz, "\n");
cat(" *** File name -", fn, "\n");
pf = paste0(fn, ".png"); df = paste0(fn, ".dmp");
source(df);
d <- length(X);
cat(" *** Source dump-file:", df, d, "DOTS\n");
cat(" *** Plot file -", pf, "\n");
plot(X, Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20);
dev.copy(png, filename=pf, width=psz, height=psz);
dev.off(); graphics.off();
cat(" *** END:", date(), "\n");
} | 1,079Brownian tree
| 13r
| vgg27 |
class BullsAndCows {
static void main(args) {
def inputReader = System.in.newReader()
def numberGenerator = new Random()
def targetValue
while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue
def targetStr = targetValue.toString()
def guessed = false
def guesses = 0
while (!guessed) {
def bulls = 0, cows = 0
print 'Guess a 4-digit number with no duplicate digits: '
def guess = inputReader.readLine()
if (guess.length() != 4 || !guess.isInteger() || targetValueIsInvalid(guess.toInteger())) {
continue
}
guesses++
4.times {
if (targetStr[it] == guess[it]) {
bulls++
} else if (targetStr.contains(guess[it])) {
cows++
}
}
if (bulls == 4) {
guessed = true
} else {
println "$cows Cows and $bulls Bulls."
}
}
println "You won after $guesses guesses!"
}
static targetValueIsInvalid(value) {
def digitList = []
while (value > 0) {
if (digitList[value % 10] == 0 || digitList[value % 10]) {
return true
}
digitList[value % 10] = true
value = value.intdiv(10)
}
false
}
} | 1,082Bulls and cows
| 7groovy
| bepky |
<?php
class CatalanNumbersSerie
{
private static $cache = array(0 => 1);
private function fill_cache($i)
{
$accum = 0;
$n = $i-1;
for($k = 0; $k <= $n; $k++)
{
$accum += $this->item($k)*$this->item($n-$k);
}
self::$cache[$i] = $accum;
}
function item($i)
{
if (!isset(self::$cache[$i]))
{
$this->fill_cache($i);
}
return self::$cache[$i];
}
}
$cn = new CatalanNumbersSerie();
for($i = 0; $i <= 15;$i++)
{
$r = $cn->item($i);
echo ;
}
?> | 1,068Catalan numbers
| 12php
| sicqs |
def sameDigits(n,b)
f = n % b
while (n /= b) > 0 do
if n % b!= f then
return false
end
end
return true
end
def isBrazilian(n)
if n < 7 then
return false
end
if n % 2 == 0 then
return true
end
for b in 2 .. n - 2 do
if sameDigits(n, b) then
return true
end
end
return false
end
def isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
d = 5
while d * d <= n do
if n % d == 0 then
return false
end
d = d + 2
if n % d == 0 then
return false
end
d = d + 4
end
return true
end
def main
for kind in [, , ] do
quiet = false
bigLim = 99999
limit = 20
puts % [limit, kind]
c = 0
n = 7
while c < bigLim do
if isBrazilian(n) then
if not quiet then
print % [n]
end
c = c + 1
if c == limit then
puts
puts
quiet = true
end
end
if quiet and kind!= then
next
end
if kind == then
n = n + 1
elsif kind == then
n = n + 2
elsif kind == then
loop do
n = n + 2
if isPrime(n) then
break
end
end
else
raise
end
end
if kind == then
puts % [bigLim + 1, n]
puts
end
end
end
main() | 1,080Brazilian numbers
| 14ruby
| sioqw |
import Data.List (partition, intersect, nub)
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
import Text.Printf
numberOfDigits = 4 :: Int
main = bullsAndCows
bullsAndCows :: IO ()
bullsAndCows = do
digits <- getStdRandom $ pick numberOfDigits ['1' .. '9']
putStrLn "Guess away!"
loop digits
where loop digits = do
input <- getLine
if okay input
then
let (bulls, cows) = score digits input in
if bulls == numberOfDigits then
putStrLn "You win!"
else do
printf "%d bulls,%d cows.\n" bulls cows
loop digits
else do
putStrLn "Malformed guess; try again."
loop digits
okay :: String -> Bool
okay input =
length input == numberOfDigits &&
input == nub input &&
all legalchar input
where legalchar c = '1' <= c && c <= '9'
score :: String -> String -> (Int, Int)
score secret guess = (length bulls, cows)
where (bulls, nonbulls) = partition (uncurry (==)) $
zip secret guess
cows = length $ uncurry intersect $ unzip nonbulls
pick :: Int -> [a] -> StdGen -> ([a], StdGen)
pick n l g = f n l g (length l - 1) []
where f 0 _ g _ ps = (ps, g)
f n l g max ps =
f (n - 1) (left ++ right) g' (max - 1) (picked: ps)
where (i, g') = randomR (0, max) g
(left, picked: right) = splitAt i l | 1,082Bulls and cows
| 8haskell
| 6cy3k |
fn same_digits(x: u64, base: u64) -> bool {
let f = x% base;
let mut n = x;
while n > 0 {
if n% base!= f {
return false;
}
n /= base;
}
true
}
fn is_brazilian(x: u64) -> bool {
if x < 7 {
return false;
};
if x% 2 == 0 {
return true;
};
for base in 2..(x - 1) {
if same_digits(x, base) {
return true;
}
}
false
}
fn main() {
let mut counter = 0;
let limit = 20;
let big_limit = 100_000;
let mut big_result: u64 = 0;
let mut br: Vec<u64> = Vec::new();
let mut o: Vec<u64> = Vec::new();
let mut p: Vec<u64> = Vec::new();
for x in 7.. {
if is_brazilian(x) {
counter += 1;
if br.len() < limit {
br.push(x);
}
if o.len() < limit && x% 2 == 1 {
o.push(x);
}
if p.len() < limit && primes::is_prime(x) {
p.push(x);
}
if counter == big_limit {
big_result = x;
break;
}
}
}
println!("First {} Brazilian numbers:", limit);
println!("{:?}", br);
println!("\nFirst {} odd Brazilian numbers:", limit);
println!("{:?}", o);
println!("\nFirst {} prime Brazilian numbers:", limit);
println!("{:?}", p);
println!("\nThe {}th Brazilian number: {}", big_limit, big_result);
} | 1,080Brazilian numbers
| 15rust
| 0nisl |
object BrazilianNumbers {
private val PRIME_LIST = List(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
)
def isPrime(n: Int): Boolean = {
if (n < 2) {
return false
}
for (prime <- PRIME_LIST) {
if (n == prime) {
return true
}
if (n % prime == 0) {
return false
}
if (prime * prime > n) {
return true
}
}
val bigDecimal = BigInt.int2bigInt(n)
bigDecimal.isProbablePrime(10)
}
def sameDigits(n: Int, b: Int): Boolean = {
var n2 = n
val f = n % b
var done = false
while (!done) {
n2 /= b
if (n2 > 0) {
if (n2 % b != f) {
return false
}
} else {
done = true
}
}
true
}
def isBrazilian(n: Int): Boolean = {
if (n < 7) {
return false
}
if (n % 2 == 0) {
return true
}
for (b <- 2 until n - 1) {
if (sameDigits(n, b)) {
return true
}
}
false
}
def main(args: Array[String]): Unit = {
for (kind <- List("", "odd ", "prime ")) {
var quiet = false
var bigLim = 99999
var limit = 20
println(s"First $limit ${kind}Brazilian numbers:")
var c = 0
var n = 7
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) {
print(s"$n ")
}
c = c + 1
if (c == limit) {
println()
println()
quiet = true
}
}
if (!quiet || kind == "") {
if (kind == "") {
n = n + 1
} else if (kind == "odd ") {
n = n + 2
} else if (kind == "prime ") {
do {
n = n + 2
} while (!isPrime(n))
} else {
throw new AssertionError("Oops")
}
}
}
if (kind == "") {
println(s"The ${bigLim + 1}th Brazilian number is: $n")
println()
}
}
}
} | 1,080Brazilian numbers
| 16scala
| itfox |
require 'rubygems'
require 'RMagick'
NUM_PARTICLES = 1000
SIZE = 800
def draw_brownian_tree world
world[rand SIZE][rand SIZE] = 1
NUM_PARTICLES.times do
px = rand SIZE
py = rand SIZE
loop do
dx = rand(3) - 1
dy = rand(3) - 1
if dx + px < 0 or dx + px >= SIZE or dy + py < 0 or dy + py >= SIZE
px = rand SIZE
py = rand SIZE
elsif world[py + dy][px + dx]!= 0
world[py][px] = 1
break
else
py += dy
px += dx
end
end
end
end
world = Array.new(SIZE) { Array.new(SIZE, 0) }
srand Time.now.to_i
draw_brownian_tree world
img = Magick::Image.new(SIZE, SIZE) do
self.background_color =
end
draw = Magick::Draw.new
draw.fill
world.each_with_index do |row, y|
row.each_with_index do |colour, x|
draw.point x, y if colour!= 0
end
end
draw.draw img
img.write | 1,079Brownian tree
| 14ruby
| 7bbri |
use strict;
use warnings;
use Time::Local;
my $year = shift // 1969;
my $width = shift // 80;
my $columns = int +($width + 2) / 22 or die "width too short at $width";
print map { center($_, $width), "\n" } '<reserved for snoopy>', $year;
my @months = qw( January February March April May June
July August September October November December );
my @days = qw( 31 28 31 30 31 30 31 31 30 31 30 31 );
(gmtime 86400 + timegm 1,1,1,28,1,$year)[3] == 29 and $days[1]++;
my @blocks = map
{
my $m = center($months[$_], 20) . "\nSu Mo Tu We Th Fr Sa\n" .
"00 00 00 00 00 00 00\n" x 6;
$m =~ s/00/ / for 1 .. (gmtime timegm 1,1,1,1,$_,$year )[6];
$m =~ s/00/ center($_, 2) /e for 1 .. $days[$_];
$m =~ s/00/ /g;
[ split /\n/, $m ]
} 0 .. 11;
while( my @row = splice @blocks, 0, $columns )
{
print center(join(' ', map shift @$_, @row), $width) for 1 .. @{$row[0]};
}
sub center
{
my ($string, $w) = @_;
sprintf "%${w}s", $string . ' ' x ($w - length($string) >> 1);
} | 1,081Calendar
| 2perl
| 0nos4 |
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class BullsAndCows{
public static void main(String[] args){
Random gen= new Random();
int target;
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
String targetStr = target +"";
boolean guessed = false;
Scanner input = new Scanner(System.in);
int guesses = 0;
do{
int bulls = 0;
int cows = 0;
System.out.print("Guess a 4-digit number with no duplicate digits: ");
int guess;
try{
guess = input.nextInt();
if(hasDupes(guess) || guess < 1000) continue;
}catch(InputMismatchException e){
continue;
}
guesses++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}
}
if(bulls == 4){
guessed = true;
}else{
System.out.println(cows+" Cows and "+bulls+" Bulls.");
}
}while(!guessed);
System.out.println("You won after "+guesses+" guesses!");
}
public static boolean hasDupes(int num){
boolean[] digs = new boolean[10];
while(num > 0){
if(digs[num%10]) return true;
digs[num%10] = true;
num/= 10;
}
return false;
}
} | 1,082Bulls and cows
| 9java
| nzdih |
null | 1,077Call a function
| 1lua
| l5gck |
extern crate image;
extern crate rand;
use image::ColorType;
use std::cmp::{min, max};
use std::env;
use std::path::Path;
use std::process;
use rand::Rng;
fn help() {
println!("Usage: brownian_tree <output_path> <mote_count> <edge_length>");
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut output_path = Path::new("out.png");
let mut mote_count: u32 = 10000;
let mut width: usize = 512;
let mut height: usize = 512;
match args.len() {
1 => {}
4 => {
output_path = Path::new(&args[1]);
mote_count = args[2].parse::<u32>().unwrap();
width = args[3].parse::<usize>().unwrap();
height = width;
}
_ => {
help();
process::exit(0);
}
}
assert!(width >= 2); | 1,079Brownian tree
| 15rust
| jpp72 |
#!/usr/bin/env js
function main() {
var len = 4;
playBullsAndCows(len);
}
function playBullsAndCows(len) {
var num = pickNum(len); | 1,082Bulls and cows
| 10javascript
| 396z0 |
import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.JFrame
import scala.collection.mutable.ListBuffer
object BrownianTree extends App {
val rand = scala.util.Random
class BrownianTree extends JFrame("Brownian Tree") with Runnable {
setBounds(100, 100, 400, 300)
val img = new BufferedImage(getWidth, getHeight, BufferedImage.TYPE_INT_RGB)
override def paint(g: Graphics): Unit = g.drawImage(img, 0, 0, this)
override def run(): Unit = {
class Particle(var x: Int = rand.nextInt(img.getWidth),
var y: Int = rand.nextInt(img.getHeight)) {
def move: Boolean = {
val (dx, dy) = (rand.nextInt(3) - 1, rand.nextInt(3) - 1)
if ((x + dx < 0) || (y + dy < 0) ||
(y + dy >= img.getHeight) || (x + dx >= img.getWidth)) false
else {
x += dx
y += dy
if ((img.getRGB(x, y) & 0xff00) == 0xff00) {
img.setRGB(x - dx, y - dy, 0xff00)
false
} else true
}
}
}
var particles = ListBuffer.fill(20000)(new Particle)
while (particles.nonEmpty) {
particles = particles.filter(_.move)
repaint()
}
}
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)
img.setRGB(img.getWidth / 2, img.getHeight / 2, 0xff00)
setVisible(true)
}
new Thread(new BrownianTree).start()
} | 1,079Brownian tree
| 16scala
| beek6 |
null | 1,082Bulls and cows
| 11kotlin
| si0q7 |
from math import factorial
import functools
def memoize(func):
cache = {}
def memoized(key):
if key not in cache:
cache[key] = func(key)
return cache[key]
return functools.update_wrapper(memoized, func)
@memoize
def fact(n):
return factorial(n)
def cat_direct(n):
return fact(2 * n)
@memoize
def catR1(n):
return 1 if n == 0 else (
sum(catR1(i) * catR1(n - 1 - i) for i in range(n))
)
@memoize
def catR2(n):
return 1 if n == 0 else (
((4 * n - 2) * catR2(n - 1))
)
if __name__ == '__main__':
def pr(results):
fmt = '%-10s%-10s%-10s'
print((fmt% tuple(c.__name__ for c in defs)).upper())
print(fmt% (('=' * 10,) * 3))
for r in zip(*results):
print(fmt% r)
defs = (cat_direct, catR1, catR2)
results = [tuple(c(i) for i in range(15)) for c in defs]
pr(results) | 1,068Catalan numbers
| 3python
| vgw29 |
catalan <- function(n) choose(2*n, n)/(n + 1)
catalan(0:15)
[1] 1 1 2 5 14 42 132 429 1430
[10] 4862 16796 58786 208012 742900 2674440 9694845 | 1,068Catalan numbers
| 13r
| 9vpmg |
Subsets and Splits