code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
MyClass::method($someParameter); $foo = 'MyClass'; $foo::method($someParameter); $myInstance->method($someParameter);
1,065Call an object method
12php
kazhv
char *list; const char *line = ; int len = 0; int irand(int n) { int r, rand_max = RAND_MAX - (RAND_MAX % n); do { r = rand(); } while(r >= rand_max); return r / (rand_max / n); } char* get_digits(int n, char *ret) { int i, j; char d[] = ; for (i = 0; i < n; i++) { j = irand(9 - i); ret[i] = d[i + j]; if (j) d[i + j] = d[i], d[i] = ret[i]; } return ret; } int score(const char *digits, const char *guess, int *cow) { int i, bits = 0, bull = *cow = 0; for (i = 0; guess[i] != '\0'; i++) if (guess[i] != digits[i]) bits |= MASK(digits[i]); else ++bull; while (i--) *cow += ((bits & MASK(guess[i])) != 0); return bull; } void pick(int n, int got, int marker, char *buf) { int i, bits = 1; if (got >= n) strcpy(list + (n + 1) * len++, buf); else for (i = 0; i < 9; i++, bits *= 2) { if ((marker & bits)) continue; buf[got] = i + '1'; pick(n, got + 1, marker | bits, buf); } } void filter(const char *buf, int n, int bull, int cow) { int i = 0, c; char *ptr = list; while (i < len) { if (score(ptr, buf, &c) != bull || c != cow) strcpy(ptr, list + --len * (n + 1)); else ptr += n + 1, i++; } } void game(const char *tgt, char *buf) { int i, p, bull, cow, n = strlen(tgt); for (i = 0, p = 1; i < n && (p *= 9 - i); i++); list = malloc(p * (n + 1)); pick(n, 0, 0, buf); for (p = 1, bull = 0; n - bull; p++) { strcpy(buf, list + (n + 1) * irand(len)); bull = score(tgt, buf, &cow); printf( , p, buf, len, bull, cow, line); filter(buf, n, bull, cow); } } int main(int c, char **v) { int n = c > 1 ? atoi(v[1]) : 4; char secret[10] = , answer[10] = ; srand(time(0)); printf(, line, get_digits(n, secret), line); game(secret, answer); return 0; }
1,073Bulls and cows/Player
5c
rkwg7
tcc -DSTRUCT=struct -DCONST=const -DINT=int -DCHAR=char -DVOID=void -DMAIN=main -DIF=if -DELSE=else -DWHILE=while -DFOR=for -DDO=do -DBREAK=break -DRETURN=return -DPUTCHAR=putchar UCCALENDAR.c
1,074Calendar - for "REAL" programmers
5c
8d604
package main
1,070Call a foreign-language function
0go
8dc0g
fn compare_co9_efficiency(base: u64, upto: u64) { let naive_candidates: Vec<u64> = (1u64..upto).collect(); let co9_candidates: Vec<u64> = naive_candidates.iter().cloned() .filter(|&x| x% (base - 1) == (x * x)% (base - 1)) .collect(); for candidate in &co9_candidates { print!("{} ", candidate); } println!(); println!( "Trying {} numbers instead of {} saves {:.2}%", co9_candidates.len(), naive_candidates.len(), 100.0 - 100.0 * (co9_candidates.len() as f64 / naive_candidates.len() as f64) ); } fn main() { compare_co9_efficiency(10, 100); compare_co9_efficiency(16, 256); }
1,060Casting out nines
15rust
1x2pu
object kaprekar{
1,060Casting out nines
16scala
w05es
fn main() { let dog = "Benjamin"; let Dog = "Samba"; let DOG = "Bernie"; println!("The three dogs are named {}, {} and {}.", dog, Dog, DOG); }
1,057Case-sensitivity of identifiers
15rust
573uq
val dog = "Benjamin" val Dog = "Samba" val DOG = "Bernie" println("There are three dogs named " + dog + ", " + Dog + ", and " + DOG + ".")
1,057Case-sensitivity of identifiers
16scala
rkmgn
sub cartesian { my $sets = shift @_; for (@$sets) { return [] unless @$_ } my $products = [[]]; for my $set (reverse @$sets) { my $partial = $products; $products = []; for my $item (@$set) { for my $product (@$partial) { push @$products, [$item, @$product]; } } } $products; } sub product { my($s,$fmt) = @_; my $tuples; for $a ( @{ cartesian( \@$s ) } ) { $tuples .= sprintf "($fmt) ", @$a; } $tuples . "\n"; } print product([[1, 2], [3, 4] ], '%1d%1d' ). product([[3, 4], [1, 2] ], '%1d%1d' ). product([[1, 2], [] ], '%1d%1d' ). product([[], [1, 2] ], '%1d%1d' ). product([[1,2,3], [30], [500,100] ], '%1d%1d%3d' ). product([[1,2,3], [], [500,100] ], '%1d%1d%3d' ). product([[1776,1789], [7,12], [4,14,23], [0,1]], '%4d%2d%2d%1d')
1,058Cartesian product of two or more lists
2perl
gh64e
import ctypes user32_dll = ctypes.cdll.LoadLibrary('User32.dll') print user32_dll.GetDoubleClickTime()
1,066Call a function in a shared library
3python
rkigq
(defn inverse-plus-1 [n] (+ 1 (/ 1 n))) (defn e-return [n] (Math/pow (inverse-plus-1 n) n)) (time (e-return 100000.)) (defn method-e [n] (loop [e-aprx 0M value-add 1M p 1M] (if (> p n) e-aprx (recur (+ e-aprx value-add) (/ value-add p) (inc p))))) (time (with-precision 110 (method-e 200M)))
1,072Calculating the value of e
6clojure
cuh9b
import Foreign (free) import Foreign.C.String (CString, withCString, peekCString) foreign import ccall unsafe "string.h strdup" strdup :: CString -> IO CString testC = withCString "Hello World!" (\s -> do s2 <- strdup s s2_hs <- peekCString s2 putStrLn s2_hs free s2)
1,070Call a foreign-language function
8haskell
l5pch
null
1,067Cantor set
11kotlin
qocx1
cw = Enumerator.new do |y| y << a = 1.to_r loop { y << a = 1/(2*a.floor + 1 - a) } end def term_num(rat) num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1 while den > 0 num, (digit, den) = den, num.divmod(den) digit.times do res |= dig << pwr pwr += 1 end dig ^= 1 end res end puts cw.take(20).join() puts term_num (83116/51639r)
1,069Calkin-Wilf sequence
14ruby
bedkq
null
1,069Calkin-Wilf sequence
15rust
pwfbu
require 'prime' Prime.each(61) do |p| (2...p).each do |h3| g = h3 + p (1...g).each do |d| next if (g*(p-1)) % d!= 0 or (-p*p) % h3!= d % h3 q = 1 + ((p - 1) * g / d) next unless q.prime? r = 1 + (p * q / h3) next unless r.prime? and (q * r) % (p - 1) == 1 puts end end puts end
1,064Carmichael 3 strong pseudoprimes
14ruby
8d401
class MyClass(object): @classmethod def myClassMethod(self, x): pass @staticmethod def myStaticMethod(x): pass def myMethod(self, x): return 42 + x myInstance = MyClass() myInstance.myMethod(someParameter) MyClass.myMethod(myInstance, someParameter) MyClass.myClassMethod(someParameter) MyClass.myStaticMethod(someParameter) myInstance.myClassMethod(someParameter) myInstance.myStaticMethod(someParameter)
1,065Call an object method
3python
zmktt
dyn.load("my/special/R/lib.so") .Call("my_lib_fun", arg1, arg2)
1,066Call a function in a shared library
13r
ursvx
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) table := make([]string, le) table[0] = s for i := 1; i < le; i++ { table[i] = s[i:] + s[:i] } sort.Strings(table) lastBytes := make([]byte, le) for i := 0; i < le; i++ { lastBytes[i] = table[i][le-1] } return string(lastBytes), nil } func ibwt(r string) string { le := len(r) table := make([]string, le) for range table { for i := 0; i < le; i++ { table[i] = r[i:i+1] + table[i] } sort.Strings(table) } for _, row := range table { if strings.HasSuffix(row, etx) { return row[1 : le-1] } } return "" } func makePrintable(s string) string {
1,071Burrows–Wheeler transform
0go
24pl7
local WIDTH = 81 local HEIGHT = 5 local lines = {} function cantor(start, length, index)
1,067Cantor set
1lua
silq8
fn is_prime(n: i64) -> bool { if n > 1 { (2..((n / 2) + 1)).all(|x| n% x!= 0) } else { false } }
1,064Carmichael 3 strong pseudoprimes
15rust
ofg83
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >=%18s is%14s in the series:%18s\n", climit, ctotal, cnext) } }
1,075Brilliant numbers
0go
vgh2m
class BWT { private static final String STX = "\u0002" private static final String ETX = "\u0003" private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String cannot contain STX or ETX") } String ss = STX + s + ETX List<String> table = new ArrayList<>() for (int i = 0; i < ss.length(); i++) { String before = ss.substring(i) String after = ss.substring(0, i) table.add(before + after) } Collections.sort(table) StringBuilder sb = new StringBuilder() for (String str: table) { sb.append(str[str.length() - 1]) } return sb.toString() } private static String ibwt(String r) { int len = r.length() List<String> table = new ArrayList<>() for (int i = 0; i < len; ++i) { table.add("") } for (int j = 0; j < len; ++j) { for (int i = 0; i < len; ++i) { table[i] = r[i] + table[i] } Collections.sort(table) } for (String row: table) { if (row.endsWith(ETX)) { return row.substring(1, len - 1) } } return "" } private static String makePrintable(String s) {
1,071Burrows–Wheeler transform
7groovy
yl76o
public class JNIDemo { static { System.loadLibrary("JNIDemo"); } public static void main(String[] args) { System.out.println(callStrdup("Hello World!")); } private static native String callStrdup(String s); }
1,070Call a foreign-language function
9java
39rzg
MyClass.some_method(some_parameter) foo = MyClass foo.some_method(some_parameter) my_instance.a_method(some_parameter) my_instance.a_method some_parameter my_instance.another_method
1,065Call an object method
14ruby
6cp3t
struct Foo; impl Foo {
1,065Call an object method
15rust
yl168
require 'fiddle/import' module FakeImgLib extend Fiddle::Importer begin dlload './fakeimglib.so' extern 'int openimage(const char *)' rescue Fiddle::DLError @@handle = -1 def openimage(path) $stderr.puts @@handle += 1 end module_function :openimage end end handle = FakeImgLib.openimage() puts
1,066Call a function in a shared library
14ruby
jpd7x
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List (intercalate, transpose) import Data.List.Split (chunksOf, splitWhen) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) isBrilliant :: (Integral a, Show a) => a -> Bool isBrilliant n = case primeFactors n of [a, b] -> length (show a) == length (show b) _ -> False main :: IO () main = do let indexedBrilliants = zip [1 ..] (filter isBrilliant [1 ..]) putStrLn $ table " " $ chunksOf 10 $ show . snd <$> take 100 indexedBrilliants putStrLn "(index, brilliant)" mapM_ print $ take 6 $ fmap (fst . head) $ splitWhen (uncurry (<) . join bimap (length . show . snd)) $ zip indexedBrilliants (tail indexedBrilliants) table :: String -> [[String]] -> String table gap rows = let ws = maximum . fmap length <$> transpose rows pw = printf . flip intercalate ["%", "s"] . show in unlines $ intercalate gap . zipWith pw ws <$> rows
1,075Brilliant numbers
8haskell
esiai
import Data.List ((!!), find, sort, tails, transpose) import Data.Maybe (fromJust) import Text.Printf (printf) newtype BWT a = BWT [Val a] bwt :: Ord a => [a] -> BWT a bwt xs = let n = length xs + 2 ys = transpose $ sort $ take n $ tails $ cycle $ pos xs in BWT $ ys !! (n-1) invBwt :: Ord a => BWT a -> [a] invBwt (BWT xs) = let ys = iterate step (map (const []) xs) !! length xs in unpos $ fromJust $ find ((== Post) . last) ys where step = sort . zipWith (:) xs data Val a = In a | Pre | Post deriving (Eq, Ord) pos :: [a] -> [Val a] pos xs = Pre: map In xs ++ [Post] unpos :: [Val a] -> [a] unpos xs = [x | In x <- xs] main :: IO () main = mapM_ testBWT [ "", "a", "BANANA", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" ] testBWT :: String -> IO () testBWT xs = let fwd = bwt xs inv = invBwt fwd in printf "%s\n\t%s\n\t%s\n" xs (pretty fwd) inv where pretty (BWT ps) = map prettyVal ps prettyVal (In c) = c prettyVal Pre = '^' prettyVal Post = '|'
1,071Burrows–Wheeler transform
8haskell
aqf1g
#include <napi.h> #include <openssl/md5.h> #include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace Napi; Napi::Value md5sum(const Napi::CallbackInfo& info) { std::string input = info[0].ToString(); unsigned char result[MD5_DIGEST_LENGTH]; MD5((unsigned char*)input.c_str(), input.size(), result); std::stringstream md5string; md5string << std::hex << std::setfill('0'); for (const auto& byte : result) md5string << std::setw(2) << (int)byte; return String::New(info.Env(), md5string.str().c_str()); } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "md5sum"), Napi::Function::New(env, md5sum)); return exports; } NODE_API_MODULE(addon, Init)
1,070Call a foreign-language function
10javascript
cub9j
import Foundation extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true } let max = Self(ceil((Double(self).squareRoot()))) for i in stride(from: 2, through: max, by: 1) { if self% i == 0 { return false } } return true } } @inlinable public func carmichael<T: BinaryInteger & SignedNumeric>(p1: T) -> [(T, T, T)] { func mod(_ n: T, _ m: T) -> T { (n% m + m)% m } var res = [(T, T, T)]() guard p1.isPrime else { return res } for h3 in stride(from: 2, to: p1, by: 1) { for d in stride(from: 1, to: h3 + p1, by: 1) { if (h3 + p1) * (p1 - 1)% d!= 0 || mod(-p1 * p1, h3)!= d% h3 { continue } let p2 = 1 + (p1 - 1) * (h3 + p1) / d guard p2.isPrime else { continue } let p3 = 1 + p1 * p2 / h3 guard p3.isPrime && (p2 * p3)% (p1 - 1) == 1 else { continue } res.append((p1, p2, p3)) } } return res } let res = (1..<62) .lazy .filter({ $0.isPrime }) .map(carmichael) .filter({!$0.isEmpty }) .flatMap({ $0 }) for c in res { print(c) }
1,064Carmichael 3 strong pseudoprimes
17swift
0n5s6
class MyClass(val memberVal: Int) {
1,065Call an object method
16scala
cuw93
#![allow(unused_unsafe)] extern crate libc; use std::io::{self,Write}; use std::{mem,ffi,process}; use libc::{c_double, RTLD_NOW};
1,066Call a function in a shared library
15rust
h1fj2
import net.java.dev.sna.SNA import com.sun.jna.ptr.IntByReference object GetDiskFreeSpace extends App with SNA { snaLibrary = "Kernel32"
1,066Call a function in a shared library
16scala
pw3bj
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) { int n = primes.size(); for (int i = 0; i < n; ++i) { int prime1 = primes.get(i); for (int j = i; j < n; ++j) { int prime2 = primes.get(j); brilliantNumbers.add(prime1 * prime2); } } if (brilliantNumbers.size() >= 100) break; } Collections.sort(brilliantNumbers); for (int i = 0; i < 100; ++i) { char c = (i + 1) % 10 == 0 ? '\n' : ' '; System.out.printf("%,5d%c", brilliantNumbers.get(i), c); } System.out.println(); long power = 10; long count = 0; for (int p = 1; p < 2 * primesByDigits.size(); ++p) { var primes = primesByDigits.get(p / 2); long position = count + 1; long minProduct = 0; int n = primes.size(); for (int i = 0; i < n; ++i) { long prime1 = primes.get(i); var primes2 = primes.subList(i, n); int q = (int)((power + prime1 - 1) / prime1); int j = Collections.binarySearch(primes2, q); if (j == n) continue; if (j < 0) j = -(j + 1); long prime2 = primes2.get(j); long product = prime1 * prime2; if (minProduct == 0 || product < minProduct) minProduct = product; position += j; if (prime1 >= prime2) break; } System.out.printf("First brilliant number >= 10^%d is%,d at position%,d\n", p, minProduct, position); power *= 10; if (p % 2 == 1) { long size = primes.size(); count += size * (size + 1) / 2; } } } private static List<List<Integer>> getPrimesByDigits(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 100000); List<List<Integer>> primesByDigits = new ArrayList<>(); List<Integer> primes = new ArrayList<>(); for (int p = 10; p <= limit; ) { int prime = primeGen.nextPrime(); if (prime > p) { primesByDigits.add(primes); primes = new ArrayList<>(); p *= 10; } primes.add(prime); } return primesByDigits; } }
1,075Brilliant numbers
9java
h1xjm
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String cannot contain STX or ETX"); } String ss = STX + s + ETX; List<String> table = new ArrayList<>(); for (int i = 0; i < ss.length(); i++) { String before = ss.substring(i); String after = ss.substring(0, i); table.add(before + after); } table.sort(String::compareTo); StringBuilder sb = new StringBuilder(); for (String str : table) { sb.append(str.charAt(str.length() - 1)); } return sb.toString(); } private static String ibwt(String r) { int len = r.length(); List<String> table = new ArrayList<>(); for (int i = 0; i < len; ++i) { table.add(""); } for (int j = 0; j < len; ++j) { for (int i = 0; i < len; ++i) { table.set(i, r.charAt(i) + table.get(i)); } table.sort(String::compareTo); } for (String row : table) { if (row.endsWith(ETX)) { return row.substring(1, len - 1); } } return ""; } private static String makePrintable(String s) {
1,071Burrows–Wheeler transform
9java
jp07c
null
1,070Call a foreign-language function
11kotlin
nzvij
use strict; use feature 'say'; sub cantor { our($height) = @_; my $width = 3 ** ($height - 1); our @lines = (' sub trim_middle_third { my($len, $start, $index) = @_; my $seg = int $len / 3 or return; for my $i ( $index .. $height - 1 ) { for my $j ( 0 .. $seg - 1 ) { substr $lines[$i], $start + $seg + $j, 1, ' '; } } trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2; } trim_middle_third( $width, 0, 1 ); @lines; } say for cantor(5);
1,067Cantor set
2perl
vgx20
let dog = "Benjamin" let Dog = "Samba" let DOG = "Bernie" println("The three dogs are named \(dog), \(Dog), and \(DOG).")
1,057Case-sensitivity of identifiers
17swift
vgt2r
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
1,058Cartesian product of two or more lists
3python
rkygq
use strict; use warnings; use feature 'say'; use List::AllUtils <max head firstidx uniqint>; use ntheory <primes is_semiprime forsetproduct>; sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } my(@B,@Br); for my $oom (1..5) { my @P = grep { $oom == length } @{primes(10**$oom)}; forsetproduct { is_semiprime($_[0] * $_[1]) and push @B, $_[0] * $_[1] } \@P, \@P; @Br = uniqint sort { $a <=> $b } @Br, @B; } say "First 100 brilliant numbers:\n" . table 10, head 100, @Br; for my $oom (1..9) { my $key = firstidx { $_ > 10**$oom } @Br; printf "First >=%13s is position%9s in the series:%13s\n", comma(10**$oom), comma($key), comma $Br[$key]; }
1,075Brilliant numbers
2perl
ityo3
(ns a) (def ^:private priv:secret) user=> @a/priv user=> @#'a/priv :secret
1,076Break OO privacy
6clojure
tycfv
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf(, a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, , (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf(, args.arg1, args.arg2); } v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf(, f); double a = asin(1);
1,077Call a function
5c
1xspj
null
1,065Call an object method
17swift
39bz2
null
1,071Burrows–Wheeler transform
11kotlin
57eua
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,074Calendar - for "REAL" programmers
0go
57pul
local ffi = require("ffi") ffi.cdef[[ char * strndup(const char * s, size_t n); int strlen(const char *s); ]] local s1 = "Hello, world!" print("Original: " .. s1) local s_s1 = ffi.C.strlen(s1) print("strlen: " .. s_s1) local s2 = ffi.string(ffi.C.strndup(s1, s_s1), s_s1) print("Copy: " .. s2) print("strlen: " .. ffi.C.strlen(s2))
1,070Call a foreign-language function
1lua
d3unq
one_w_many <- function(one, many) lapply(many, function(x) c(one,x)) "%p%" <- function( a, b ) { p = c( sapply(a, function (x) one_w_many(x, b) ) ) if (is.null(unlist(p))) list() else p} display_prod <- function (xs) { for (x in xs) cat( paste(x, collapse=", "), "\n" ) } fmt_vec <- function(v) sprintf("(%s)", paste(v, collapse=', ')) go <- function (...) { cat("\n", paste( sapply(list(...),fmt_vec), collapse=" * "), "\n") prod = Reduce( '%p%', list(...) ) display_prod( prod ) }
1,058Cartesian product of two or more lists
13r
urtvx
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1) continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1) idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
1,075Brilliant numbers
3python
nzmiz
STX = string.char(tonumber(2,16)) ETX = string.char(tonumber(3,16)) function bwt(s) if s:find(STX, 1, true) then error("String cannot contain STX") end if s:find(ETX, 1, true) then error("String cannot contain ETX") end local ss = STX .. s .. ETX local tbl = {} for i=1,#ss do local before = ss:sub(i + 1) local after = ss:sub(1, i) table.insert(tbl, before .. after) end table.sort(tbl) local sb = "" for _,v in pairs(tbl) do sb = sb .. string.sub(v, #v, #v) end return sb end function ibwt(r) local le = #r local tbl = {} for i=1,le do table.insert(tbl, "") end for j=1,le do for i=1,le do tbl[i] = r:sub(i,i) .. tbl[i] end table.sort(tbl) end for _,row in pairs(tbl) do if row:sub(le,le) == ETX then return row:sub(2, le - 1) end end return "" end function makePrintable(s) local a = s:gsub(STX, '^') local b = a:gsub(ETX, '|') return b end function main() local tests = { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", STX .. "ABC" .. ETX } for _,test in pairs(tests) do print(makePrintable(test)) io.write("
1,071Burrows–Wheeler transform
1lua
4jw5c
WIDTH = 81 HEIGHT = 5 lines=[] def cantor(start, len, index): seg = len / 3 if seg == 0: return None for it in xrange(HEIGHT-index): i = index + it for jt in xrange(seg): j = start + seg + jt pos = i * WIDTH + j lines[pos] = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) return None lines = ['*'] * (WIDTH*HEIGHT) cantor(0, WIDTH, 1) for i in xrange(HEIGHT): beg = WIDTH * i print ''.join(lines[beg: beg+WIDTH])
1,067Cantor set
3python
urqvd
null
1,075Brilliant numbers
15rust
tylfd
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { fmt.Println(`Cows and bulls/player You think of four digit number of unique digits in the range 1 to 9. I guess. You score my guess: A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull. You give my score as two numbers separated with a space.`)
1,073Bulls and cows/Player
0go
nzci1
null
1,075Brilliant numbers
17swift
d39nh
typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, , tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, , n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, ); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, , root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, , n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, , n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, ); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf(, input); for (i = 0; i < cnt; i++) { expand(n, i); printf(); } printf(); deallocate_node(n); } int main() { test(); test(); test(); return 0; }
1,078Brace expansion
5c
tymf4
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int
1,076Break OO privacy
0go
4jb52
void draw_brownian_tree(int world[SIZE][SIZE]){ int px, py; int dx, dy; int i; world[rand() % SIZE][rand() % SIZE] = 1; for (i = 0; i < NUM_PARTICLES; i++){ px = rand() % SIZE; py = rand() % SIZE; while (1){ dx = rand() % 3 - 1; dy = rand() % 3 - 1; if (dx + px < 0 || dx + px >= SIZE || dy + py < 0 || dy + py >= SIZE){ px = rand() % SIZE; py = rand() % SIZE; }else if (world[py + dy][px + dx] != 0){ world[py][px] = 1; break; }else{ py += dy; px += dx; } } } } int main(){ int world[SIZE][SIZE]; FIBITMAP * img; RGBQUAD rgb; int x, y; memset(world, 0, sizeof world); srand((unsigned)time(NULL)); draw_brownian_tree(world); img = FreeImage_Allocate(SIZE, SIZE, 32, 0, 0, 0); for (y = 0; y < SIZE; y++){ for (x = 0; x < SIZE; x++){ rgb.rgbRed = rgb.rgbGreen = rgb.rgbBlue = (world[y][x] ? 255 : 0); FreeImage_SetPixelColor(img, x, y, &rgb); } } FreeImage_Save(FIF_BMP, img, , 0); FreeImage_Unload(img); }
1,079Brownian tree
5c
244lo
import Data.List import Control.Monad import System.Random (randomRIO) import Data.Char(digitToInt) combinationsOf 0 _ = [[]] combinationsOf _ [] = [] combinationsOf k (x:xs) = map (x:) (combinationsOf (k-1) xs) ++ combinationsOf k xs player = do let ps = concatMap permutations $ combinationsOf 4 ['1'..'9'] play ps where play ps = if null ps then putStrLn "Unable to find a solution" else do i <- randomRIO(0,length ps - 1) let p = ps!!i :: String putStrLn ("My guess is " ++ p) >> putStrLn "How many bulls and cows?" input <- takeInput let bc = input ::[Int] ps' = filter((==sum bc).length. filter id. map (flip elem p)) $ filter((==head bc).length. filter id. zipWith (==) p) ps if length ps' == 1 then putStrLn $ "The answer is " ++ head ps' else play ps' takeInput = do inp <- getLine let ui = map digitToInt $ take 2 $ filter(`elem` ['0'..'4']) inp if sum ui > 4 || length ui /= 2 then do putStrLn "Wrong input. Try again" takeInput else return ui
1,073Bulls and cows/Player
8haskell
urpv2
(defn one [] "Function that takes no arguments and returns 1" 1) (one)
1,077Call a function
6clojure
qonxt
cantorSet <- function() { depth <- 6L cs <- vector('list', depth) cs[[1L]] <- c(0, 1) for(k in seq_len(depth)) { cs[[k + 1L]] <- unlist(sapply(seq_len(length(cs[[k]]) / 2L), function(j) { p <- cs[[k]][2L] / 3 h <- 2L * (j - 1L) c( cs[[k]][h + 1L] + c(0, p), cs[[k]][h + 2L] - c(p, 0) ) }, simplify = FALSE)) } cs } cantorSetGraph <- function() { cs <- cantorSet() u <- unlist(cs) df <- data.frame( x_start = u[seq_along(u)%% 2L == 1L], x_end = u[seq_along(u)%% 2L == 0L], depth = unlist(lapply(cs, function(e) { l <- length(e) n <- 0 while(l > 1) { n <- n + 1L l <- l / 2 } rep(n, length(e) / 2) })) ) require(ggplot2) g <- ggplot(df, aes_string(x = 'x_start', y = 'depth')) + geom_segment(aes_string(xend = 'x_end', yend = 'depth', size = 3)) + scale_y_continuous(trans = "reverse") + theme( axis.title = element_blank(), axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), legend.position = 'none', aspect.ratio = 1/5 ) list(graph = g, data = df, set = cs) }
1,067Cantor set
13r
cua95
use List::Util 'reduce'; print +(reduce {$a + $b} 1 .. 10), "\n"; sub func { $b & 1 ? "$a $b" : "$b $a" } print +(reduce \&func, 1 .. 10), "\n"
1,061Catamorphism
2perl
4jf5d
use utf8; binmode STDOUT, ":utf8"; use constant STX => ' '; sub transform { my($s) = @_; my($t); warn "String can't contain STX character." and exit if $s =~ /STX/; $s = STX . $s; $t .= substr($_,-1,1) for sort map { rotate($s,$_) } 1..length($s); return $t; } sub rotate { my($s,$n) = @_; join '', (split '', $s)[$n..length($s)-1, 0..$n-1] } sub osu { my($s) = @_; my @s = split '', $s; my @t = sort @s; map { @t = sort map { $s[$_] . $t[$_] } 0..length($s)-1 } 1..length($s)-1; for (@t) { next unless /${\(STX)}$/; chop $_ and return $_ } } for $phrase (qw<BANANA dogwood SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES>, 'TO BE OR NOT TO BE OR WANT TO BE OR NOT?') { push @res, 'Original: '. $phrase; push @res, 'Transformed: '. transform $phrase; push @res, 'Inverse transformed: '. osu transform $phrase; push @res, ''; } print join "\n", @res;
1,071Burrows–Wheeler transform
2perl
ofc8x
import java.lang.reflect.*; class Example { private String _name; public Example(String name) { _name = name; } public String toString() { return "Hello, I am " + _name; } } public class BreakPrivacy { public static final void main(String[] args) throws Exception { Example foo = new Example("Eric"); for (Field f : Example.class.getDeclaredFields()) { if (f.getName().equals("_name")) {
1,076Break OO privacy
9java
pwsb3
public class BullsAndCowsPlayerGame { private static int count; private static Console io = System.console(); private final GameNumber secret; private List<AutoGuessNumber> pool = new ArrayList<>(); public BullsAndCowsPlayerGame(GameNumber secret) { this.secret = secret; fillPool(); } private void fillPool() { for (int i = 123; i < 9877; i++) { int[] arr = AutoGuessNumber.parseDigits(i, 4); if (GameNumber.isGuess(arr)) { pool.add(new AutoGuessNumber(i, 4)); } } } public void play() { io.printf("Bulls and Cows%n"); io.printf("==============%n"); io.printf("Secret number is%s%n", secret); do { AutoGuessNumber guess = guessNumber(); io.printf("Guess #%d is%s from%d%n", count, guess, pool.size()); GuessResult result = secret.match(guess); if (result != null) { printScore(io, result); if (result.isWin()) { io.printf("The answer is%s%n", guess); break; } clearPool(guess, result); } else { io.printf("No more variants%n"); System.exit(0); } } while (true); } private AutoGuessNumber guessNumber() { Random random = new Random(); if (pool.size() > 0) { int number = random.nextInt(pool.size()); count++; return pool.get(number); } return null; } private static void printScore(Console io, GuessResult result) { io.printf("%1$d %2$d%n", result.getBulls(), result.getCows()); } private void clearPool(AutoGuessNumber guess, GuessResult guessResult) { pool.remove(guess); for (int i = 0; i < pool.size(); i++) { AutoGuessNumber g = pool.get(i); GuessResult gr = guess.match(g); if (!guessResult.equals(gr)) { pool.remove(g); } } } public static void main(String[] args) { new BullsAndCowsPlayerGame(new GameNumber()).play(); } }
1,073Bulls and cows/Player
9java
m2rym
IMPORT JAVA.TEXT.* IMPORT JAVA.UTIL.* IMPORT JAVA.IO.PRINTSTREAM 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..NROWS - 1) { FOR (I IN 0..7) { VAR C = R * NCOLS WHILE (C < (R + 1) * NCOLS && C < 12) { PRINTF(" %S", MONS[C][I].TOUPPERCASE())
1,074Calendar - for "REAL" programmers
11kotlin
rkego
p [1, 2].product([3, 4]) p [3, 4].product([1, 2]) p [1, 2].product([]) p [].product([1, 2]) p [1776, 1789].product([7, 12], [4, 14, 23], [0, 1]) p [1, 2, 3].product([30], [500, 100]) p [1, 2, 3].product([], [500, 100])
1,058Cartesian product of two or more lists
14ruby
jp97x
import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible class ToBeBroken { @Suppress("unused") private val secret: Int = 42 } fun main(args: Array<String>) { val tbb = ToBeBroken() val props = ToBeBroken::class.declaredMemberProperties for (prop in props) { prop.isAccessible = true
1,076Break OO privacy
11kotlin
7bar4
local function Counter()
1,076Break OO privacy
1lua
jpe71
def bwt(s): assert not in s and not in s, s = + s + table = sorted(s[i:] + s[:i] for i in range(len(s))) last_column = [row[-1:] for row in table] return .join(last_column) def ibwt(r): table = [] * len(r) for i in range(len(r)): table = sorted(r[i] + table[i] for i in range(len(r))) s = [row for row in table if row.endswith()][0] return s.rstrip().strip()
1,071Burrows–Wheeler transform
3python
itlof
null
1,073Bulls and cows/Player
11kotlin
tyvf0
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):UPPER(),"\N") PRINT(CENTER("
1,074Calendar - for "REAL" programmers
1lua
7bwru
lines = 5 (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1)? : } puts chars.map{ |c| c * seg_size }.join end
1,067Cantor set
14ruby
4j05p
fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> { let mut res = vec![]; let mut list_iter = lists.iter(); if let Some(first_list) = list_iter.next() { for &i in first_list { res.push(vec![i]); } } for l in list_iter { let mut tmp = vec![]; for r in res { for &el in l { let mut tmp_el = r.clone(); tmp_el.push(el); tmp.push(tmp_el); } } res = tmp; } res } fn main() { let cases = vec![ vec![vec![1, 2], vec![3, 4]], vec![vec![3, 4], vec![1, 2]], vec![vec![1, 2], vec![]], vec![vec![], vec![1, 2]], vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]], vec![vec![1, 2, 3], vec![30], vec![500, 100]], vec![vec![1, 2, 3], vec![], vec![500, 100]], ]; for case in cases { println!( "{}\n{:?}\n", case.iter().map(|c| format!("{:?}", c)).collect::<Vec<_>>().join(" "), cartesian_product(&case) ) } }
1,058Cartesian product of two or more lists
15rust
h1cj2
typedef char bool; bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; } bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n % 2) && n >= 8) return TRUE; for (b = 2; b < n - 1; ++b) { if (same_digits(n, b)) return TRUE; } return FALSE; } bool is_prime(int n) { int d = 5; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; while (d * d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) return FALSE; d += 4; } return TRUE; } int main() { int i, c, n; const char *kinds[3] = {, , }; for (i = 0; i < 3; ++i) { printf(, kinds[i]); c = 0; n = 7; while (TRUE) { if (is_brazilian(n)) { printf(, n); if (++c == 20) { printf(); break; } } switch (i) { case 0: n++; break; case 1: n += 2; break; case 2: do { n += 2; } while (!is_prime(n)); break; } } } for (n = 7, c = 0; c < 100000; ++n) { if (is_brazilian(n)) c++; } printf(, n - 1); return 0; }
1,080Brazilian numbers
5c
pweby
use convert_base::Convert; use std::fmt; struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> {
1,067Cantor set
15rust
gh84o
object CantorSetQD extends App { val (width, height) = (81, 5) val lines = Seq.fill[Array[Char]](height)(Array.fill[Char](width)('*')) def cantor(start: Int, len: Int, index: Int) { val seg = len / 3 println(start, len, index) if (seg != 0) { for (i <- index until height; j <- (start + seg) until (start + seg * 2)) lines(i)(j) = ' ' cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } } cantor(0, width, 1) lines.foreach(l => println(l.mkString)) }
1,067Cantor set
16scala
jpn7i
>>> >>> from operator import add >>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']] >>> help(reduce) Help on built-in function reduce in module __builtin__: reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. >>> reduce(add, listoflists, []) ['the', 'cat', 'sat', 'on', 'the', 'mat'] >>>
1,061Catamorphism
3python
ght4h
def cartesianProduct[T](lst: List[T]*): List[List[T]] = { def pel(e: T, ll: List[List[T]], a: List[List[T]] = Nil): List[List[T]] = ll match { case Nil => a.reverse case x :: xs => pel(e, xs, (e :: x) :: a ) } lst.toList match { case Nil => Nil case x :: Nil => List(x) case x :: _ => x match { case Nil => Nil case _ => lst.par.foldRight(List(x))( (l, a) => l.flatMap(pel(_, a)) ).map(_.dropRight(x.size)) } } }
1,058Cartesian product of two or more lists
16scala
pwvbj
package main import ( "fmt" "math/big" ) func main() { var b, c big.Int for n := int64(0); n < 15; n++ { fmt.Println(c.Div(b.Binomial(n*2, n), c.SetInt64(n+1))) } }
1,068Catalan numbers
0go
aq31f
package expand
1,078Brace expansion
0go
h1ajq
int width = 80, year = 1969; int cols, lead, gap; const char *wdays[] = { , , , , , , }; struct months { const char *name; int days, start_wday, at; } months[12] = { { , 31, 0, 0 }, { , 28, 0, 0 }, { , 31, 0, 0 }, { , 30, 0, 0 }, { , 31, 0, 0 }, { , 30, 0, 0 }, { , 31, 0, 0 }, { , 31, 0, 0 }, { , 30, 0, 0 }, { , 31, 0, 0 }, { , 30, 0, 0 }, { , 31, 0, 0 } }; void space(int n) { while (n-- > 0) putchar(' '); } void init_months() { int i; if ((!(year % 4) && (year % 100)) || !(year % 400)) months[1].days = 29; year--; months[0].start_wday = (year * 365 + year/4 - year/100 + year/400 + 1) % 7; for (i = 1; i < 12; i++) months[i].start_wday = (months[i-1].start_wday + months[i-1].days) % 7; cols = (width + 2) / 22; while (12 % cols) cols--; gap = cols - 1 ? (width - 20 * cols) / (cols - 1) : 0; if (gap > 4) gap = 4; lead = (width - (20 + gap) * cols + gap + 1) / 2; year++; } void print_row(int row) { int c, i, from = row * cols, to = from + cols; space(lead); for (c = from; c < to; c++) { i = strlen(months[c].name); space((20 - i)/2); printf(, months[c].name); space(20 - i - (20 - i)/2 + ((c == to - 1) ? 0 : gap)); } putchar('\n'); space(lead); for (c = from; c < to; c++) { for (i = 0; i < 7; i++) printf(, wdays[i], i == 6 ? : ); if (c < to - 1) space(gap); else putchar('\n'); } while (1) { for (c = from; c < to; c++) if (months[c].at < months[c].days) break; if (c == to) break; space(lead); for (c = from; c < to; c++) { for (i = 0; i < months[c].start_wday; i++) space(3); while(i++ < 7 && months[c].at < months[c].days) { printf(, ++months[c].at); if (i < 7 || c < to - 1) putchar(' '); } while (i++ <= 7 && c < to - 1) space(3); if (c < to - 1) space(gap - 1); months[c].start_wday = 0; } putchar('\n'); } putchar('\n'); } void print_year() { int row; char buf[32]; sprintf(buf, , year); space((width - strlen(buf)) / 2); printf(, buf); for (row = 0; row * cols < 12; row++) print_row(row); } int main(int c, char **v) { int i, year_set = 0; for (i = 1; i < c; i++) { if (!strcmp(v[i], )) { if (++i == c || (width = atoi(v[i])) < 20) goto bail; } else if (!year_set) { if (!sscanf(v[i], , &year) || year <= 0) year = 1969; year_set = 1; } else goto bail; } init_months(); print_year(); return 0; bail: fprintf(stderr, , v[0]); exit(1); }
1,081Calendar
5c
w0qec
package main import ( "fmt" "math" ) const epsilon = 1.0e-15 func main() { fact := uint64(1) e := 2.0 n := uint64(2) for { e0 := e fact *= n n++ e += 1.0 / float64(fact) if math.Abs(e - e0) < epsilon { break } } fmt.Printf("e =%.15f\n", e) }
1,072Calculating the value of e
0go
beokh
local line = "
1,073Bulls and cows/Player
1lua
zmuty
void main() {
1,077Call a function
18dart
7b1r7
Reduce('+', c(2,30,400,5000)) 5432
1,061Catamorphism
13r
vgi27
class Catalan { public static void main(String[] args) { BigInteger N = 15; BigInteger k,n,num,den; BigInteger catalan; print(1); for(n=2;n<=N;n++) { num = 1; den = 1; for(k=2;k<=n;k++) { num = num*(n+k); den = den*k; catalan = num/den; } println(catalan); } } }
1,068Catalan numbers
7groovy
h1nj9
class BraceExpansion { static void main(String[] args) { for (String s: [ "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}" ]) { println() expand(s) } } 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 == ('{' as char)) ? ++depth: depth depth = (c == ('}' as char)) ? --depth: depth if (c == (',' as char) && depth == 1) { sb.setCharAt(i2, '\u0000' as char) } else if (c == ('}' as char) && depth == 0 && sb.indexOf("\u0000") != -1) { break outer } } } if (i1 == -1) { if (suf.length() > 0) { expandR(pre + s, suf, "") } else { 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
7groovy
4jh5f
package Foo; sub new { my $class = shift; my $self = { _bar => 'I am ostensibly private' }; return bless $self, $class; } sub get_bar { my $self = shift; return $self->{_bar}; } package main; my $foo = Foo->new(); print "$_\n" for $foo->get_bar(), $foo->{_bar};
1,076Break OO privacy
2perl
f69d7
int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = ; move(5,0); clrtoeol(); addstr(); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = ; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
1,082Bulls and cows
5c
cul9c
STX = ETX = def bwt(s) for c in s.split('') if c == STX or c == ETX then raise ArgumentError.new() end end ss = ( % [STX, s, ETX]).split('') table = [] for i in 0 .. ss.length - 1 table.append(ss.join) ss = ss.rotate(-1) end table = table.sort return table.map{ |e| e[-1] }.join end def ibwt(r) len = r.length table = [] * len for i in 0 .. len - 1 for j in 0 .. len - 1 table[j] = r[j] + table[j] end table = table.sort end for row in table if row[-1] == ETX then return row[1 .. -2] end end return end def makePrintable(s) s = s.gsub(STX, ) return s.gsub(ETX, ) end def main tests = [ , , , , , ] for test in tests print makePrintable(test), print begin t = bwt(test) print makePrintable(t), r = ibwt(t) print , r, rescue ArgumentError => e print e.message, print end end end main()
1,071Burrows–Wheeler transform
14ruby
d3vns
caesar_cipher() { local -a _ABC=( "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" ) local -a _abc=( "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" ) local _out if (( $ echo "Usage: ${FUNCNAME[0]} -e|-d rotation (1-25) argument[(s)...]" >&2 return 1 fi _func="${1}"; shift _rotval="${1}"; shift while [[ -n "${1}" ]]; do for (( i = 0; i < ${ for (( x = 0; x < ${ case "${_func}" in "-e") [[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x + _rotval )% 26 ))]}" && break [[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x + _rotval )% 26 ))]}" && break;; "-d") [[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x - _rotval )% 26 ))]}" && break [[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x - _rotval )% 26 ))]}" && break;; esac (( x == ${ done done _out+=" " shift done echo "${_out[*]}" }
1,083Caesar cipher
4bash
9v9ms
def = 1.0e-15 def = 1/ def generateAddends = { def addends = [] def n = 0.0 def fact = 1.0 while (true) { fact *= (n < 2 ? 1.0: n) as double addends << 1.0/fact if (fact > ) break
1,072Calculating the value of e
7groovy
rkxgh
eApprox :: Int -> Double eApprox n = (sum . take n) $ (1 /) <$> scanl (*) 1 [1 ..] main :: IO () main = print $ eApprox 20
1,072Calculating the value of e
8haskell
d32n4
$PROGRAM = '\' MY @START_DOW = (3, 6, 6, 2, 4, 0, 2, 5, 1, 3, 6, 1); MY @DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); MY @MONTHS; FOREACH MY $M (0 .. 11) { FOREACH MY $R (0 .. 5) { $MONTHS[$M][$R] = JOIN " ", MAP { $_ < 1 || $_ > $DAYS[$M]? " ": SPRINTF "%2D", $_ } MAP { $_ - $START_DOW[$M] + 1 } $R * 7 .. $R * 7 + 6; } } SUB P { WARN $_[0], "\\N" } P UC " [INSERT SNOOPY HERE]"; P " 1969"; P ""; FOREACH (UC(" JANUARY FEBRUARY MARCH APRIL MAY JUNE"), UC(" JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER")) { P $_; MY @MS = SPLICE @MONTHS, 0, 6; P JOIN " ", ((UC "SU MO TU WE TH FR SA") X 6); P JOIN " ", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5; } \''; $E = '%' | '@'; $C = ' $H = '(' | '@'; $O = '/' | '@'; $T = '4' | '@'; $R = '2' | '@'; $A = '!' | '@'; $Z = ':' | '@'; $P = '0' | '@'; $L = ',' | '@'; `${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${L}`;
1,074Calendar - for "REAL" programmers
2perl
d3cnw
import qualified Text.Parsec as P showExpansion :: String -> String showExpansion = (<>) . (<> "\n parser :: P.Parsec String u [String] parser = expansion P.anyChar expansion :: P.Parsec String u Char -> P.Parsec String u [String] expansion = fmap expand . P.many . ((P.try alts P.<|> P.try alt1 P.<|> escape) P.<|>) . fmap (pure . pure) expand :: [[String]] -> [String] expand = foldr ((<*>) . fmap (<>)) [[]] alts :: P.Parsec String u [String] alts = concat <$> P.between (P.char '{') (P.char '}') (alt `sepBy2` P.char ',') alt :: P.Parsec String u [String] alt = expansion (P.noneOf ",}") alt1 :: P.Parsec String u [String] alt1 = (\x -> ['{': (x <> "}")]) <$> P.between (P.char '{') (P.char '}') (P.many $ P.noneOf ",{}") sepBy2 :: P.Parsec String u a -> P.Parsec String u b -> P.Parsec String u [a] p `sepBy2` sep = (:) <$> p <*> P.many1 (sep >> p) escape :: P.Parsec String u [String] escape = pure <$> sequence [P.char '\\', P.anyChar] main :: IO () main = mapM_ (putStrLn . showExpansion) [ "~/{Downloads,Pictures}/*.{jpg,gif,png}" , "It{{em,alic}iz,erat}e{d,}, please." , "{,{,gotta have{ ,\\, again\\, }}more }cowbell!" , "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}" ]
1,078Brace expansion
8haskell
itzor
<?php class SimpleClass { private $answer = world\nforever:)^SimpleClass::__set_state\(\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
1,076Break OO privacy
12php
h1wjf
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File , line 1, in <module> mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
1,076Break OO privacy
3python
tycfw
use core::cmp::Ordering; const STX: char = '\u{0002}'; const ETX: char = '\u{0003}';
1,071Burrows–Wheeler transform
15rust
f6ud6
import scala.collection.mutable.ArrayBuffer object BWT { val STX = '\u0002' val ETX = '\u0003' def bwt(s: String): String = { if (s.contains(STX) || s.contains(ETX)) { throw new RuntimeException("String can't contain STX or ETX") } var ss = STX + s + ETX var table = new ArrayBuffer[String]() (0 until ss.length).foreach(_ => { table += ss ss = ss.substring(1) + ss.charAt(0) }) table.sorted.map(a => a.last).mkString } def ibwt(r: String): String = { var table = Array.fill(r.length)("") (0 until r.length).foreach(_ => { (0 until r.length).foreach(i => { table(i) = r.charAt(i) + table(i) }) table = table.sorted }) table.indices.foreach(i => { val row = table(i) if (row.last == ETX) { return row.substring(1, row.length - 1) } }) "" } def makePrintable(s: String): String = { s.replace(STX, '^').replace(ETX, '|') } def main(args: Array[String]): Unit = { val tests = Array("banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" ) tests.foreach(test => { println(makePrintable(test)) print(" --> ") try { val t = bwt(test) println(makePrintable(t)) val r = ibwt(t) printf(" -->%s\n", r) } catch { case e: Exception => printf("ERROR:%s\n", e.getMessage) } println() }) } }
1,071Burrows–Wheeler transform
16scala
39gzy
use Inline C => q{ char *copy; char * c_dup(char *orig) { return copy = strdup(orig); } void c_free() { free(copy); } }; print c_dup('Hello'), "\n"; c_free();
1,070Call a foreign-language function
2perl
7b0rh