code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
function a(i) print "Function a(i) called." return i end function b(i) print "Function b(i) called." return i end i = true x = a(i) and b(i); print "" y = a(i) or b(i); print "" i = false x = a(i) and b(i); print "" y = a(i) or b(i)
284Short-circuit evaluation
1lua
jcv71
import Data.Char (ord) import Crypto.Hash.SHA256 (hash) import Data.ByteString (unpack, pack) import Text.Printf (printf) main = putStrLn $ concatMap (printf "%02x") $ unpack $ hash $ pack $ map (fromIntegral.ord) "Rosetta code"
290SHA-256
8haskell
60x3k
int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, next = 1; printf(, MAX); for (i = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { printf(, i); next++; } } printf(); return 0; }
293Sequence: smallest number greater than previous term with exactly n divisors
5c
60a32
var str = 'Rosetta code'; puts(Util.hash(str, {type:'sha1'}));
289SHA-1
9java
rm6g0
require 'prime' prime_array, sppair2, sppair3, sppair4, sppair5 = Array.new(5) {Array.new()} unsexy, i, start = [2], 0, Time.now Prime.each(1_000_100) {|prime| prime_array.push prime} while prime_array[i] < 1_000_035 i+=1 unsexy.push(i) if prime_array[(i+1)..(i+2)].include?(prime_array[i]+6) == false && prime_array[(i-2)..(i-1)].include?(prime_array[i]-6) == false && prime_array[i]+6 < 1_000_035 prime_array[(i+1)..(i+4)].include?(prime_array[i]+6) && prime_array[i]+6 < 1_000_035? sppair2.push(i): next prime_array[(i+2)..(i+5)].include?(prime_array[i]+12) && prime_array[i]+12 < 1_000_035? sppair3.push(i): next prime_array[(i+3)..(i+6)].include?(prime_array[i]+18) && prime_array[i]+18 < 1_000_035? sppair4.push(i): next prime_array[(i+4)..(i+7)].include?(prime_array[i]+24) && prime_array[i]+24 < 1_000_035? sppair5.push(i): next end puts sppair2.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6].join(), } puts sppair3.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12].join(), } puts sppair4.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18].join(), } puts sppair5.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18, prime_array[prime]+24].join(), } puts unsexy.last(10).each {|item| print prime_array[item], } print , Time.now - start,
286Sexy primes
14ruby
cnd9k
public static boolean inCarpet(long x, long y) { while (x!=0 && y!=0) { if (x % 3 == 1 && y % 3 == 1) return false; x /= 3; y /= 3; } return true; } public static void carpet(final int n) { final double power = Math.pow(3,n); for(long i = 0; i < power; i++) { for(long j = 0; j < power; j++) { System.out.print(inCarpet(i, j) ? "*" : " "); } System.out.println(); } }
283Sierpinski carpet
9java
hl5jm
int smallPrimes[LIMIT]; static void sieve() { int i = 2, j; int p = 5; smallPrimes[0] = 2; smallPrimes[1] = 3; while (i < LIMIT) { for (j = 0; j < i; j++) { if (smallPrimes[j] * smallPrimes[j] <= p) { if (p % smallPrimes[j] == 0) { p += 2; break; } } else { smallPrimes[i++] = p; p += 2; break; } } } } static bool is_prime(uint64_t n) { uint64_t i; for (i = 0; i < LIMIT; i++) { if (n % smallPrimes[i] == 0) { return n == smallPrimes[i]; } } i = smallPrimes[LIMIT - 1] + 2; for (; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } static uint64_t divisor_count(uint64_t n) { uint64_t count = 1; uint64_t d; while (n % 2 == 0) { n /= 2; count++; } for (d = 3; d * d <= n; d += 2) { uint64_t q = n / d; uint64_t r = n % d; uint64_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { return count *= 2; } return count; } static uint64_t OEISA073916(size_t n) { uint64_t count = 0; uint64_t result = 0; size_t i; if (is_prime(n)) { return (uint64_t)pow(smallPrimes[n - 1], n - 1); } for (i = 1; count < n; i++) { if (n % 2 == 1) { uint64_t root = (uint64_t)sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { size_t n; sieve(); for (n = 1; n <= LIMIT; n++) { if (n == 13) { printf(, n); } else { printf(, n, OEISA073916(n)); } } return 0; }
294Sequence: nth number with exactly n divisors
5c
ldqcy
typedef unsigned int bitset; int consolidate(bitset *x, int len) { int i, j; for (i = len - 2; i >= 0; i--) for (j = len - 1; j > i; j--) if (x[i] & x[j]) x[i] |= x[j], x[j] = x[--len]; return len; } void show_sets(bitset *x, int len) { bitset b; while(len--) { for (b = 'A'; b <= 'Z'; b++) if (x[len] & s(b)) printf(, b); putchar('\n'); } } int main(void) { bitset x[] = { s('A') | s('B'), s('C') | s('D'), s('B') | s('D'), s('F') | s('G') | s('H'), s('H') | s('I') | s('K') }; int len = sizeof(x) / sizeof(x[0]); puts(); show_sets(x, len); puts(); show_sets(x, consolidate(x, len)); return 0; }
295Set consolidation
5c
79drg
null
289SHA-1
11kotlin
vtd21
null
286Sexy primes
15rust
ldfcc
object SexyPrimes { def isPrime(n: Int): Boolean = ! ((2 until n-1) exists (n % _ == 0)) && n > 1 def getSexyPrimesPairs (primes : List[Int]) = { primes .map(n => if(primes.contains(n+6)) (n, n+6)) .filter(p => p != ()) .map{ case (a,b) => (a.toString.toInt, b.toString.toInt)} } def getSexyPrimesTriplets (primes : List[Int]) = { primes .map(n => if( primes.contains(n+6) && primes.contains(n+12)) (n, n+6, n+12) ) .filter(p => p != ()) .map{ case (a,b,c) => (a.toString.toInt, b.toString.toInt, c.toString.toInt)} } def getSexyPrimesQuadruplets (primes : List[Int]) = { primes .map(n => if( primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18)) (n, n+6, n+12, n+18) ) .filter(p => p != ()) .map{ case (a,b,c,d) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt)} } def getSexyPrimesQuintuplets (primes : List[Int]) = { primes .map(n => if ( primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18) && primes.contains(n + 24)) (n, n + 6, n + 12, n + 18, n + 24) ) .filter(p => p != ()) .map { case (a, b, c, d, e) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt, e.toString.toInt) } } def removeOutsideSexyPrimes( l : List[Int], limit : Int) : List[Int] = { l.filter(n => !isPrime(n+6) && n+6 < limit) } def main(args: Array[String]): Unit = { val limit = 1000035 val l = List.range(1,limit) val primes = l.filter( n => isPrime(n)) val sexyPairs = getSexyPrimesPairs(primes) println("Number of sexy pairs: " + sexyPairs.size) println("5 last sexy pairs: " + sexyPairs.takeRight(5)) val primes2 = sexyPairs.flatMap(t => List(t._1, t._2)).distinct.sorted val sexyTriplets = getSexyPrimesTriplets(primes2) println("Number of sexy triplets: " + sexyTriplets.size) println("5 last sexy triplets: " + sexyTriplets.takeRight(5)) val primes3 = sexyTriplets.flatMap(t => List(t._1, t._2, t._3)).distinct.sorted val sexyQuadruplets = getSexyPrimesQuadruplets(primes3) println("Number of sexy quadruplets: " + sexyQuadruplets.size) println("5 last sexy quadruplets: " + sexyQuadruplets.takeRight(5)) val primes4 = sexyQuadruplets.flatMap(t => List(t._1, t._2, t._3, t._4)).distinct.sorted val sexyQuintuplets = getSexyPrimesQuintuplets(primes4) println("Number of sexy quintuplets: " + sexyQuintuplets.size) println("The last sexy quintuplet: " + sexyQuintuplets.takeRight(10)) val sexyPrimes = primes2.toSet val unsexyPrimes = removeOutsideSexyPrimes( primes.toSet.diff((sexyPrimes)).toList.sorted, limit) println("Number of unsexy primes: " + unsexyPrimes.size) println("10 last unsexy primes: " + unsexyPrimes.takeRight(10)) } }
286Sexy primes
16scala
uz3v8
sub sierpinski { my ($n) = @_; my @down = '*'; my $space = ' '; foreach (1..$n) { @down = (map("$space$_$space", @down), map("$_ $_", @down)); $space = "$space$space"; } return @down; } print "$_\n" foreach sierpinski 4;
278Sierpinski triangle
2perl
7c7rh
<!DOCTYPE html PUBLIC "-
283Sierpinski carpet
10javascript
a4j10
from itertools import product, combinations from random import sample features = [ 'green purple red'.split(), 'one two three'.split(), 'oval diamond squiggle'.split(), 'open striped solid'.split() ] deck = list(product(list(range(3)), repeat=4)) dealt = 9 def printcard(card): print(' '.join('%8s'% f[i] for f,i in zip(features, card))) def getdeal(dealt=dealt): deal = sample(deck, dealt) return deal def getsets(deal): good_feature_count = set([1, 3]) sets = [ comb for comb in combinations(deal, 3) if all( [(len(set(feature)) in good_feature_count) for feature in zip(*comb)] ) ] return sets def printit(deal, sets): print('Dealt%i cards:'% len(deal)) for card in deal: printcard(card) print('\nFound%i sets:'% len(sets)) for s in sets: for card in s: printcard(card) print('') if __name__ == '__main__': while True: deal = getdeal() sets = getsets(deal) if len(sets) == dealt / 2: break printit(deal, sets)
291Set puzzle
3python
46f5k
int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; printf(, MAX); for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) printf(, seq[i]); printf(); return 0; }
296Sequence: smallest number with exactly n divisors
5c
fw7d3
const crypto = require('crypto'); const msg = 'Rosetta code'; const hash = crypto.createHash('sha256').update(msg).digest('hex'); console.log(hash);
290SHA-256
9java
nabih
const crypto = require('crypto'); const msg = 'Rosetta code'; const hash = crypto.createHash('sha256').update(msg).digest('hex'); console.log(hash);
290SHA-256
10javascript
3swz0
(defn consolidate-linked-sets [sets] (apply clojure.set/union sets)) (defn linked? [s1 s2] (not (empty? (clojure.set/intersection s1 s2)))) (defn consolidate [& sets] (loop [seeds sets sets sets] (if (empty? seeds) sets (let [s0 (first seeds) linked (filter #(linked? s0 %) sets) remove-used (fn [sets used] (remove #(contains? (set used) %) sets))] (recur (remove-used (rest seeds) linked) (conj (remove-used sets linked) (consolidate-linked-sets linked)))))))
295Set consolidation
6clojure
pu6bd
sub dice5 { 1+int rand(5) } sub dice7 { while(1) { my $d7 = (5*dice5()+dice5()-6) % 8; return $d7 if $d7; } } my %count7; my $n = 1000000; $count7{dice7()}++ for 1..$n; printf "%s:%5.2f%%\n", $_, 100*($count7{$_}/$n*7-1) for sort keys %count7;
292Seven-sided dice from five-sided dice
2perl
moxyz
package main import "fmt" func main() { for i := 0; i < 16; i++ { for j := 32 + i; j < 128; j += 16 { k := string(j) switch j { case 32: k = "Spc" case 127: k = "Del" } fmt.Printf("%3d:%-3s ", j, k) } fmt.Println() } }
288Show ASCII table
0go
60s3p
int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); gmp_printf(, n); i++; continue; } mpz_sub_ui(p, p, 2); if (mpz_probab_prime_p(p, 25)) { mpz_add_ui(p, p, 1); gmp_printf(, n); i++; continue; } mpz_add_ui(p, p, 1); } mpz_clear(s); mpz_clear(p); }
297Sequence of primorial primes
5c
0k2st
null
290SHA-256
11kotlin
shrq7
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 fmt.Println("The first", max, "terms of the sequence are:") for i, next := 1, 1; next <= max; i++ { if next == countDivisors(i) { fmt.Printf("%d ", i) next++ } } fmt.Println() }
293Sequence: smallest number greater than previous term with exactly n divisors
0go
pumbg
#!/usr/bin/lua local sha1 = require "sha1" for i, str in ipairs{"Rosetta code", "Rosetta Code"} do print(string.format("SHA-1(%q) =%s", str, sha1(str))) end
289SHA-1
1lua
uzfvl
class ShowAsciiTable { static void main(String[] args) { for (int i = 32; i <= 127; i++) { if (i == 32 || i == 127) { String s = i == 32 ? "Spc": "Del" printf("%3d:%s ", i, s) } else { printf("%3d:%c ", i, i) } if ((i - 1) % 6 == 0) { println() } } } }
288Show ASCII table
7groovy
dean3
<?php function sierpinskiTriangle($order) { $char = ' $n = 1 << $order; $line = array(); for ($i = 0 ; $i <= 2 * $n ; $i++) { $line[$i] = ' '; } $line[$n] = $char; for ($i = 0 ; $i < $n ; $i++) { echo implode('', $line), PHP_EOL; $u = $char; for ($j = $n - $i ; $j < $n + $i + 1 ; $j++) { $t = ($line[$j - 1] == $line[$j + 1]? ' ' : $char); $line[$j - 1] = $u; $u = $t; } $line[$n + $i] = $t; $line[$n + $i + 1] = $char; } } sierpinskiTriangle(4);
278Sierpinski triangle
12php
fxfdh
null
283Sierpinski carpet
11kotlin
46c57
COLORS = %i(red green purple) SYMBOLS = %i(oval squiggle diamond) NUMBERS = %i(one two three) SHADINGS = %i(solid open striped) DECK = COLORS.product(SYMBOLS, NUMBERS, SHADINGS) def get_all_sets(hand) hand.combination(3).select do |candidate| grouped_features = candidate.flatten.group_by{|f| f} grouped_features.values.none?{|v| v.size == 2} end end def get_puzzle_and_answer(hand_size, num_sets_goal) begin hand = DECK.sample(hand_size) sets = get_all_sets(hand) end until sets.size == num_sets_goal [hand, sets] end def print_cards(cards) puts cards.map{|card| * 4 % card} puts end def set_puzzle(deal, goal=deal/2) puzzle, sets = get_puzzle_and_answer(deal, goal) puts print_cards(puzzle) puts sets.each{|set| print_cards(set)} end set_puzzle(9) set_puzzle(12)
291Set puzzle
14ruby
rmzgs
struct RealSet { bool(*contains)(struct RealSet*, struct RealSet*, double); struct RealSet *left; struct RealSet *right; double low, high; }; typedef enum { CLOSED, LEFT_OPEN, RIGHT_OPEN, BOTH_OPEN, } RangeType; double length(struct RealSet *self) { const double interval = 0.00001; double p = self->low; int count = 0; if (isinf(self->low) || isinf(self->high)) return -1.0; if (self->high <= self->low) return 0.0; do { if (self->contains(self, NULL, p)) count++; p += interval; } while (p < self->high); return count * interval; } bool empty(struct RealSet *self) { if (self->low == self->high) { return !self->contains(self, NULL, self->low); } return length(self) == 0.0; } static bool contains_closed(struct RealSet *self, struct RealSet *_, double d) { return self->low <= d && d <= self->high; } static bool contains_left_open(struct RealSet *self, struct RealSet *_, double d) { return self->low < d && d <= self->high; } static bool contains_right_open(struct RealSet *self, struct RealSet *_, double d) { return self->low <= d && d < self->high; } static bool contains_both_open(struct RealSet *self, struct RealSet *_, double d) { return self->low < d && d < self->high; } static bool contains_intersect(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) && self->right->contains(self->right, NULL, d); } static bool contains_union(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) || self->right->contains(self->right, NULL, d); } static bool contains_subtract(struct RealSet *self, struct RealSet *_, double d) { return self->left->contains(self->left, NULL, d) && !self->right->contains(self->right, NULL, d); } struct RealSet* makeSet(double low, double high, RangeType type) { bool(*contains)(struct RealSet*, struct RealSet*, double); struct RealSet *rs; switch (type) { case CLOSED: contains = contains_closed; break; case LEFT_OPEN: contains = contains_left_open; break; case RIGHT_OPEN: contains = contains_right_open; break; case BOTH_OPEN: contains = contains_both_open; break; default: return NULL; } rs = malloc(sizeof(struct RealSet)); rs->contains = contains; rs->left = NULL; rs->right = NULL; rs->low = low; rs->high = high; return rs; } struct RealSet* makeIntersect(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_intersect; rs->left = left; rs->right = right; rs->low = fmin(left->low, right->low); rs->high = fmin(left->high, right->high); return rs; } struct RealSet* makeUnion(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_union; rs->left = left; rs->right = right; rs->low = fmin(left->low, right->low); rs->high = fmin(left->high, right->high); return rs; } struct RealSet* makeSubtract(struct RealSet *left, struct RealSet *right) { struct RealSet *rs = malloc(sizeof(struct RealSet)); rs->contains = contains_subtract; rs->left = left; rs->right = right; rs->low = left->low; rs->high = left->high; return rs; } int main() { struct RealSet *a = makeSet(0.0, 1.0, LEFT_OPEN); struct RealSet *b = makeSet(0.0, 2.0, RIGHT_OPEN); struct RealSet *c = makeSet(1.0, 2.0, LEFT_OPEN); struct RealSet *d = makeSet(0.0, 3.0, RIGHT_OPEN); struct RealSet *e = makeSet(0.0, 1.0, BOTH_OPEN); struct RealSet *f = makeSet(0.0, 1.0, CLOSED); struct RealSet *g = makeSet(0.0, 0.0, CLOSED); int i; for (i = 0; i < 3; ++i) { struct RealSet *t; t = makeUnion(a, b); printf(, i, t->contains(t, NULL, i)); free(t); t = makeIntersect(b, c); printf(, i, t->contains(t, NULL, i)); free(t); t = makeSubtract(d, e); printf(, i, t->contains(t, NULL, i)); free(t); t = makeSubtract(d, f); printf(, i, t->contains(t, NULL, i)); free(t); printf(); } printf(, empty(g)); free(a); free(b); free(c); free(d); free(e); free(f); free(g); return 0; }
298Set of real numbers
5c
de4nv
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes } func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count } func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d:%d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d:%d\n", i, j) break } } } } } }
294Sequence: nth number with exactly n divisors
0go
x72wf
#!/usr/bin/lua require "sha2" print(sha2.sha256hex("Rosetta code"))
290SHA-256
1lua
0k7sd
import Text.Printf (printf) sequence_A069654 :: [(Int,Int)] sequence_A069654 = go 1 $ (,) <*> countDivisors <$> [1..] where go t ((n,c):xs) | c == t = (t,n):go (succ t) xs | otherwise = go t xs countDivisors n = foldr f 0 [1..floor $ sqrt $ realToFrac n] where f x r | n `mod` x == 0 = if n `div` x == x then r+1 else r+2 | otherwise = r main :: IO () main = mapM_ (uncurry $ printf "a(%2d)=%5d\n") $ take 15 sequence_A069654
293Sequence: smallest number greater than previous term with exactly n divisors
8haskell
fwkd1
from random import randint def dice5(): return randint(1, 5) def dice7(): r = dice5() + dice5() * 5 - 6 return (r% 7) + 1 if r < 21 else dice7()
292Seven-sided dice from five-sided dice
3python
9iqmf
dice5 <- function(n=1) sample(5, n, replace=TRUE)
292Seven-sided dice from five-sided dice
13r
3sazt
import Data.Char (chr) import Data.List (transpose) import Data.List.Split (chunksOf) import Text.Printf (printf) asciiTable :: String asciiTable = unlines $ (printf "%-12s" =<<) <$> transpose (chunksOf 16 $ asciiEntry <$> [32 .. 127]) asciiEntry :: Int -> String asciiEntry n | null k = k | otherwise = concat [printf "%3d" n, ": ", k] where k = asciiName n asciiName :: Int -> String asciiName n | 32 > n = [] | 127 < n = [] | 32 == n = "Spc" | 127 == n = "Del" | otherwise = [chr n] main :: IO () main = putStrLn asciiTable
288Show ASCII table
8haskell
jc97g
local function carpet(n, f) print("n = " .. n) local function S(x, y) if x==0 or y==0 then return true elseif x%3==1 and y%3==1 then return false end return S(x//3, y//3) end for y = 0, 3^n-1 do for x = 0, 3^n-1 do io.write(f(S(x, y))) end print() end print() end for n = 0, 4 do carpet(n, function(b) return b and " " or " " end) end
283Sierpinski carpet
1lua
gyl4j
use itertools::Itertools; use rand::Rng; const DECK_SIZE: usize = 81; const NUM_ATTRIBUTES: usize = 4; const ATTRIBUTES: [&[&str]; NUM_ATTRIBUTES] = [ &["red", "green", "purple"], &["one", "two", "three"], &["oval", "squiggle", "diamond"], &["solid", "open", "striped"], ]; fn get_random_card_indexes(num_of_cards: usize) -> Vec<usize> { let mut selected_cards: Vec<usize> = Vec::with_capacity(num_of_cards); let mut rng = rand::thread_rng(); loop { let idx = rng.gen_range(0..DECK_SIZE); if!selected_cards.contains(&idx) { selected_cards.push(idx); } if selected_cards.len() == num_of_cards { break; } } selected_cards } fn run_game(num_of_cards: usize, minimum_number_of_sets: usize) { println!( "\nGAME: # of cards: {} # of sets: {}", num_of_cards, minimum_number_of_sets );
291Set puzzle
15rust
793rc
(ns example (:gen-class)) (def primes (iterate #(.nextProbablePrime %) (biginteger 2))) (defn primorial-prime? [v] " Test if value is a primorial prime " (let [a (biginteger (inc v)) b (biginteger (dec v))] (or (.isProbablePrime a 16) (.isProbablePrime b 16)))) (println (take 20 (keep-indexed #(if (primorial-prime? %2) (inc %1)) (reductions *' primes))))
297Sequence of primorial primes
6clojure
degnb
import Control.Monad (guard) import Math.NumberTheory.ArithmeticFunctions (divisorCount) import Math.NumberTheory.Primes (Prime, unPrime) import Math.NumberTheory.Primes.Testing (isPrime) calc :: Integer -> [(Integer, Integer)] calc n = do x <- [1..] guard (even n || odd n && f x == x) [(x, divisorCount x)] where f n = floor (sqrt $ realToFrac n) ^ 2 havingNthDivisors :: Integer -> [(Integer, Integer)] havingNthDivisors n = filter ((==n) . snd) $ calc n nths :: [(Integer, Integer)] nths = do n <- [1..35] :: [Integer] if isPrime n then pure (n, nthPrime (fromIntegral n) ^ pred n) else pure (n, f n) where f n = fst (havingNthDivisors n !! pred (fromIntegral n)) nthPrime n = unPrime (toEnum n :: Prime Integer) main :: IO () main = mapM_ print nths
294Sequence: nth number with exactly n divisors
8haskell
y8a66
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
296Sequence: smallest number with exactly n divisors
0go
jcd7d
public class AntiPrimesPlus { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; System.out.printf("The first%d terms of the sequence are:\n", max); for (int i = 1, next = 1; next <= max; ++i) { if (next == count_divisors(i)) { System.out.printf("%d ", i); next++; } } System.out.println(); } }
293Sequence: smallest number greater than previous term with exactly n divisors
9java
0k4se
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class SequenceNthNumberWithExactlyNDivisors { public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) =%s%n", n, OEISA073916(n)); } } private static List<Integer> smallPrimes = new ArrayList<>(); private static void smallPrimes(int numPrimes) { smallPrimes.add(2); for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) { if ( isPrime(n) ) { smallPrimes.add(n); count++; } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long d = 3 ; d*d <= test ; d += 2 ) { if ( test % d == 0 ) { return false; } } return true; } private static int getDivisorCount(long n) { int count = 1; while ( n % 2 == 0 ) { n /= 2; count += 1; } for ( long d = 3 ; d*d <= n ; d += 2 ) { long q = n / d; long r = n % d; int dc = 0; while ( r == 0 ) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if ( n != 1 ) { count *= 2; } return count; } private static BigInteger OEISA073916(int n) { if ( isPrime(n) ) { return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1); } int count = 0; int result = 0; for ( int i = 1 ; count < n ; i++ ) { if ( n % 2 == 1 ) {
294Sequence: nth number with exactly n divisors
9java
dejn9
import Data.List (find, group, sort) import Data.Maybe (mapMaybe) import Data.Numbers.Primes (primeFactors) a005179 :: [Int] a005179 = mapMaybe ( \n -> find ((n ==) . succ . length . properDivisors) [1 ..] ) [1 ..] main :: IO () main = print $ take 15 a005179 properDivisors :: Int -> [Int] properDivisors = init . sort . foldr (flip ((<*>) . fmap (*)) . scanl (*) 1) [1] . group . primeFactors
296Sequence: smallest number with exactly n divisors
8haskell
op58p
null
293Sequence: smallest number greater than previous term with exactly n divisors
11kotlin
egla4
(ns rosettacode.real-set) (defn >=|<= [lo hi] #(<= lo % hi)) (defn >|< [lo hi] #(< lo % hi)) (defn >=|< [lo hi] #(and (<= lo %) (< % hi))) (defn >|<= [lo hi] #(and (< lo %) (<= % hi))) (def some-fn) (def every-pred) (defn ([s1] s1) ([s1 s2] #(and (s1 %) (not (s2 %)))) ([s1 s2 s3] #(and (s1 %) (not (s2 %)) (not (s3 %)))) ([s1 s2 s3 & ss] (fn [x] (every? #(not (% x)) (list* s1 s2 s3 ss))))) (clojure.pprint/pprint (map #(map % [0 1 2]) [( (>|<= 0 1) (>=|< 0 2)) ( (>=|< 0 2) (>|<= 1 2)) ( (>=|< 0 3) (>|< 0 1)) ( (>=|< 0 3) (>=|<= 0 1))]) (def (constantly false)) (def R (constantly true)) (def Z integer?) (def Q ratio?) (def I #( R Z Q)) (def N #( Z neg?))
298Set of real numbers
6clojure
60h3q
null
294Sequence: nth number with exactly n divisors
11kotlin
0k5sf
(() => { 'use strict';
296Sequence: smallest number with exactly n divisors
10javascript
8bu0l
require './distcheck.rb' def d5 1 + rand(5) end def d7 loop do d55 = 5*d5 + d5 - 6 return (d55 % 7 + 1) if d55 < 21 end end distcheck(1_000_000) {d5} distcheck(1_000_000) {d7}
292Seven-sided dice from five-sided dice
14ruby
ld0cl
import scala.util.Random object SevenSidedDice extends App { private val rnd = new Random private def seven = { var v = 21 def five = 1 + rnd.nextInt(5) while (v > 20) v = five + five * 5 - 6 1 + v % 7 } println("Random number from 1 to 7: " + seven) }
292Seven-sided dice from five-sided dice
16scala
53nut
public class ShowAsciiTable { public static void main(String[] args) { for ( int i = 32 ; i <= 127 ; i++ ) { if ( i == 32 || i == 127 ) { String s = i == 32 ? "Spc" : "Del"; System.out.printf("%3d:%s ", i, s); } else { System.out.printf("%3d:%c ", i, i); } if ( (i-1) % 6 == 0 ) { System.out.println(); } } } }
288Show ASCII table
9java
uztvv
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first%d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
296Sequence: smallest number with exactly n divisors
9java
wr9ej
use strict; use warnings; use ntheory 'divisors'; print "First 15 terms of OEIS: A069654\n"; my $m = 0; for my $n (1..15) { my $l = $m; while (++$l) { print("$l "), $m = $l, last if $n == divisors($l); } }
293Sequence: smallest number greater than previous term with exactly n divisors
2perl
cnq9a
(() => { "use strict";
288Show ASCII table
10javascript
79mrd
(import '[java.util Date]) (import '[clojure.lang Reflector]) (def date1 (Date.)) (def date2 (Date.)) (def method "equals") (Reflector/invokeMethod date1 method (object-array [date2])) (eval `(. date1 ~(symbol method) date2))
299Send an unknown method call
6clojure
0kcsj
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) pm := big.NewInt(1)
297Sequence of primorial primes
0go
uzqvt
use strict; use warnings; use bigint; use ntheory <nth_prime is_prime divisors>; my $limit = 20; print "First $limit terms of OEIS:A073916\n"; for my $n (1..$limit) { if ($n > 4 and is_prime($n)) { print nth_prime($n)**($n-1) . ' '; } else { my $i = my $x = 0; while (1) { my $nn = $n%2 ? ++$x**2 : ++$x; next unless $n == divisors($nn) and ++$i == $n; print "$nn " and last; } } }
294Sequence: nth number with exactly n divisors
2perl
53ou2
package main import "fmt" type set map[string]bool var testCase = []set{ set{"H": true, "I": true, "K": true}, set{"A": true, "B": true}, set{"C": true, "D": true}, set{"D": true, "B": true}, set{"F": true, "G": true, "H": true}, } func main() { fmt.Println(consolidate(testCase)) } func consolidate(sets []set) []set { setlist := []set{} for _, s := range sets { if s != nil && len(s) > 0 { setlist = append(setlist, s) } } for i, s1 := range setlist { if len(s1) > 0 { for _, s2 := range setlist[i+1:] { if s1.disjoint(s2) { continue } for e := range s1 { s2[e] = true delete(s1, e) } s1 = s2 } } } r := []set{} for _, s := range setlist { if len(s) > 0 { r = append(r, s) } } return r } func (s1 set) disjoint(s2 set) bool { for e := range s2 { if s1[e] { return false } } return true }
295Set consolidation
0go
de7ne
static const char *payload_text[] = { , to , from , cc , , , , , , , , , , NULL }; struct upload_status { int lines_read; }; static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) { struct upload_status *upload_ctx = (struct upload_status *)userp; const char *data; if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { return 0; } data = payload_text[upload_ctx->lines_read]; if(data) { size_t len = strlen(data); memcpy(ptr, data, len); upload_ctx->lines_read++; return len; } return 0; } int main(void) { CURL *curl; CURLcode res = CURLE_OK; struct curl_slist *recipients = NULL; struct upload_status upload_ctx; upload_ctx.lines_read = 0; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_USERNAME, ); curl_easy_setopt(curl, CURLOPT_PASSWORD, ); curl_easy_setopt(curl, CURLOPT_URL, ); curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); curl_easy_setopt(curl, CURLOPT_CAINFO, ); curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from); recipients = curl_slist_append(recipients, to); recipients = curl_slist_append(recipients, cc); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, ,curl_easy_strerror(res)); curl_slist_free_all(recipients); curl_easy_cleanup(curl); } return (int)res; }
300Send email
5c
x76wu
package main import ( "fmt" "reflect" ) type example struct{}
299Send an unknown method call
0go
9ibmt
import Data.List (scanl1, elemIndices, nub) primes :: [Integer] primes = 2: filter isPrime [3,5 ..] isPrime :: Integer -> Bool isPrime = isPrime_ primes where isPrime_ :: [Integer] -> Integer -> Bool isPrime_ (p:ps) n | p * p > n = True | n `mod` p == 0 = False | otherwise = isPrime_ ps n primorials :: [Integer] primorials = 1: scanl1 (*) primes primorialsPlusMinusOne :: [Integer] primorialsPlusMinusOne = concatMap (((:) . pred) <*> (return . succ)) primorials sequenceOfPrimorialPrimes :: [Int] sequenceOfPrimorialPrimes = (tail . nub) $ (`div` 2) <$> elemIndices True bools where bools = isPrime <$> primorialsPlusMinusOne main :: IO () main = mapM_ print $ take 10 sequenceOfPrimorialPrimes
297Sequence of primorial primes
8haskell
wrmed
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n% ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
294Sequence: nth number with exactly n divisors
3python
46i5k
import Data.List (intersperse, intercalate) import qualified Data.Set as S consolidate :: Ord a => [S.Set a] -> [S.Set a] consolidate = foldr comb [] where comb s_ [] = [s_] comb s_ (s:ss) | S.null (s `S.intersection` s_) = s: comb s_ ss | otherwise = comb (s `S.union` s_) ss main :: IO () main = (putStrLn . unlines) ((intercalate ", and " . fmap showSet . consolidate) . fmap S.fromList <$> [ ["ab", "cd"] , ["ab", "bd"] , ["ab", "cd", "db"] , ["hik", "ab", "cd", "db", "fgh"] ]) showSet :: S.Set Char -> String showSet = flip intercalate ["{", "}"] . intersperse ',' . S.elems
295Set consolidation
8haskell
538ug
null
296Sequence: smallest number with exactly n divisors
11kotlin
bvzkb
sub a { print 'A'; return $_[0] } sub b { print 'B'; return $_[0] } sub test { for my $op ('&&','||') { for (qw(1,1 1,0 0,1 0,0)) { my ($x,$y) = /(.),(.)/; print my $str = "a($x) $op b($y)", ': '; eval $str; print "\n"; } } } test();
284Short-circuit evaluation
2perl
fwsd7
class Example { def foo(value) { "Invoked with '$value'" } } def example = new Example() def method = "foo" def arg = "test value" assert "Invoked with 'test value'" == example."$method"(arg)
299Send an unknown method call
7groovy
zqrt5
import java.math.BigInteger; public class PrimorialPrimes { final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = primorial(i); if (b.add(BigInteger.ONE).isProbablePrime(1) || b.subtract(BigInteger.ONE).isProbablePrime(1)) { System.out.printf("%d ", i); count++; } } } static BigInteger primorial(int n) { if (n == 0) return BigInteger.ONE; BigInteger result = BigInteger.ONE; for (int i = 0; i < sieveLimit && n > 0; i++) { if (notPrime[i]) continue; result = result.multiply(BigInteger.valueOf(i)); n--; } return result; } public static boolean[] sieve(int limit) { boolean[] composite = new boolean[limit]; composite[0] = composite[1] = true; int max = (int) Math.sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } }
297Sequence of primorial primes
9java
k2fhm
import java.util.*; public class SetConsolidation { public static void main(String[] args) { List<Set<Character>> h1 = hashSetList("AB", "CD"); System.out.println(consolidate(h1)); List<Set<Character>> h2 = hashSetList("AB", "BD"); System.out.println(consolidateR(h2)); List<Set<Character>> h3 = hashSetList("AB", "CD", "DB"); System.out.println(consolidate(h3)); List<Set<Character>> h4 = hashSetList("HIK", "AB", "CD", "DB", "FGH"); System.out.println(consolidateR(h4)); }
295Set consolidation
9java
9iemu
use strict ; use warnings ; use Digest::SHA qw( sha256_hex ) ; my $digest = sha256_hex my $phrase = "Rosetta code" ; print "SHA-256('$phrase'): $digest\n" ;
290SHA-256
2perl
uzdvr
use Digest::SHA qw(sha1_hex); print sha1_hex('Rosetta Code'), "\n";
289SHA-1
2perl
0kjs4
(require '[postal.core:refer [send-message]]) (send-message {:host "smtp.gmail.com" :ssl true :user your_username :pass your_password} {:from "[email protected]" :to ["[email protected]"] :cc ["[email protected]" "[email protected]"] :subject "Yo" :body "Testing."})
300Send email
6clojure
opl8j
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(name, int.class); Object result = meth.invoke(example, 5);
299Send an unknown method call
9java
gys4m
example = new Object; example.foo = function(x) { return 42 + x; }; name = "foo"; example[name](5) # => 47
299Send an unknown method call
10javascript
k2nhq
null
297Sequence of primorial primes
11kotlin
gy84d
(() => { 'use strict';
295Set consolidation
10javascript
uz0vb
<?php echo hash('sha256', 'Rosetta code');
290SHA-256
12php
8bj0m
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n% ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
293Sequence: smallest number greater than previous term with exactly n divisors
3python
ldscv
<?php $string = 'Rosetta Code'; echo sha1( $string ), ; ?>
289SHA-1
12php
53tus
null
288Show ASCII table
11kotlin
9iomh
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = string(ss) s = strings.Replace(s, "b", "E", 1) s = strings.Replace(s, "r", "F", 2) s = strings.Replace(s, "F", "r", 1) fmt.Println(s) }
301Selectively replace multiple instances of a character within a string
0go
15dp5
package main import "fmt" type Set func(float64) bool func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } func open(a, b float64) Set { return func(x float64) bool { return a < x && x < b } } func closed(a, b float64) Set { return func(x float64) bool { return a <= x && x <= b } } func opCl(a, b float64) Set { return func(x float64) bool { return a < x && x <= b } } func clOp(a, b float64) Set { return func(x float64) bool { return a <= x && x < b } } func main() { s := make([]Set, 4) s[0] = Union(opCl(0, 1), clOp(0, 2))
298Set of real numbers
0go
79or2
null
299Send an unknown method call
11kotlin
2fali
local example = { } function example:foo (x) return 42 + x end local name = "foo" example[name](example, 5)
299Send an unknown method call
1lua
vte2x
def isPrime(n) return false if n < 2 return n == 2 if n % 2 == 0 return n == 3 if n % 3 == 0 k = 5 while k * k <= n return false if n % k == 0 k = k + 2 end return true end def getSmallPrimes(numPrimes) smallPrimes = [2] count = 0 n = 3 while count < numPrimes if isPrime(n) then smallPrimes << n count = count + 1 end n = n + 2 end return smallPrimes end def getDivisorCount(n) count = 1 while n% 2 == 0 n = (n / 2).floor count = count + 1 end d = 3 while d * d <= n q = (n / d).floor r = n% d dc = 0 while r == 0 dc = dc + count n = q q = (n / d).floor r = n% d end count = count + dc d = d + 2 end if n!= 1 then count = 2 * count end return count end MAX = 15 @smallPrimes = getSmallPrimes(MAX) def OEISA073916(n) if isPrime(n) then return @smallPrimes[n - 1] ** (n - 1) end count = 0 result = 0 i = 1 while count < n if n% 2 == 1 then root = Math.sqrt(i) if root * root!= i then i = i + 1 next end end if getDivisorCount(i) == n then count = count + 1 result = i end i = i + 1 end return result end n = 1 while n <= MAX print , n, , OEISA073916(n), n = n + 1 end
294Sequence: nth number with exactly n divisors
14ruby
rmdgs
divisorCount <- function(n) length(Filter(function(x) n %% x == 0, seq_len(n %/% 2))) + 1 A06954 <- function(terms) { out <- 1 while((resultCount <- length(out)) != terms) { n <- resultCount + 1 out[n] <- out[resultCount] while(divisorCount(out[n]) != n) out[n] <- out[n] + 1 } out } print(A06954(15))
293Sequence: smallest number greater than previous term with exactly n divisors
13r
y8e6h
use strict; use warnings; use feature 'say'; sub transmogrify { my($str, %sub) = @_; for my $l (keys %sub) { $str =~ s/$l/$_/ for split '', $sub{$l}; $str =~ s/_/$l/g; } $str } my $word = 'abracadabra'; say "$word -> " . transmogrify $word, 'a' => 'AB_CD', 'r' => '_F', 'b' => 'E';
301Selectively replace multiple instances of a character within a string
2perl
ldbc5
import Data.List import Data.Maybe data BracketType = OpenSub | ClosedSub deriving (Show, Enum, Eq, Ord) data RealInterval = RealInterval {left :: BracketType, right :: BracketType, lowerBound :: Double, upperBound :: Double} deriving (Eq) type RealSet = [RealInterval] posInf = 1.0/0.0 :: Double negInf = (-1.0/0.0) :: Double set_R = RealInterval ClosedSub ClosedSub negInf posInf :: RealInterval emptySet = [] :: [RealInterval] instance Show RealInterval where show x@(RealInterval _ _ y y') | y == y' && (left x == right x) && (left x == ClosedSub) = "{" ++ (show y) ++ "}" | otherwise = [['(', '[']!!(fromEnum $ left x)] ++ (show $ lowerBound x) ++ "," ++ (show $ upperBound x) ++ [[')', ']']!!(fromEnum $ right x)] showList [x] = shows x showList (h:t) = shows h . (" U " ++) . showList t showList [] = (++ "(/)") construct_interval :: Char -> Double -> Double -> Char -> RealInterval construct_interval '(' x y ')' = RealInterval OpenSub OpenSub x y construct_interval '(' x y ']' = RealInterval OpenSub ClosedSub x y construct_interval '[' x y ')' = RealInterval ClosedSub OpenSub x y construct_interval _ x y _ = RealInterval ClosedSub ClosedSub x y set_is_empty :: RealSet -> Bool set_is_empty rs = (rs == emptySet) set_in :: Double -> RealSet -> Bool set_in x [] = False set_in x rs = isJust (find (\s -> ((lowerBound s < x) && (x < upperBound s)) || (x == lowerBound s && left s == ClosedSub) || (x == upperBound s && right s == ClosedSub)) rs) max_p :: (Double, BracketType) -> (Double, BracketType) -> (Double, BracketType) min_p :: (Double, BracketType) -> (Double, BracketType) -> (Double, BracketType) max_p p1@(x, y) p2@(x', y') | x == x' = (x, max y y') | x < x' = p2 | otherwise = p1 min_p p1@(x, y) p2@(x', y') | x == x' = (x, min y y') | x < x' = p1 | otherwise = p2 simple_intersection :: RealInterval -> RealInterval -> [RealInterval] simple_intersection ri1@(RealInterval l_ri1 r_ri1 x1 y1) ri2@(RealInterval l_ri2 r_ri2 x2 y2) | (y1 < x2) || (y2 < x1) = emptySet | (y1 == x2) && ((fromEnum r_ri1) + (fromEnum l_ri2) /= 2) = emptySet | (y2 == x1) && ((fromEnum r_ri2) + (fromEnum l_ri1) /= 2) = emptySet | otherwise = let lb = if x1 == x2 then (x1, min l_ri1 l_ri2) else max_p (x1, l_ri1) (x2, l_ri2) in let rb = min_p (y1, right ri1) (y2, right ri2) in [RealInterval (snd lb) (snd rb) (fst lb) (fst rb)] simple_union :: RealInterval -> RealInterval -> [RealInterval] simple_union ri1@(RealInterval l_ri1 r_ri1 x1 y1) ri2@(RealInterval l_ri2 r_ri2 x2 y2) | (y1 < x2) || (y2 < x1) = [ri2, ri1] | (y1 == x2) && ((fromEnum r_ri1) + (fromEnum l_ri2) /= 2) = [ri1, ri2] | (y2 == x1) && ((fromEnum r_ri2) + (fromEnum l_ri1) /= 2) = [ri1, ri2] | otherwise = let lb = if x1 == x2 then (x1, max l_ri1 l_ri2) else min_p (x1, l_ri1) (x2, l_ri2) in let rb = max_p (y1, right ri1) (y2, right ri2) in [RealInterval (snd lb) (snd rb) (fst lb) (fst rb)] simple_complement :: RealInterval -> [RealInterval] simple_complement ri1@(RealInterval l_ri1 r_ri1 x1 y1) = [(RealInterval ClosedSub (inv l_ri1) negInf x1), (RealInterval (inv r_ri1) ClosedSub y1 posInf)] where inv OpenSub = ClosedSub inv ClosedSub = OpenSub set_sort :: RealSet -> RealSet set_sort rs = sortBy (\s1 s2 -> let (lp, rp) = ((lowerBound s1, left s1), (lowerBound s2, left s2)) in if max_p lp rp == lp then GT else LT) rs set_simplify :: RealSet -> RealSet set_simplify [] = emptySet set_simplify rs = concat (map make_empty (set_sort (foldl (\acc ri1 -> (simple_union (head acc) ri1) ++ (tail acc)) [head sorted_rs] sorted_rs))) where sorted_rs = set_sort rs make_empty ri@(RealInterval lb rb x y) | x >= y && (lb /= rb || rb /= ClosedSub) = emptySet | otherwise = [ri] set_complement :: RealSet -> RealSet set_union :: RealSet -> RealSet -> RealSet set_intersection :: RealSet -> RealSet -> RealSet set_difference :: RealSet -> RealSet -> RealSet set_measure :: RealSet -> Double set_complement rs = foldl set_intersection [set_R] (map simple_complement rs) set_union rs1 rs2 = set_simplify (rs1 ++ rs2) set_intersection rs1 rs2 = set_simplify $ concat [simple_intersection s1 s2 | s1 <- rs1, s2 <- rs2] set_difference rs1 rs2 = set_intersection (set_complement rs2) rs1 set_measure rs = foldl (\acc x -> acc + (upperBound x) - (lowerBound x)) 0.0 rs test = map (\x -> [x]) [construct_interval '(' 0 1 ']', construct_interval '[' 0 2 ')', construct_interval '[' 0 2 ')', construct_interval '(' 1 2 ']', construct_interval '[' 0 3 ')', construct_interval '(' 0 1 ')', construct_interval '[' 0 3 ')', construct_interval '[' 0 1 ']'] restest = [set_union (test!!0) (test!!1), set_intersection (test!!2) (test!!3), set_difference (test!!4) (test!!5), set_difference (test!!6) (test!!7)] isintest s = mapM_ (\x -> putStrLn ((show x) ++ " is in " ++ (show s) ++ ": " ++ (show (set_in x s)))) [0, 1, 2] testA = [construct_interval '(' (sqrt (n + (1.0/6))) (sqrt (n + (5.0/6))) ')' | n <- [0..99]] testB = [construct_interval '(' (n + (1.0/6)) (n + (5.0/6)) ')' | n <- [0..9]] main = putStrLn ("union " ++ (show (test!!0)) ++ " " ++ (show (test!!1)) ++ " = " ++ (show (restest!!0))) >> putStrLn ("inter " ++ (show (test!!2)) ++ " " ++ (show (test!!3)) ++ " = " ++ (show (restest!!1))) >> putStrLn ("diff " ++ (show (test!!4)) ++ " " ++ (show (test!!5)) ++ " = " ++ (show (restest!!2))) >> putStrLn ("diff " ++ (show (test!!6)) ++ " " ++ (show (test!!7)) ++ " = " ++ (show (restest!!3))) >> mapM_ isintest restest >> putStrLn ("measure: " ++ (show (set_measure (set_difference testA testB))))
298Set of real numbers
8haskell
8b20z
use ntheory ":all"; my $i = 0; for (1..1e6) { my $n = pn_primorial($_); if (is_prime($n-1) || is_prime($n+1)) { print "$_\n"; last if ++$i >= 20; } }
297Sequence of primorial primes
2perl
na4iw
null
295Set consolidation
11kotlin
zqkts
use strict; use warnings; use ntheory 'divisors'; print "First 15 terms of OEIS: A005179\n"; for my $n (1..15) { my $l = 0; while (++$l) { print "$l " and last if $n == divisors($l); } }
296Sequence: smallest number with exactly n divisors
2perl
60b36
import hashlib h = hashlib.sha1() h.update(bytes(, encoding=)) h.hexdigest()
289SHA-1
3python
8bh0o
null
288Show ASCII table
1lua
cni92
def sierpinski(n): d = [] for i in xrange(n): sp = * (2 ** i) d = [sp+x+sp for x in d] + [x++x for x in d] return d print .join(sierpinski(4))
278Sierpinski triangle
3python
jlj7p
from collections import defaultdict rep = {'a': {1: 'A', 2: 'B', 4: 'C', 5: 'D'}, 'b': {1: 'E'}, 'r': {2: 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
301Selectively replace multiple instances of a character within a string
3python
2fplz
package Example; sub new { bless {} } sub foo { my ($self, $x) = @_; return 42 + $x; } package main; my $name = "foo"; print Example->new->$name(5), "\n";
299Send an unknown method call
2perl
sh9q3
null
295Set consolidation
1lua
3sbzo
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n% ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
296Sequence: smallest number with exactly n divisors
3python
y8p6q
>>> import hashlib >>> hashlib.sha256( .encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>>
290SHA-256
3python
53fux
library(digest) input <- "Rosetta code" cat(digest(input, algo = "sha256", serialize = FALSE), "\n")
290SHA-256
13r
ldoce
require 'prime' def num_divisors(n) n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } end seq = Enumerator.new do |y| cur = 0 (1..).each do |i| if num_divisors(i) == cur + 1 then y << i cur += 1 end end end p seq.take(15)
293Sequence: smallest number greater than previous term with exactly n divisors
14ruby
vt82n
library(digest) input <- "Rosetta Code" cat(digest(input, algo = "sha1", serialize = FALSE), "\n")
289SHA-1
13r
x7gw2