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,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 (j...
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, 4...
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(...
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 S...
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} \\,}{ cas...
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 ...
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 ...
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 ...
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]] { switc...
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(); Sys...
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,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...
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...
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) -> In...
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) % 2...
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 sco...
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 = ['']...
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...
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("Possibili...
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 _BE...
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]!! ...
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,...
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("Bro...
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] (app...
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 = []; ...
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) ...
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, 16...
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 ...
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 =...
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.z...
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(Rand...
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...
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{|...
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) the...
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."); ...
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++) { ...
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 { mat...
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 = ...
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()...
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 IllegalArgum...
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...
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_d...
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" = ${ite...
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 t...
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)/...
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: [calcul...
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.displ...
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,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() de...
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(sel...
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,...
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!" ...
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; ...
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, ...
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 >= SIZ...
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 O...
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; ...
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(); l...
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 ...
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(...
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