code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
size_t bellIndex(int row, int col) { return row * (row - 1) / 2 + col; } int getBell(int *bellTri, int row, int col) { size_t index = bellIndex(row, col); return bellTri[index]; } void setBell(int *bellTri, int row, int col, int value) { size_t index = bellIndex(row, col); bellTri[index] = value; } int *bellTriangle(int n) { size_t length = n * (n + 1) / 2; int *tri = calloc(length, sizeof(int)); int i, j; setBell(tri, 1, 0, 1); for (i = 2; i <= n; ++i) { setBell(tri, i, 0, getBell(tri, i - 1, i - 2)); for (j = 1; j < i; ++j) { int value = getBell(tri, i, j - 1) + getBell(tri, i - 1, j - 1); setBell(tri, i, j, value); } } return tri; } int main() { const int rows = 15; int *bt = bellTriangle(rows); int i, j; printf(); for (i = 1; i <= rows; ++i) { printf(, i, getBell(bt, i, 0)); } printf(); for (i = 1; i <= 10; ++i) { printf(, getBell(bt, i, 0)); for (j = 1; j < i; ++j) { printf(, getBell(bt, i, j)); } printf(); } free(bt); return 0; }
1,106Bell numbers
5c
5reuk
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d)
1,104Bin given limits
0go
axz1f
fun printSequence(sequence: String, width: Int = 50) { fun <K, V> printWithLabel(k: K, v: V) { val label = k.toString().padStart(5) println("$label: $v") } println("SEQUENCE:") sequence.chunked(width).withIndex().forEach { (i, line) -> printWithLabel(i*width + line.length, line) } println("BASE:") sequence.groupingBy { it }.eachCount().forEach { (k, v) -> printWithLabel(k, v) } printWithLabel("TOTALS", sequence.length) } const val BASE_SEQUENCE = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fun main() { printSequence(BASE_SEQUENCE) }
1,101Bioinformatics/base count
11kotlin
jbd7r
class DNA_Seq attr_accessor :seq def initialize(bases: %i[A C G T] , size: 0) @bases = bases @seq = Array.new(size){ bases.sample } end def mutate(n = 10) n.times{|n| method([:s, :d, :i].sample).call} end def to_s(n = 50) just_size = @seq.size / n ([email protected]).step(n).map{|from| + @seq[from, n].join}.join() + end def s = @seq[rand_index]= @bases.sample def d = @seq.delete_at(rand_index) def i = @seq.insert(rand_index, @bases.sample ) alias :swap :s alias :delete :d alias :insert :i private def rand_index = rand( @seq.size ) end puts test = DNA_Seq.new(size: 200) test.mutate puts test test.delete puts test
1,099Bioinformatics/Sequence mutation
14ruby
eqcax
float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, ); if (!input) { perror(); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf(); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts(); for (int i = 0; i < 9; i++) printf(, i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
1,107Benford's law
5c
q83xc
import Control.Monad (foldM) import Data.List (partition) binSplit :: Ord a => [a] -> [a] -> [[a]] binSplit lims ns = counts ++ [rest] where (counts, rest) = foldM split ns lims split l i = let (a, b) = partition (< i) l in ([a], b) binCounts :: Ord a => [a] -> [a] -> [Int] binCounts b = fmap length . binSplit b
1,104Bin given limits
8haskell
zyrt0
function prettyprint(seq)
1,101Bioinformatics/base count
1lua
hpfj8
let bases: [Character] = ["A", "C", "G", "T"] enum Action: CaseIterable { case swap, delete, insert } @discardableResult func mutate(dna: inout String) -> Action { guard let i = dna.indices.shuffled().first(where: { $0!= dna.endIndex }) else { fatalError() } let action = Action.allCases.randomElement()! switch action { case .swap: dna.replaceSubrange(i..<i, with: [bases.randomElement()!]) case .delete: dna.remove(at: i) case .insert: dna.insert(bases.randomElement()!, at: i) } return action } var d = "" for _ in 0..<200 { d.append(bases.randomElement()!) } func printSeq(_ dna: String) { for startI in stride(from: 0, to: dna.count, by: 50) { print("\(startI): \(dna.dropFirst(startI).prefix(50))") } print() print("Size: \(dna.count)") print() let counts = dna.reduce(into: [:], { $0[$1, default: 0] += 1 }) for (char, count) in counts.sorted(by: { $0.key < $1.key }) { print("\(char): \(count)") } } printSeq(d) print() for _ in 0..<20 { mutate(dna: &d) } printSeq(d)
1,099Bioinformatics/Sequence mutation
17swift
ax91i
do {\ size_t i;\ for (i = 0; i < (n); ++i)\ mpq_ } while (0) void bernoulli(mpq_t rop, unsigned int n) { unsigned int m, j; mpq_t *a = malloc(sizeof(mpq_t) * (n + 1)); mpq_for(a, init, n + 1); for (m = 0; m <= n; ++m) { mpq_set_ui(a[m], 1, m + 1); for (j = m; j > 0; --j) { mpq_sub(a[j-1], a[j], a[j-1]); mpq_set_ui(rop, j, 1); mpq_mul(a[j-1], a[j-1], rop); } } mpq_set(rop, a[0]); mpq_for(a, clear, n + 1); free(a); } int main(void) { mpq_t rop; mpz_t n, d; mpq_init(rop); mpz_inits(n, d, NULL); unsigned int i; for (i = 0; i <= 60; ++i) { bernoulli(rop, i); if (mpq_cmp_ui(rop, 0, 1)) { mpq_get_num(n, rop); mpq_get_den(d, rop); gmp_printf(, i, n, d); } } mpz_clears(n, d, NULL); mpq_clear(rop); return 0; }
1,108Bernoulli numbers
5c
3m5za
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Bins { public static <T extends Comparable<? super T>> int[] bins( List<? extends T> limits, Iterable<? extends T> data) { int[] result = new int[limits.size() + 1]; for (T n : data) { int i = Collections.binarySearch(limits, n); if (i >= 0) {
1,104Bin given limits
9java
od28d
require_relative 'raster_graphics' class RGBColour def ==(other) values == other.values end end class Pixmap def flood_fill(pixel, new_colour) current_colour = self[pixel.x, pixel.y] queue = Queue.new queue.enq(pixel) until queue.empty? p = queue.pop next unless self[p.x, p.y] == current_colour west = find_border(p, current_colour, :west) east = find_border(p, current_colour, :east) draw_line(west, east, new_colour) q = west while q.x <= east.x %i[north south].each do |direction| n = neighbour(q, direction) queue.enq(n) if self[n.x, n.y] == current_colour end q = neighbour(q, :east) end end end def neighbour(pixel, direction) case direction when :north then Pixel[pixel.x, pixel.y - 1] when :south then Pixel[pixel.x, pixel.y + 1] when :east then Pixel[pixel.x + 1, pixel.y] when :west then Pixel[pixel.x - 1, pixel.y] end end def find_border(pixel, colour, direction) nextp = neighbour(pixel, direction) while self[nextp.x, nextp.y] == colour pixel = nextp nextp = neighbour(pixel, direction) end pixel end end bitmap = Pixmap.new(300, 300) bitmap.draw_circle(Pixel[149, 149], 120, RGBColour::BLACK) bitmap.draw_circle(Pixel[200, 100], 40, RGBColour::BLACK) bitmap.flood_fill(Pixel[140, 160], RGBColour::BLUE) bitmap.save_as_png('flood_fill.png')
1,094Bitmap/Flood fill
14ruby
jbm7x
null
1,096Box the compass
11kotlin
f3pdo
(ns example (:gen-class)) (defn abs [x] (if (> x 0) x (- x))) (defn calc-benford-stats [digits] " Frequencies of digits in data " (let [y (frequencies digits) tot (reduce + (vals y))] [y tot])) (defn show-benford-stats [v] " Prints in percent the actual, Benford expected, and difference" (let [fd (map (comp first str) v)] (doseq [q (range 1 10) :let [[y tot] (calc-benford-stats fd) d (first (str q)) f (/ (get y d 0) tot 0.01) p (* (Math/log10 (/ (inc q) q)) 100) e (abs (- f p))]] (println (format "%3d%10.2f%10.2f%10.2f" q f p e))))) (def fib (lazy-cat [0N 1N] (map + fib (rest fib)))) (def fib-digits (take 10000 fib)) (def header " found-% expected-% diff") (println "Fibonacci Results") (println header) (show-benford-stats fib-digits) (println "Universal Constants from Physics") (println header) (let [ data-parser (fn [s] (let [x (re-find #"\s{10}-?[0|/\.]*([1-9])" s)] (if (not (nil? x)) (second x) x))) input (slurp "http://physics.nist.gov/cuu/Constants/Table/allascii.txt") y (for [line (line-seq (java.io.BufferedReader. (java.io.StringReader. input)))] (data-parser line)) z (filter identity y)] (show-benford-stats z)) (println "Sunspots average count per month since 1749") (println header) (let [ data-parser (fn [s] (nth (re-find #"(.+?\s){3}([1-9])" s) 2)) input (slurp "SN_m_tot_V2.0.txt") y (for [line (line-seq (java.io.BufferedReader. (java.io.StringReader. input)))] (data-parser line))] (show-benford-stats y))
1,107Benford's law
6clojure
ifcom
use rand::prelude::*; use std::collections::HashMap; use std::fmt::{Display, Formatter, Error}; pub struct Seq<'a> { alphabet: Vec<&'a str>, distr: rand::distributions::Uniform<usize>, pos_distr: rand::distributions::Uniform<usize>, seq: Vec<&'a str>, } impl Display for Seq<'_> { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { let pretty: String = self.seq .iter() .enumerate() .map(|(i, nt)| if (i + 1)% 60 == 0 { format!("{}\n", nt) } else { nt.to_string() }) .collect(); let counts_hm = self.seq .iter() .fold(HashMap::<&str, usize>::new(), |mut m, nt| { *m.entry(nt).or_default() += 1; m }); let mut counts_vec: Vec<(&str, usize)> = counts_hm.into_iter().collect(); counts_vec.sort_by(|a, b| a.0.cmp(&b.0)); let counts_string = counts_vec .iter() .fold(String::new(), |mut counts_string, (nt, count)| { counts_string += &format!("{} = {}\n", nt, count); counts_string }); write!(f, "Seq:\n{}\n\nLength: {}\n\nCounts:\n{}", pretty, self.seq.len(), counts_string) } } impl Seq<'_> { pub fn new(alphabet: Vec<&str>, len: usize) -> Seq { let distr = rand::distributions::Uniform::new_inclusive(0, alphabet.len() - 1); let pos_distr = rand::distributions::Uniform::new_inclusive(0, len - 1); let seq: Vec<&str> = (0..len) .map(|_| { alphabet[thread_rng().sample(distr)] }) .collect(); Seq { alphabet, distr, pos_distr, seq } } pub fn insert(&mut self) { let pos = thread_rng().sample(self.pos_distr); let nt = self.alphabet[thread_rng().sample(self.distr)]; println!("Inserting {} at position {}", nt, pos); self.seq.insert(pos, nt); } pub fn delete(&mut self) { let pos = thread_rng().sample(self.pos_distr); println!("Deleting {} at position {}", self.seq[pos], pos); self.seq.remove(pos); } pub fn swap(&mut self) { let pos = thread_rng().sample(self.pos_distr); let cur_nt = self.seq[pos]; let new_nt = self.alphabet[thread_rng().sample(self.distr)]; println!("Replacing {} at position {} with {}", cur_nt, pos, new_nt); self.seq[pos] = new_nt; } } fn main() { let mut seq = Seq::new(vec!["A", "C", "T", "G"], 200); println!("Initial sequnce:\n{}", seq); let mut_distr = rand::distributions::Uniform::new_inclusive(0, 2); for _ in 0..10 { let mutation = thread_rng().sample(mut_distr); if mutation == 0 { seq.insert() } else if mutation == 1 { seq.delete() } else { seq.swap() } } println!("\nMutated sequence:\n{}", seq); }
1,099Bioinformatics/Sequence mutation
15rust
wsle4
use std::fs::File;
1,094Bitmap/Flood fill
15rust
hp9j2
import java.awt.Color import scala.collection.mutable object Flood { def floodFillStack(bm:RgbBitmap, x: Int, y: Int, targetColor: Color): Unit = {
1,094Bitmap/Flood fill
16scala
pe2bj
function binner(limits, data) local bins = setmetatable({}, {__index=function() return 0 end}) local n, flr = #limits+1, math.floor for _, x in ipairs(data) do local lo, hi = 1, n while lo < hi do local mid = flr((lo + hi) / 2) if not limits[mid] or x < limits[mid] then hi=mid else lo=mid+1 end end bins[lo] = bins[lo] + 1 end return bins end function printer(limits, bins) for i = 1, #limits+1 do print(string.format("[%3s,%3s):%d", limits[i-1] or " -", limits[i] or " +", bins[i])) end end print("PART 1:") limits = {23, 37, 43, 53, 67, 83} data = {95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55} bins = binner(limits, data) printer(limits, bins) print("\nPART 2:") limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} data = {445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749} bins = binner(limits, data) printer(limits, bins)
1,104Bin given limits
1lua
q8mx0
use strict; use warnings; use feature 'say'; my %cnt; my $total = 0; while ($_ = <DATA>) { chomp; printf "%4d:%s\n", $total+1, s/(.{10})/$1 /gr; $total += length; $cnt{$_}++ for split // } say "\nTotal bases: $total"; say "$_: " . ($cnt{$_}//0) for <A C G T>; __DATA__ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
1,101Bioinformatics/base count
2perl
t6jfg
ns test-project-intellij.core (:gen-class)) (defn a-t [n] " Used Akiyama-Tanigawa algorithm with a single loop rather than double nested loop " " Clojure does fractional arithmetic automatically so that part is easy " (loop [m 0 j m A (vec (map #(/ 1 %) (range 1 (+ n 2))))] (cond (>= j 1) (recur m (dec j) (assoc A (dec j) (* j (- (nth A (dec j)) (nth A j))))) (< m n) (recur (inc m) (inc m) A) :else (nth A 0)))) (defn format-ans [ans] " Formats answer so that '/' is aligned for all answers " (if (= ans 1) (format "%50d /%8d" 1 1) (format "%50d /%8d" (numerator ans) (denominator ans)))) (doseq [q (flatten [0 1 (range 2 62 2)]) :let [ans (a-t q)]] (println q ":" (format-ans ans)))
1,108Bernoulli numbers
6clojure
cvj9b
void best_shuffle(const char* txt, char* result) { const size_t len = strlen(txt); if (len == 0) return; assert(len == strlen(result)); size_t counts[UCHAR_MAX]; memset(counts, '\0', UCHAR_MAX * sizeof(int)); size_t fmax = 0; for (size_t i = 0; i < len; i++) { counts[(unsigned char)txt[i]]++; const size_t fnew = counts[(unsigned char)txt[i]]; if (fmax < fnew) fmax = fnew; } assert(fmax > 0 && fmax <= len); size_t *ndx1 = malloc(len * sizeof(size_t)); if (ndx1 == NULL) exit(EXIT_FAILURE); for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++) if (counts[ch]) for (size_t j = 0; j < len; j++) if (ch == (unsigned char)txt[j]) { ndx1[i] = j; i++; } size_t *ndx2 = malloc(len * sizeof(size_t)); if (ndx2 == NULL) exit(EXIT_FAILURE); for (size_t i = 0, n = 0, m = 0; i < len; i++) { ndx2[i] = ndx1[n]; n += fmax; if (n >= len) { m++; n = m; } } const size_t grp = 1 + (len - 1) / fmax; assert(grp > 0 && grp <= len); const size_t lng = 1 + (len - 1) % fmax; assert(lng > 0 && lng <= len); for (size_t i = 0, j = 0; i < fmax; i++) { const size_t first = ndx2[j]; const size_t glen = grp - (i < lng ? 0 : 1); for (size_t k = 1; k < glen; k++) ndx1[j + k - 1] = ndx2[j + k]; ndx1[j + glen - 1] = first; j += glen; } result[len] = '\0'; for (size_t i = 0; i < len; i++) result[ndx2[i]] = txt[ndx1[i]]; free(ndx1); free(ndx2); } void display(const char* txt1, const char* txt2) { const size_t len = strlen(txt1); assert(len == strlen(txt2)); int score = 0; for (size_t i = 0; i < len; i++) if (txt1[i] == txt2[i]) score++; (void)printf(, txt1, txt2, score); } int main() { const char* data[] = {, , , , , , , , }; const size_t data_len = sizeof(data) / sizeof(data[0]); for (size_t i = 0; i < data_len; i++) { const size_t shuf_len = strlen(data[i]) + 1; char shuf[shuf_len]; memset(shuf, 0xFF, sizeof shuf); shuf[shuf_len - 1] = '\0'; best_shuffle(data[i], shuf); display(data[i], shuf); } return EXIT_SUCCESS; }
1,109Best shuffle
5c
rheg7
(defn score [before after] (->> (map = before after) (filter true? ,) count)) (defn merge-vecs [init vecs] (reduce (fn [counts [index x]] (assoc counts x (conj (get counts x []) index))) init vecs)) (defn frequency "Returns a collection of indecies of distinct items" [coll] (->> (map-indexed vector coll) (merge-vecs {} ,))) (defn group-indecies [s] (->> (frequency s) vals (sort-by count ,) reverse)) (defn cycles [coll] (let [n (count (first coll)) cycle (cycle (range n)) coll (apply concat coll)] (->> (map vector coll cycle) (merge-vecs [] ,)))) (defn rotate [n coll] (let [c (count coll) n (rem (+ c n) c)] (concat (drop n coll) (take n coll)))) (defn best-shuffle [s] (let [ref (cycles (group-indecies s)) prm (apply concat (map (partial rotate 1) ref)) ref (apply concat ref)] (->> (map vector ref prm) (sort-by first ,) (map second ,) (map (partial get s) ,) (apply str ,) (#(vector s % (score s %)))))) user> (->> ["abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"] (map best-shuffle ,) vec) [["abracadabra" "bdabararaac" 0] ["seesaw" "eawess" 0] ["elk" "lke" 0] ["grrrrrr" "rgrrrrr" 5] ["up" "pu" 0] ["a" "a" 1]]
1,109Best shuffle
6clojure
ba0kz
package main import ( "bytes" "fmt" )
1,105Binary strings
0go
odl8q
use strict; use warnings; no warnings 'uninitialized'; use feature 'say'; use experimental 'signatures'; use constant Inf => 1e10; my @tests = ( { limits => [23, 37, 43, 53, 67, 83], data => [ 95,21,94,12,99,4,70,75,83,93,52,80,57, 5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96, 6,98,40,79,97,45,64,60,29,49,36,43,55 ] }, { limits => [14, 18, 249, 312, 389, 392, 513, 591, 634, 720], data => [ 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749 ] } ); sub bisect_right ($x, $low, $high, @array) { my ($middle); while ($low < $high) { $middle = ($low + $high) / 2; $x < $array[$middle] ? $high = $middle : ($low = $middle + 1) } $low-1 } sub bin_it ($limits, $data) { my @bins; ++$bins[ bisect_right($_, 0, @$limits-1, @$limits) ] for @$data; @bins } sub bin_format ($limits, @bins) { my @lim = @$limits; my(@formatted); push @formatted, sprintf "[%3d,%3d) =>%3d\n", $lim[$_], ($lim[$_+1] == Inf ? 'Inf' : $lim[$_+1]), $bins[$_] for 0..@lim-2; @formatted } for (0..$ my @limits = (0, @{$tests[$_]{limits}}, Inf); say bin_format \@limits, bin_it(\@limits,\@{$tests[$_]{data}}); }
1,104Bin given limits
2perl
25alf
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f) print() tot = 0 for base, count in basecount(dna): print(f) tot += count base, count = 'TOT', tot print(f) if __name__ == '__main__': print() sequence = '''\ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT''' seq_pp(sequence)
1,101Bioinformatics/base count
3python
zyhtt
package main import ( "fmt" "math/big" ) func bellTriangle(n int) [][]*big.Int { tri := make([][]*big.Int, n) for i := 0; i < n; i++ { tri[i] = make([]*big.Int, i) for j := 0; j < i; j++ { tri[i][j] = new(big.Int) } } tri[1][0].SetUint64(1) for i := 2; i < n; i++ { tri[i][0].Set(tri[i-1][i-2]) for j := 1; j < i; j++ { tri[i][j].Add(tri[i][j-1], tri[i-1][j-1]) } } return tri } func main() { bt := bellTriangle(51) fmt.Println("First fifteen and fiftieth Bell numbers:") for i := 1; i <= 15; i++ { fmt.Printf("%2d:%d\n", i, bt[i][0]) } fmt.Println("50:", bt[50][0]) fmt.Println("\nThe first ten rows of Bell's triangle:") for i := 1; i <= 10; i++ { fmt.Println(bt[i]) } }
1,106Bell numbers
0go
8n90g
import java.nio.charset.StandardCharsets class MutableByteString { private byte[] bytes private int length MutableByteString(byte... bytes) { setInternal(bytes) } int length() { return length } boolean isEmpty() { return length == 0 } byte get(int index) { return bytes[check(index)] } void set(byte[] bytes) { setInternal(bytes) } void set(int index, byte b) { bytes[check(index)] = b } void append(byte b) { if (length >= bytes.length) { int len = 2 * bytes.length if (len < 0) { len = Integer.MAX_VALUE } bytes = Arrays.copyOf(bytes, len) } bytes[length] = b length++ } MutableByteString substring(int from, int to) { return new MutableByteString(Arrays.copyOfRange(bytes, from, to)) } void replace(byte[] from, byte[] to) { ByteArrayOutputStream copy = new ByteArrayOutputStream() if (from.length == 0) { for (byte b: bytes) { copy.write(to, 0, to.length) copy.write(b) } copy.write(to, 0, to.length) } else { for (int i = 0; i < length; i++) { if (regionEqualsImpl(i, from)) { copy.write(to, 0, to.length) i += from.length - 1 } else { copy.write(bytes[i]) } } } set(copy.toByteArray()) } boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) { if (Math.max(offset, otherOffset) + len < 0) { return false } if (offset + len > length || otherOffset + len > other.length()) { return false } for (int i = 0; i < len; i++) { if (bytes[offset + i] != other.get(otherOffset + i)) { return false } } return true } String toHexString() { char[] hex = new char[2 * length] for (int i = 0; i < length; i++) { hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F) hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F) } return new String(hex) } String toStringUtf8() { return new String(bytes, 0, length, StandardCharsets.UTF_8) } private void setInternal(byte[] bytes) { this.bytes = bytes.clone() this.length = bytes.length } private boolean regionEqualsImpl(int offset, byte[] other) { int len = other.length if (offset < 0 || offset + len < 0) return false if (offset + len > length) return false for (int i = 0; i < len; i++) { if (bytes[offset + i] != other[i]) return false } return true } private int check(int index) { if (index < 0 || index >= length) throw new IndexOutOfBoundsException(String.valueOf(index)) return index } }
1,105Binary strings
7groovy
x06wl
gene1 <- "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" gene2 <- gsub("\n", "", gene1) gene3 <- strsplit(gene2, split = character(0)) gene4 <- gene3[[1]] basecounts <- as.data.frame(table(gene4)) print_row <- function(df, row){paste0(df$gene[row],": ", df$Freq[row])} cat(" Data: \n", " 1:",substring(gene2, 1, 50),"\n", " 51:",substring(gene2, 51, 100),"\n", "101:",substring(gene2, 101, 150),"\n", "151:",substring(gene2, 151, 200),"\n", "201:",substring(gene2, 201, 250),"\n", "251:",substring(gene2, 251, 300),"\n", "301:",substring(gene2, 301, 350),"\n", "351:",substring(gene2, 351, 400),"\n", "401:",substring(gene2, 401, 450),"\n", "451:",substring(gene2, 451, 500),"\n", "\n", "Base Count Results: \n", print_row(basecounts,1), "\n", print_row(basecounts,2), "\n", print_row(basecounts,3), "\n", print_row(basecounts,4), "\n", "\n", "Total Base Count:", paste(length(gene4)) )
1,101Bioinformatics/base count
13r
ntgi2
null
1,096Box the compass
1lua
t61fn
class Bell { private static class BellTriangle { private List<Integer> arr BellTriangle(int n) { int length = (int) (n * (n + 1) / 2) arr = new ArrayList<>(length) for (int i = 0; i < length; ++i) { arr.add(0) } set(1, 0, 1) for (int i = 2; i <= n; ++i) { set(i, 0, get(i - 1, i - 2)) for (int j = 1; j < i; ++j) { int value = get(i, j - 1) + get(i - 1, j - 1) set(i, j, value) } } } private static int index(int row, int col) { if (row > 0 && col >= 0 && col < row) { return row * (row - 1) / 2 + col } else { throw new IllegalArgumentException() } } int get(int row, int col) { int i = index(row, col) return arr.get(i) } void set(int row, int col, int value) { int i = index(row, col) arr.set(i, value) } } static void main(String[] args) { final int rows = 15 BellTriangle bt = new BellTriangle(rows) System.out.println("First fifteen Bell numbers:") for (int i = 0; i < rows; ++i) { System.out.printf("%2d:%d\n", i + 1, bt.get(i + 1, 0)) } for (int i = 1; i <= 10; ++i) { System.out.print(bt.get(i, 0)) for (int j = 1; j < i; ++j) { System.out.printf(",%d", bt.get(i, j)) } System.out.println() } } }
1,106Bell numbers
7groovy
wszel
import Text.Regex string = "world" :: String
1,105Binary strings
8haskell
251ll
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f) for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f) print(f) if __name__ == : print() limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print() limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
1,104Bin given limits
3python
v4e29
package raster
1,100Bitmap/Bresenham's line algorithm
0go
mlayi
bellTri :: [[Integer]] bellTri = let f xs = (last xs, xs) in map snd (iterate (f . uncurry (scanl (+))) (1, [1])) bell :: [Integer] bell = map head bellTri main :: IO () main = do putStrLn "First 10 rows of Bell's Triangle:" mapM_ print (take 10 bellTri) putStrLn "\nFirst 15 Bell numbers:" mapM_ print (take 15 bell) putStrLn "\n50th Bell number:" print (bell !! 49)
1,106Bell numbers
8haskell
lubch
import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class MutableByteString { private byte[] bytes; private int length; public MutableByteString(byte... bytes) { setInternal(bytes); } public int length() { return length; } public boolean isEmpty() { return length == 0; } public byte get(int index) { return bytes[check(index)]; } public void set(byte[] bytes) { setInternal(bytes); } public void set(int index, byte b) { bytes[check(index)] = b; } public void append(byte b) { if (length >= bytes.length) { int len = 2 * bytes.length; if (len < 0) len = Integer.MAX_VALUE; bytes = Arrays.copyOf(bytes, len); } bytes[length] = b; length++; } public MutableByteString substring(int from, int to) { return new MutableByteString(Arrays.copyOfRange(bytes, from, to)); } public void replace(byte[] from, byte[] to) { ByteArrayOutputStream copy = new ByteArrayOutputStream(); if (from.length == 0) { for (byte b : bytes) { copy.write(to, 0, to.length); copy.write(b); } copy.write(to, 0, to.length); } else { for (int i = 0; i < length; i++) { if (regionEquals(i, from)) { copy.write(to, 0, to.length); i += from.length - 1; } else { copy.write(bytes[i]); } } } set(copy.toByteArray()); } public boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) { if (Math.max(offset, otherOffset) + len < 0) return false; if (offset + len > length || otherOffset + len > other.length()) return false; for (int i = 0; i < len; i++) { if (bytes[offset + i] != other.get(otherOffset + i)) return false; } return true; } public String toHexString() { char[] hex = new char[2 * length]; for (int i = 0; i < length; i++) { hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F); hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F); } return new String(hex); } public String toStringUtf8() { return new String(bytes, 0, length, StandardCharsets.UTF_8); } private void setInternal(byte[] bytes) { this.bytes = bytes.clone(); this.length = bytes.length; } private boolean regionEquals(int offset, byte[] other) { int len = other.length; if (offset < 0 || offset + len < 0) return false; if (offset + len > length) return false; for (int i = 0; i < len; i++) { if (bytes[offset + i] != other[i]) return false; } return true; } private int check(int index) { if (index < 0 || index >= length) throw new IndexOutOfBoundsException(String.valueOf(index)); return index; } }
1,105Binary strings
9java
6973z
limits1 <- c(23, 37, 43, 53, 67, 83) data1 <- c(95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55) limits2 <- c(14, 18, 249, 312, 389, 392, 513, 591, 634, 720) data2 <- c(445,814,519,697,700,130,255,889,481,122,932,77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775,47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238,62,678,98,534,622,907,406,714,184,391,913,42,560,247, 346,860,56,138,546,38,985,948,58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426,9,457,628,410,723,354,895,881,953,677,137,397,97, 854,740,83,216,421,94,517,479,292,963,376,981,480,39,257,272,157,5,316,395, 787,942,456,242,759,898,576,67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585,40,54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466,23,707,467,33,670,921,180,991,396,160,436,717,918,8,374,101,684,727,749) createBin <- function(limits, data) sapply(0:length(limits), function(x) sum(findInterval(data, limits) == x)) printBin <- function(limits, bin) { invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:", if(x == 0) "-\U221E < x <" else paste(limits[x], "\U2264 x <"), if(x == length(limits)) "\U221E" else limits[x + 1], "and contains", bin[x + 1], "elements.\n"))) } oneLine <- function(limits, data) { invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:", if(x == 0) "-\U221E < x <" else paste(limits[x], "\U2264 x <"), if(x == length(limits)) "\U221E" else limits[x + 1], "and contains", sum(findInterval(data, limits) == x), "elements.\n"))) } createBin(limits1, data1) printBin(limits1, createBin(limits1, data1)) createBin(limits2, data2) printBin(limits2, createBin(limits2, data2)) oneLine(limits2, c(data1, data2))
1,104Bin given limits
13r
92bmg
module Bitmap.Line(line) where import Bitmap import Control.Monad import Control.Monad.ST import qualified Data.STRef var = Data.STRef.newSTRef get = Data.STRef.readSTRef mutate = Data.STRef.modifySTRef line :: Color c => Image s c -> Pixel -> Pixel -> c -> ST s () line i (Pixel (xa, ya)) (Pixel (xb, yb)) c = do yV <- var y1 errorV <- var $ deltax `div` 2 forM_ [x1 .. x2] (\x -> do y <- get yV setPix i (Pixel $ if steep then (y, x) else (x, y)) c mutate errorV $ subtract deltay error <- get errorV when (error < 0) (do mutate yV (+ ystep) mutate errorV (+ deltax))) where steep = abs (yb - ya) > abs (xb - xa) (xa', ya', xb', yb') = if steep then (ya, xa, yb, xb) else (xa, ya, xb, yb) (x1, y1, x2, y2) = if xa' > xb' then (xb', yb', xa', ya') else (xa', ya', xb', yb') deltax = x2 - x1 deltay = abs $ y2 - y1 ystep = if y1 < y2 then 1 else -1
1,100Bitmap/Bresenham's line algorithm
8haskell
k1zh0
import java.util.ArrayList; import java.util.List; public class Bell { private static class BellTriangle { private List<Integer> arr; BellTriangle(int n) { int length = n * (n + 1) / 2; arr = new ArrayList<>(length); for (int i = 0; i < length; ++i) { arr.add(0); } set(1, 0, 1); for (int i = 2; i <= n; ++i) { set(i, 0, get(i - 1, i - 2)); for (int j = 1; j < i; ++j) { int value = get(i, j - 1) + get(i - 1, j - 1); set(i, j, value); } } } private int index(int row, int col) { if (row > 0 && col >= 0 && col < row) { return row * (row - 1) / 2 + col; } else { throw new IllegalArgumentException(); } } public int get(int row, int col) { int i = index(row, col); return arr.get(i); } public void set(int row, int col, int value) { int i = index(row, col); arr.set(i, value); } } public static void main(String[] args) { final int rows = 15; BellTriangle bt = new BellTriangle(rows); System.out.println("First fifteen Bell numbers:"); for (int i = 0; i < rows; ++i) { System.out.printf("%2d:%d\n", i + 1, bt.get(i + 1, 0)); } for (int i = 1; i <= 10; ++i) { System.out.print(bt.get(i, 0)); for (int j = 1; j < i; ++j) { System.out.printf(",%d", bt.get(i, j)); } System.out.println(); } } }
1,106Bell numbers
9java
3mgzg
null
1,105Binary strings
10javascript
lupcf
dna = <<DNA_STR CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT DNA_STR chunk_size = 60 dna = dna.delete() size = dna.size 0.step(size, chunk_size) do |pos| puts end puts dna.chars.tally.sort.map{|ar| ar.join() } puts
1,101Bioinformatics/base count
14ruby
69b3t
use std::collections::HashMap; fn main() { let dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; let mut base_count = HashMap::new(); let mut total_count = 0; print!("Sequence:"); for base in dna.chars() { if total_count% 50 == 0 { print!("\n{:3}: ", total_count); } print!("{}", base); total_count += 1; let count = base_count.entry(base).or_insert(0);
1,101Bioinformatics/base count
15rust
ycp68
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false';
1,090Boolean values
2perl
3m8zs
package main import ( "bytes" "fmt" "image" "image/color" "image/draw" "image/png" ) func main() {
1,102Bitmap
0go
solqa
import Foundation let dna = """ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT """ print("input:\n\(dna)\n") let counts = dna.replacingOccurrences(of: "\n", with: "").reduce(into: [:], { $0[$1, default: 0] += 1 }) print("Counts: \(counts)") print("Total: \(counts.values.reduce(0, +))")
1,101Bioinformatics/base count
17swift
3mkz2
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public class Bresenham { public static void main(String[] args) { SwingUtilities.invokeLater(Bresenham::run); } private static void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setTitle("Bresenham"); f.getContentPane().add(new BresenhamPanel()); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } } class BresenhamPanel extends JPanel { private final int pixelSize = 10; BresenhamPanel() { setPreferredSize(new Dimension(600, 500)); setBackground(Color.WHITE); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int w = (getWidth() - 1) / pixelSize; int h = (getHeight() - 1) / pixelSize; int maxX = (w - 1) / 2; int maxY = (h - 1) / 2; int x1 = -maxX, x2 = maxX * -2 / 3, x3 = maxX * 2 / 3, x4 = maxX; int y1 = -maxY, y2 = maxY * -2 / 3, y3 = maxY * 2 / 3, y4 = maxY; drawLine(g, 0, 0, x3, y1);
1,100Bitmap/Bresenham's line algorithm
9java
47o58
go?=> member(N,1..5), println(N), fail,% or false/0 to get other solutions nl. go => true.
1,090Boolean values
12php
pe4ba
module Bitmap(module Bitmap) where import Control.Monad import Control.Monad.ST import Data.Array.ST newtype Pixel = Pixel (Int, Int) deriving Eq instance Ord Pixel where compare (Pixel (x1, y1)) (Pixel (x2, y2)) = case compare y1 y2 of EQ -> compare x1 x2 v -> v instance Ix Pixel where range (Pixel (xa, ya), Pixel (xz, yz)) = [Pixel (x, y) | y <- [ya .. yz], x <- [xa .. xz]] index (Pixel (xa, ya), Pixel (xz, _)) (Pixel (xi, yi)) = (yi - ya)*(xz - xa + 1) + (xi - xa) inRange (Pixel (xa, ya), Pixel (xz, yz)) (Pixel (xi, yi)) = not $ xi < xa || xi > xz || yi < ya || yi > yz rangeSize (Pixel (xa, ya), Pixel (xz, yz)) = (xz - xa + 1) * (yz - ya + 1) instance Show Pixel where show (Pixel p) = show p class Ord c => Color c where luminance :: c -> Int black, white :: c toNetpbm :: [c] -> String fromNetpbm :: [Int] -> [c] netpbmMagicNumber, netpbmMaxval :: c -> String newtype Color c => Image s c = Image (STArray s Pixel c) image :: Color c => Int -> Int -> c -> ST s (Image s c) image w h = liftM Image . newArray (Pixel (0, 0), Pixel (w - 1, h - 1)) listImage :: Color c => Int -> Int -> [c] -> ST s (Image s c) listImage w h = liftM Image . newListArray (Pixel (0, 0), Pixel (w - 1, h - 1)) dimensions :: Color c => Image s c -> ST s (Int, Int) dimensions (Image i) = do (_, Pixel (x, y)) <- getBounds i return (x + 1, y + 1) getPix :: Color c => Image s c -> Pixel -> ST s c getPix (Image i) = readArray i getPixels :: Color c => Image s c -> ST s [c] getPixels (Image i) = getElems i setPix :: Color c => Image s c -> Pixel -> c -> ST s () setPix (Image i) = writeArray i fill :: Color c => Image s c -> c -> ST s () fill (Image i) c = getBounds i >>= mapM_ f . range where f p = writeArray i p c mapImage :: (Color c, Color c') => (c -> c') -> Image s c -> ST s (Image s c') mapImage f (Image i) = liftM Image $ mapArray f i
1,102Bitmap
8haskell
921mo
class BellTriangle(n: Int) { private val arr: Array<Int> init { val length = n * (n + 1) / 2 arr = Array(length) { 0 } set(1, 0, 1) for (i in 2..n) { set(i, 0, get(i - 1, i - 2)) for (j in 1 until i) { val value = get(i, j - 1) + get(i - 1, j - 1) set(i, j, value) } } } private fun index(row: Int, col: Int): Int { require(row > 0) require(col >= 0) require(col < row) return row * (row - 1) / 2 + col } operator fun get(row: Int, col: Int): Int { val i = index(row, col) return arr[i] } private operator fun set(row: Int, col: Int, value: Int) { val i = index(row, col) arr[i] = value } } fun main() { val rows = 15 val bt = BellTriangle(rows) println("First fifteen Bell numbers:") for (i in 1..rows) { println("%2d:%d".format(i, bt[i, 0])) } for (i in 1..10) { print("${bt[i, 0]}") for (j in 1 until i) { print(", ${bt[i, j]}") } println() } }
1,106Bell numbers
11kotlin
nt2ij
class ByteString(private val bytes: ByteArray) : Comparable<ByteString> { val length get() = bytes.size fun isEmpty() = bytes.isEmpty() operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes) operator fun plus(byte: Byte) = ByteString(bytes + byte) operator fun get(index: Int): Byte { require (index in 0 until length) return bytes[index] } fun toByteArray() = bytes fun copy() = ByteString(bytes.copyOf()) override fun compareTo(other: ByteString) = this.toString().compareTo(other.toString()) override fun equals(other: Any?): Boolean { if (other == null || other !is ByteString) return false return compareTo(other) == 0 } override fun hashCode() = this.toString().hashCode() fun substring(startIndex: Int) = ByteString(bytes.sliceArray(startIndex until length)) fun substring(startIndex: Int, endIndex: Int) = ByteString(bytes.sliceArray(startIndex until endIndex)) fun replace(oldByte: Byte, newByte: Byte): ByteString { val ba = ByteArray(length) { if (bytes[it] == oldByte) newByte else bytes[it] } return ByteString(ba) } fun replace(oldValue: ByteString, newValue: ByteString) = this.toString().replace(oldValue.toString(), newValue.toString()).toByteString() override fun toString(): String { val chars = CharArray(length) for (i in 0 until length) { chars[i] = when (bytes[i]) { in 0..127 -> bytes[i].toChar() else -> (256 + bytes[i]).toChar() } } return chars.joinToString("") } } fun String.toByteString(): ByteString { val bytes = ByteArray(this.length) for (i in 0 until this.length) { bytes[i] = when (this[i].toInt()) { in 0..127 -> this[i].toByte() in 128..255 -> (this[i] - 256).toByte() else -> '?'.toByte()
1,105Binary strings
11kotlin
dzunz
Test = Struct.new(:limits, :data) tests = Test.new( [23, 37, 43, 53, 67, 83], [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]), Test.new( [14, 18, 249, 312, 389, 392, 513, 591, 634, 720], [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]) def bin(limits, data) data.map{|d| limits.bsearch{|limit| limit > d} }.tally end def present_bins(limits, bins) ranges = ([nil]+limits+[nil]).each_cons(2).map{|low, high| Range.new(low, high, true) } ranges.each{|range| puts } end tests.each do |test| present_bins(test.limits, bin(test.limits, test.data)) puts end
1,104Bin given limits
14ruby
5rxuj
function bline(x0, y0, x1, y1) { var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1; var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1; var err = (dx>dy ? dx : -dy)/2; while (true) { setPixel(x0,y0); if (x0 === x1 && y0 === y1) break; var e2 = err; if (e2 > -dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } }
1,100Bitmap/Bresenham's line algorithm
10javascript
hptjh
null
1,106Bell numbers
1lua
dzvnq
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
1,107Benford's law
0go
25bl7
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> { let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1); for _ in 0..=limits.len() {bins.push(Vec::new());} limits.iter().enumerate().for_each(|(idx, limit)| { data.iter().for_each(|elem| { if idx == 0 && elem < limit { bins[0].push(*elem); }
1,104Bin given limits
15rust
47q5u
def tallyFirstDigits = { size, generator -> def population = (0..<size).collect { generator(it) } def firstDigits = [0]*10 population.each { number -> firstDigits[(number as String)[0] as int] ++ } firstDigits }
1,107Benford's law
7groovy
ycr6o
import qualified Data.Map as M import Data.Char (digitToInt) fstdigit :: Integer -> Int fstdigit = digitToInt . head . show n = 1000 :: Int fibs = 1: 1: zipWith (+) fibs (tail fibs) fibdata = map fstdigit $ take n fibs freqs = M.fromListWith (+) $ zip fibdata (repeat 1) tab :: [(Int, Double, Double)] tab = [ ( d , fromIntegral (M.findWithDefault 0 d freqs) / fromIntegral n , logBase 10.0 $ 1 + 1 / fromIntegral d) | d <- [1 .. 9] ] main = print tab
1,107Benford's law
8haskell
axd1g
package main import ( "fmt" "math/rand" "time" ) var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} func main() { rand.Seed(time.Now().UnixNano()) for _, s := range ts {
1,109Best shuffle
0go
nt9i1
foo = 'foo'
1,105Binary strings
1lua
f35dp
import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; public class BasicBitmapStorage { private final BufferedImage image; public BasicBitmapStorage(int width, int height) { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } public void fill(Color c) { Graphics g = image.getGraphics(); g.setColor(c); g.fillRect(0, 0, image.getWidth(), image.getHeight()); } public void setPixel(int x, int y, Color c) { image.setRGB(x, y, c.getRGB()); } public Color getPixel(int x, int y) { return new Color(image.getRGB(x, y)); } public Image getImage() { return image; } }
1,102Bitmap
9java
t67f9
def shuffle(text) { def shuffled = (text as List) for (sourceIndex in 0..<text.size()) { for (destinationIndex in 0..<text.size()) { if (shuffled[sourceIndex] != shuffled[destinationIndex] && shuffled[sourceIndex] != text[destinationIndex] && shuffled[destinationIndex] != text[sourceIndex]) { char tmp = shuffled[sourceIndex]; shuffled[sourceIndex] = shuffled[destinationIndex]; shuffled[destinationIndex] = tmp; break; } } } [original: text, shuffled: shuffled.join(""), score: score(text, shuffled)] } def score(original, shuffled) { int score = 0 original.eachWithIndex { character, index -> if (character == shuffled[index]) { score++ } } score } ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"].each { text -> def result = shuffle(text) println "${result.original}, ${result.shuffled}, (${result.score})" }
1,109Best shuffle
7groovy
sozq1
null
1,100Bitmap/Bresenham's line algorithm
1lua
25ql3
>>> True True >>> not True False >>> >>> False + 0 0 >>> True + 0 1 >>> False + 0j 0j >>> True * 3.141 3.141 >>> >>> not 0 True >>> not not 0 False >>> not 1234 False >>> bool(0.0) False >>> bool(0j) False >>> bool(1+2j) True >>> >>> bool([]) False >>> bool([None]) True >>> 'I contain something' if (None,) else 'I am empty' 'I contain something' >>> bool({}) False >>> bool() False >>> bool() True
1,090Boolean values
3python
69o3w
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b))
1,103Bitwise operations
0go
eq6a6
null
1,102Bitmap
10javascript
mlpyv
shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2 printTest prog = mapM_ test texts where test s = do x <- prog s putStrLn $ unwords $ [ show s , show x , show $ shufflingQuality s x] texts = [ "abba", "abracadabra", "seesaw", "elk" , "grrrrrr" , "up", "a", "aaaaa.....bbbbb" , "Rosetta Code is a programming chrestomathy site." ]
1,109Best shuffle
8haskell
ugbv2
(cond ([(< 4 3) 'apple] ['bloggle 'pear] [else 'nectarine])
1,090Boolean values
13r
f3qdc
def bitwise = { a, b -> println """ a & b = ${a} & ${b} = ${a & b} a | b = ${a} | ${b} = ${a | b} a ^ b = ${a} ^ ${b} = ${a ^ b} ~ a = ~ ${a} = ${~ a} a << b = ${a} << ${b} = ${a << b} a >> b = ${a} >> ${b} = ${a >> b} arithmetic (sign-preserving) shift a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift """ }
1,103Bitwise operations
7groovy
k1dh7
use strict 'vars'; use warnings; use feature 'say'; use bigint; my @b = 1; my @Aitkens = [1]; push @Aitkens, do { my @c = $b[-1]; push @c, $b[$_] + $c[$_] for 0..$ @b = @c; [@c] } until (@Aitkens == 50); my @Bell_numbers = map { @$_[0] } @Aitkens; say 'First fifteen and fiftieth Bell numbers:'; printf "%2d:%s\n", 1+$_, $Bell_numbers[$_] for 0..14, 49; say "\nFirst ten rows of Aitken's array:"; printf '%-7d'x@{$Aitkens[$_]}."\n", @{$Aitkens[$_]} for 0..9;
1,106Bell numbers
2perl
7ksrh
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d%10.6f%10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
1,107Benford's law
9java
jbs7c
int bsearch (int *a, int n, int x) { int i = 0, j = n - 1; while (i <= j) { int k = i + ((j - i) / 2); if (a[k] == x) { return k; } else if (a[k] < x) { i = k + 1; } else { j = k - 1; } } return -1; } int bsearch_r (int *a, int x, int i, int j) { if (j < i) { return -1; } int k = i + ((j - i) / 2); if (a[k] == x) { return k; } else if (a[k] < x) { return bsearch_r(a, x, k + 1, j); } else { return bsearch_r(a, x, i, k - 1); } } int main () { int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782}; int n = sizeof a / sizeof a[0]; int x = 2; int i = bsearch(a, n, x); if (i >= 0) printf(, x, i); else printf(, x); x = 5; i = bsearch_r(a, x, 0, n - 1); if (i >= 0) printf(, x, i); else printf(, x); return 0; }
1,110Binary search
5c
8n304
null
1,102Bitmap
11kotlin
odu8z
const fibseries = n => [...Array(n)] .reduce( (fib, _, i) => i < 2 ? ( fib ) : fib.concat(fib[i - 1] + fib[i - 2]), [1, 1] ); const benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9] .map(val => [val, array .reduce( (sum, item) => sum + ( `${item}` [0] === `${val}` ), 0 ) / array.length, Math.log10(1 + 1 / val) ]); console.log(benford(fibseries(1000)))
1,107Benford's law
10javascript
1wnp7
package main import ( "fmt" "math/big" ) func b(n int) *big.Rat { var f big.Rat a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return f.Set(&a[0]) } func main() { for n := 0; n <= 60; n++ { if b := b(n); b.Num().BitLen() > 0 { fmt.Printf("B(%2d) =%45s/%s\n", n, b.Num(), b.Denom()) } } }
1,108Bernoulli numbers
0go
ba8kh
function to_binary () { if [ $1 -ge 0 ] then val=$1 binary_digits=() while [ $val -gt 0 ]; do bit=$((val % 2)) quotient=$((val / 2)) binary_digits+=("${bit}") val=$quotient done echo "${binary_digits[*]}" | rev else echo ERROR: "negative number" exit 1 fi } array=(5 50 9000) for number in "${array[@]}"; do echo $number ":> " $(to_binary $number) done
1,111Binary digits
4bash
x0nwb
import Data.Bits bitwise :: Int -> Int -> IO () bitwise a b = mapM_ print [ a .&. b , a .|. b , a `xor` b , complement a , shiftL a b , shiftR a b , shift a b , shift a (-b) , rotateL a b , rotateR a b , rotate a b , rotate a (-b) ] main :: IO () main = bitwise 255 170
1,103Bitwise operations
8haskell
3mjzj
import Data.Ratio import System.Environment main = getArgs >>= printM . defaultArg where defaultArg as = if null as then 60 else read (head as) printM m = mapM_ (putStrLn . printP) . takeWhile ((<= m) . fst) . filter (\(_, b) -> b /= 0 % 1) . zip [0 ..] $ bernoullis printP (i, r) = "B(" ++ show i ++ ") = " ++ show (numerator r) ++ "/" ++ show (denominator r) bernoullis = map head . iterate (ulli 1) . map berno $ enumFrom 0 where berno i = 1 % (i + 1) ulli _ [_] = [] ulli i (x:y:xs) = (i % 1) * (x - y): ulli (i + 1) (y: xs)
1,108Bernoulli numbers
8haskell
dzln4
import java.util.Random; public class BestShuffle { private final static Random rand = new Random(); public static void main(String[] args) { String[] words = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}; for (String w : words) System.out.println(bestShuffle(w)); } public static String bestShuffle(final String s1) { char[] s2 = s1.toCharArray(); shuffle(s2); for (int i = 0; i < s2.length; i++) { if (s2[i] != s1.charAt(i)) continue; for (int j = 0; j < s2.length; j++) { if (s2[i] != s2[j] && s2[i] != s1.charAt(j) && s2[j] != s1.charAt(i)) { char tmp = s2[i]; s2[i] = s2[j]; s2[j] = tmp; break; } } } return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")"; } public static void shuffle(char[] text) { for (int i = text.length - 1; i > 0; i--) { int r = rand.nextInt(i + 1); char tmp = text[i]; text[i] = text[r]; text[r] = tmp; } } private static int count(final String s1, final char[] s2) { int count = 0; for (int i = 0; i < s2.length; i++) if (s1.charAt(i) == s2[i]) count++; return count; } }
1,109Best shuffle
9java
mlgym
$s = undef; say 'Nothing to see here' if ! defined $s; say $s = ''; say 'Empty string' if $s eq ''; say $s = 'be'; say $t = $s; say 'Same' if $t eq $s; say $t = $t .'e' say $t .= 'keeper'; $t =~ s/ee/ook/; say $t; say $u = substr $t, 2, 2; say 'Oklahoma' . ' is ' . uc $u;
1,105Binary strings
2perl
jb87f
fn main() { let true_value = true; if true_value { println!(, true_value); } let false_value = false; if!false_value { println!(, false_value); } }
1,090Boolean values
14ruby
mlnyj
fn main() {
1,090Boolean values
15rust
92dmm
function Allocate_Bitmap( width, height ) local bitmap = {} for i = 1, width do bitmap[i] = {} for j = 1, height do bitmap[i][j] = {} end end return bitmap end function Fill_Bitmap( bitmap, color ) for i = 1, #bitmap do for j = 1, #bitmap[1] do bitmap[i][j] = color end end end function Get_Pixel( bitmap, x, y ) return bitmap[x][y] end
1,102Bitmap
1lua
if5ot
import java.math.BigInteger interface NumberGenerator { val numbers: Array<BigInteger> } class Benford(ng: NumberGenerator) { override fun toString() = str private val firstDigits = IntArray(9) private val count = ng.numbers.size.toDouble() private val str: String init { for (n in ng.numbers) { firstDigits[n.toString().substring(0, 1).toInt() - 1]++ } str = with(StringBuilder()) { for (i in firstDigits.indices) { append(i + 1).append('\t').append(firstDigits[i] / count) append('\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\n') } toString() } } } object FibonacciGenerator : NumberGenerator { override val numbers: Array<BigInteger> by lazy { val fib = Array<BigInteger>(1000, { BigInteger.ONE }) for (i in 2 until fib.size) fib[i] = fib[i - 2].add(fib[i - 1]) fib } } fun main(a: Array<String>) = println(Benford(FibonacciGenerator))
1,107Benford's law
11kotlin
5raua
function raze(a) {
1,109Best shuffle
10javascript
v4k25
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat
1,090Boolean values
16scala
25zlb
use utf8; my @names = ( "North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west", ); my @angles = (0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38); for (@angles) { my $i = int(($_ * 32 / 360) + .5) % 32; printf "%3d%18s%6.2f\n", $i + 1, $names[$i], $_; }
1,096Box the compass
2perl
hpyjl
def bellTriangle(n): tri = [None] * n for i in xrange(n): tri[i] = [0] * i tri[1][0] = 1 for i in xrange(2, n): tri[i][0] = tri[i - 1][i - 2] for j in xrange(1, i): tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] return tri def main(): bt = bellTriangle(51) print for i in xrange(1, 16): print % (i, bt[i][0]) print , bt[50][0] print print for i in xrange(1, 11): print bt[i] main()
1,106Bell numbers
3python
jb07p
(defn bsearch ([coll t] (bsearch coll 0 (dec (count coll)) t)) ([coll l u t] (if (> l u) -1 (let [m (quot (+ l u) 2) mth (nth coll m)] (cond (> mth t) (recur coll l (dec m) t) (< mth t) (recur coll (inc m) u t) (= mth t) m)))))
1,110Binary search
6clojure
f3cdm
actual = {} expected = {} for i = 1, 9 do actual[i] = 0 expected[i] = math.log10(1 + 1 / i) end n = 0 file = io.open("fibs1000.txt", "r") for line in file:lines() do digit = string.byte(line, 1) - 48 actual[digit] = actual[digit] + 1 n = n + 1 end file:close() print("digit actual expected") for i = 1, 9 do print(i, actual[i] / n, expected[i]) end
1,107Benford's law
1lua
47e5c
import org.apache.commons.math3.fraction.BigFraction; public class BernoulliNumbers { public static void main(String[] args) { for (int n = 0; n <= 60; n++) { BigFraction b = bernouilli(n); if (!b.equals(BigFraction.ZERO)) System.out.printf("B(%-2d) =%-1s%n", n , b); } } static BigFraction bernouilli(int n) { BigFraction[] A = new BigFraction[n + 1]; for (int m = 0; m <= n; m++) { A[m] = new BigFraction(1, (m + 1)); for (int j = m; j >= 1; j--) A[j - 1] = (A[j - 1].subtract(A[j])).multiply(new BigFraction(j)); } return A[0]; } }
1,108Bernoulli numbers
9java
so3q0
import java.util.Random object BestShuffle { operator fun invoke(s1: String) : String { val s2 = s1.toCharArray() s2.shuffle() for (i in s2.indices) if (s2[i] == s1[i]) for (j in s2.indices) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { val tmp = s2[i] s2[i] = s2[j] s2[j] = tmp break } return s1 + ' ' + String(s2) + " (" + s2.count(s1) + ')' } private fun CharArray.shuffle() { val rand = Random() for (i in size - 1 downTo 1) { val r = rand.nextInt(i + 1) val tmp = this[i] this[i] = this[r] this[r] = tmp } } private fun CharArray.count(s1: String) : Int { var count = 0 for (i in indices) if (s1[i] == this[i]) count++ return count } } fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }
1,109Best shuffle
11kotlin
t62f0
def bellTriangle(n) tri = Array.new(n) for i in 0 .. n - 1 do tri[i] = Array.new(i) for j in 0 .. i - 1 do tri[i][j] = 0 end end tri[1][0] = 1 for i in 2 .. n - 1 do tri[i][0] = tri[i - 1][i - 2] for j in 1 .. i - 1 do tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] end end return tri end def main bt = bellTriangle(51) puts for i in 1 .. 15 do puts % [i, bt[i][0]] end puts % [bt[50][0]] puts puts for i in 1 .. 10 do puts bt[i].inspect end end main()
1,106Bell numbers
14ruby
k1ohg
math.randomseed(os.time()) local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end local function bestshuffle(s, r) local order, shufl, count = {}, {}, 0 for ch in s:gmatch(".") do order[#order+1], shufl[#shufl+1] = ch, ch end if r then shuffle(shufl) end for i = 1, #shufl do for j = 1, #shufl do if i ~= j and shufl[i] ~= order[j] and shufl[j] ~= order[i] then shufl[i], shufl[j] = shufl[j], shufl[i] end end end for i = 1, #shufl do if shufl[i] == order[i] then count = count + 1 end end return table.concat(shufl), count end local words = { "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" } local function test(r) print(r and "RANDOM:" or "DETERMINISTIC:") for _, word in ipairs(words) do local shufl, count = bestshuffle(word, r) print(string.format("%s,%s, (%d)", word, shufl, count)) end print() end test(true) test(false)
1,109Best shuffle
1lua
zyvty
use strict; use Image::Imlib2; sub my_draw_line { my ( $img, $x0, $y0, $x1, $y1) = @_; my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { ( $y0, $x0 ) = ( $x0, $y0); ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { ( $x1, $x0 ) = ( $x0, $x1 ); ( $y1, $y0 ) = ( $y0, $y1 ); } my $deltax = $x1 - $x0; my $deltay = abs($y1 - $y0); my $error = $deltax / 2; my $ystep; my $y = $y0; my $x; $ystep = ( $y0 < $y1 ) ? 1 : -1; for( $x = $x0; $x <= $x1; $x += 1 ) { if ( $steep ) { $img->draw_point($y, $x); } else { $img->draw_point($x, $y); } $error -= $deltay; if ( $error < 0 ) { $y += $ystep; $error += $deltax; } } } my $img = Image::Imlib2->new(160, 160); $img->set_color(255, 255, 255, 255); $img->fill_rectangle(0,0,160,160); $img->set_color(0,0,0,255); my_draw_line($img, 10, 80, 80, 160); my_draw_line($img, 80, 160, 160, 80); my_draw_line($img, 160, 80, 80, 10); my_draw_line($img, 80, 10, 10, 80); $img->save("test0.png"); $img->set_color(255, 255, 255, 255); $img->fill_rectangle(0,0,160,160); $img->set_color(0,0,0,255); $img->draw_line(10, 80, 80, 160); $img->draw_line(80, 160, 160, 80); $img->draw_line(160, 80, 80, 10); $img->draw_line(80, 10, 10, 80); $img->save("test1.png"); exit 0;
1,100Bitmap/Bresenham's line algorithm
2perl
q82x6
public static void bitwise(int a, int b){ System.out.println("a AND b: " + (a & b)); System.out.println("a OR b: "+ (a | b)); System.out.println("a XOR b: "+ (a ^ b)); System.out.println("NOT a: " + ~a); System.out.println("a << b: " + (a << b));
1,103Bitwise operations
9java
ifuos
use num::BigUint; fn main() { let bt = bell_triangle(51);
1,106Bell numbers
15rust
baikx
import scala.collection.mutable.ListBuffer object BellNumbers { class BellTriangle { val arr: ListBuffer[Int] = ListBuffer.empty[Int] def this(n: Int) { this() val length = n * (n + 1) / 2 for (_ <- 0 until length) { arr += 0 } this (1, 0) = 1 for (i <- 2 to n) { this (i, 0) = this (i - 1, i - 2) for (j <- 1 until i) { this (i, j) = this (i, j - 1) + this (i - 1, j - 1) } } } private def index(row: Int, col: Int): Int = { require(row > 0, "row must be greater than zero") require(col >= 0, "col must not be negative") require(col < row, "col must be less than row") row * (row - 1) / 2 + col } def apply(row: Int, col: Int): Int = { val i = index(row, col) arr(i) } def update(row: Int, col: Int, value: Int): Unit = { val i = index(row, col) arr(i) = value } } def main(args: Array[String]): Unit = { val rows = 15 val bt = new BellTriangle(rows) println("First fifteen Bell numbers:") for (i <- 0 until rows) { printf("%2d:%d\n", i + 1, bt(i + 1, 0)) } for (i <- 1 to 10) { print(bt(i, 0)) for (j <- 1 until i) { print(s", ${bt(i, j)}") } println() } } }
1,106Bell numbers
16scala
axf1n
import org.apache.commons.math3.fraction.BigFraction object Bernoulli { operator fun invoke(n: Int) : BigFraction { val A = Array(n + 1, init) for (m in 0..n) for (j in m downTo 1) A[j - 1] = A[j - 1].subtract(A[j]).multiply(integers[j]) return A.first() } val max = 60 private val init = { m: Int -> BigFraction(1, m + 1) } private val integers = Array(max + 1, { m: Int -> BigFraction(m) } ) } fun main(args: Array<String>) { for (n in 0..Bernoulli.max) if (n % 2 == 0 || n == 1) System.out.printf("B(%-2d) =%-1s%n", n, Bernoulli(n)) }
1,108Bernoulli numbers
11kotlin
axn13
s1 = s2 = 'You may use any of \' or This text goes over several lines up to the closing triple quote"
1,105Binary strings
3python
hpojw
% if {""} then {puts true} else {puts false} expected boolean value but got ""
1,090Boolean values
17swift
yci6e
function bitwise(a, b){ alert("a AND b: " + (a & b)); alert("a OR b: "+ (a | b)); alert("a XOR b: "+ (a ^ b)); alert("NOT a: " + ~a); alert("a << b: " + (a << b));
1,103Bitwise operations
10javascript
zy7t2
#!/usr/bin/env luajit local gmp = require 'gmp' ('libgmp') local ffi = require'ffi' local mpz, mpq = gmp.types.z, gmp.types.q local function mpq_for(buf, op, n) for i=0,n-1 do op(buf[i]) end end local function bernoulli(rop, n) local a=ffi.new("mpq_t[?]", n+1) mpq_for(a, gmp.q_init, n+1) for m=0,n do gmp.q_set_ui(a[m],1, m+1) for j=m,1,-1 do gmp.q_sub(a[j-1], a[j], a[j-1]) gmp.q_set_ui(rop, j, 1) gmp.q_mul(a[j-1], a[j-1], rop) end end gmp.q_set(rop,a[0]) mpq_for(a, gmp.q_clear, n+1) end do
1,108Bernoulli numbers
1lua
eqdac