code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
public struct BellTriangle<T: BinaryInteger> {
@usableFromInline
var arr: [T]
@inlinable
public internal(set) subscript(row row: Int, col col: Int) -> T {
get { arr[row * (row - 1) / 2 + col] }
set { arr[row * (row - 1) / 2 + col] = newValue }
}
@inlinable
public init(n: Int) {
arr = Array(repeating: 0, count: n * (n + 1) / 2)
self[row: 1, col: 0] = 1
for i in 2...n {
self[row: i, col: 0] = self[row: i - 1, col: i - 2]
for j in 1..<i {
self[row: i, col: j] = self[row: i, col: j - 1] + self[row: i - 1, col: j - 1]
}
}
}
}
let tri = BellTriangle<Int>(n: 15)
print("First 15 Bell numbers:")
for i in 1...15 {
print("\(i): \(tri[row: i, col: 0])")
}
for i in 1...10 {
print(tri[row: i, col: 0], terminator: "")
for j in 1..<i {
print(", \(tri[row: i, col: j])", terminator: "")
}
print()
} | 1,106Bell numbers
| 17swift
| hp8j0 |
majors = 'north east south west'.split()
majors *= 2
quarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',')
quarter2 = [p.replace('NE','EN') for p in quarter1]
def degrees2compasspoint(d):
d = (d% 360) + 360/64
majorindex, minor = divmod(d, 90.)
majorindex = int(majorindex)
minorindex = int( (minor*4)
p1, p2 = majors[majorindex: majorindex+2]
if p1 in {'north', 'south'}:
q = quarter1
else:
q = quarter2
return q[minorindex].replace('N', p1).replace('E', p2).capitalize()
if __name__ == '__main__':
for i in range(33):
d = i * 11.25
m = i% 3
if m == 1: d += 5.62
elif m == 2: d -= 5.62
n = i% 32 + 1
print( '%2i%-18s%7.2f'% (n, degrees2compasspoint(d), d) ) | 1,096Box the compass
| 3python
| k1mhf |
infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance)
infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance)
fun main(args: Array<String>) { | 1,103Bitwise operations
| 11kotlin
| q89x1 |
use strict;
use Image::Imlib2;
my $img = Image::Imlib2->new(200,200);
$img->set_color(255, 0, 0, 255);
$img->fill_rectangle(0,0, 200, 200);
$img->set_color(0, 255, 0, 255);
$img->draw_point(40,40);
my ($red, $green, $blue, $alpha) = $img->query_pixel(40,40);
undef $img;
my $col = pack("CCCC", 255, 255, 0, 0);
my $img = Image::Imlib2->new_using_data(200, 200, $col x (200 * 200));
exit 0; | 1,102Bitmap
| 2perl
| gj84e |
use strict ;
use warnings ;
use POSIX qw( log10 ) ;
my @fibonacci = ( 0 , 1 ) ;
while ( @fibonacci != 1000 ) {
push @fibonacci , $fibonacci[ -1 ] + $fibonacci[ -2 ] ;
}
my @actuals ;
my @expected ;
for my $i( 1..9 ) {
my $sum = 0 ;
map { $sum++ if $_ =~ /\A$i/ } @fibonacci ;
push @actuals , $sum / 1000 ;
push @expected , log10( 1 + 1/$i ) ;
}
print " Observed Expected\n" ;
for my $i( 1..9 ) {
print "$i: " ;
my $result = sprintf ( "%.2f" , 100 * $actuals[ $i - 1 ] ) ;
printf "%11s%%" , $result ;
$result = sprintf ( "%.2f" , 100 * $expected[ $i - 1 ] ) ;
printf "%15s%%\n" , $result ;
} | 1,107Benford's law
| 2perl
| od98x |
use strict;
use warnings;
use List::Util qw(shuffle);
use Algorithm::Permute;
best_shuffle($_) for qw(abracadabra seesaw elk grrrrrr up a);
sub best_shuffle {
my ($original_word) = @_;
my $best_word = $original_word;
my $best_score = length $best_word;
my @shuffled = shuffle split //, $original_word;
my $iterator = Algorithm::Permute->new(\@shuffled);
while( my @array = $iterator->next ) {
my $word = join '', @array;
my $score = ($original_word ^ $word) =~ tr/\x00//;
next if $score >= $best_score;
($best_word, $best_score) = ($word, $score);
last if $score == 0;
}
print "$original_word, $best_word, $best_score\n";
} | 1,109Best shuffle
| 2perl
| k1shc |
char* bin2str(unsigned value, char* buffer)
{
const unsigned N_DIGITS = sizeof(unsigned) * 8;
unsigned mask = 1 << (N_DIGITS - 1);
char* ptr = buffer;
for (int i = 0; i < N_DIGITS; i++)
{
*ptr++ = '0' + !!(value & mask);
mask >>= 1;
}
*ptr = '\0';
for (ptr = buffer; *ptr == '0'; ptr++)
;
return ptr;
}
char* bin2strNaive(unsigned value, char* buffer)
{
unsigned n, m, p;
n = 0;
p = 1;
while (p <= value / 2)
{
n = n + 1;
p = p * 2;
}
m = 0;
while (n > 0)
{
buffer[m] = '0' + value / p;
value = value % p;
m = m + 1;
n = n - 1;
p = p / 2;
}
buffer[m + 1] = '\0';
return buffer;
}
int main(int argc, char* argv[])
{
const unsigned NUMBERS[] = { 5, 50, 9000 };
const int RADIX = 2;
char buffer[(sizeof(unsigned)*8 + 1)];
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
itoa(value, buffer, RADIX);
printf(, value, buffer);
}
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf(, value, bin2str(value, buffer));
}
for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
{
unsigned value = NUMBERS[i];
printf(, value, bin2strNaive(value, buffer));
}
return EXIT_SUCCESS;
} | 1,111Binary digits
| 5c
| sofq5 |
x =
x = nil
x =
x.length
if x ==
puts
else
puts
end
y = 'bc'
if x < y
puts
end
xx = x.dup
x == xx
x.equal?(xx)
if x.empty?
puts
end
p x <<
p xx = x[0..-2]
x[1,2] =
p x
p y = .tr(, )
a =
b =
c =
p d = a + b + c | 1,105Binary strings
| 14ruby
| bankq |
class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
print_r($b->getPixel(3,3)); | 1,102Bitmap
| 12php
| nt4ig |
foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w)
echo bestShuffle($w) . '<br>';
function bestShuffle($s1) {
$s2 = str_shuffle($s1);
for ($i = 0; $i < strlen($s2); $i++) {
if ($s2[$i] != $s1[$i]) continue;
for ($j = 0; $j < strlen($s2); $j++)
if ($i != $j && $s2[$i] != $s1[$j] && $s2[$j] != $s1[$i]) {
$t = $s2[$i];
$s2[$i] = $s2[$j];
$s2[$j] = $t;
break;
}
}
return . countSame($s1, $s2);
}
function countSame($s1, $s2) {
$cnt = 0;
for ($i = 0; $i < strlen($s2); $i++)
if ($s1[$i] == $s2[$i])
$cnt++;
return ;
} | 1,109Best shuffle
| 12php
| 3muzq |
use std::str;
fn main() { | 1,105Binary strings
| 15rust
| pedbu |
def line(self, x0, y0, x1, y1):
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x, y = x0, y0
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
if dx > dy:
err = dx / 2.0
while x != x1:
self.set(x, y)
err -= dy
if err < 0:
y += sy
err += dx
x += sx
else:
err = dy / 2.0
while y != y1:
self.set(x, y)
err -= dx
if err < 0:
x += sx
err += dy
y += sy
self.set(x, y)
Bitmap.line = line
bitmap = Bitmap(17,17)
for points in ((1,8,8,16),(8,16,16,8),(16,8,8,1),(8,1,1,8)):
bitmap.line(*points)
bitmap.chardisplay()
'''
The origin, 0,0; is the lower left, with x increasing to the right,
and Y increasing upwards.
The chardisplay above produces the following output:
+-----------------+
| @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @|
| @ @ |
| @ @ |
| @ @@ |
| @ @ |
| @ @ |
| @ @ |
| @ |
| |
+-----------------+
''' | 1,100Bitmap/Bresenham's line algorithm
| 3python
| sovq9 |
use strict;
use warnings;
use List::Util qw(max);
use Math::BigRat;
my $one = Math::BigRat->new(1);
sub bernoulli_print {
my @a;
for my $m ( 0 .. 60 ) {
push @a, $one / ($m + 1);
for my $j ( reverse 1 .. $m ) {
( $a[$j-1] -= $a[$j] ) *= $j;
}
next unless $a[0];
printf "B(%2d) =%44s/%s\n", $m, $a[0]->parts;
}
}
bernoulli_print(); | 1,108Bernoulli numbers
| 2perl
| 927mn |
(Integer/toBinaryString 5)
(Integer/toBinaryString 50)
(Integer/toBinaryString 9000) | 1,111Binary digits
| 6clojure
| ntyik |
Headings = %w(north east south west north).each_cons(2).flat_map do |a, b|
[a,
,
,
,
,
,
,
]
end
Headings.prepend nil
def heading(degrees)
i = degrees.quo(360).*(32).round.%(32).+(1)
[i, Headings[i]]
end
angles = (0..32).map { |i| i * 11.25 + [0, 5.62, -5.62][i % 3] }
angles.each do |degrees|
index, name = heading degrees
printf , index, name.center(20), degrees
end | 1,096Box the compass
| 14ruby
| pecbh |
getClass(, package=pixmap)
pixmapIndexed
plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col=))
cols <- rep(, 12); cols[7] <-
plot(p2 <- pixmapIndexed(matrix(1:12, nrow=3, ncol=4), col=cols))
getcol <- function(pm, i, j)
{
pmcol <- pm@col
dim(pmcol) <- dim(pm@index)
pmcol[i,j]
}
getcol(p2, 3, 4) | 1,102Bitmap
| 3python
| rhogq |
getClass("pixmapIndexed", package=pixmap)
pixmapIndexed
plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col="red"))
cols <- rep("blue", 12); cols[7] <- "red"
plot(p2 <- pixmapIndexed(matrix(1:12, nrow=3, ncol=4), col=cols))
getcol <- function(pm, i, j)
{
pmcol <- pm@col
dim(pmcol) <- dim(pm@index)
pmcol[i,j]
}
getcol(p2, 3, 4) | 1,102Bitmap
| 13r
| ugqvx |
from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k for k in count(0))
def heads(s):
for a in s: yield int(str(a)[0])
def show_dist(title, s):
c = Counter(s)
size = sum(c.values())
res = [c[d]/size for d in range(1,10)]
print(% title)
for r, e in zip(res, expected):
print(% (r*100., e*100., abs(r - e)*100.))
def rand1000():
while True: yield randint(1,9999)
if __name__ == '__main__':
show_dist(, islice(heads(fib()), 1000))
show_dist(, islice(heads(power_of_threes()), 1000))
show_dist(, islice(heads(rand1000()), 10000)) | 1,107Benford's law
| 3python
| ifcof |
from fractions import Fraction as Fr
def bernoulli(n):
A = [0] * (n+1)
for m in range(n+1):
A[m] = Fr(1, m+1)
for j in range(m, 0, -1):
A[j-1] = j*(A[j-1] - A[j])
return A[0]
bn = [(i, bernoulli(i)) for i in range(61)]
bn = [(i, b) for i,b in bn if b]
width = max(len(str(b.numerator)) for i,b in bn)
for i,b in bn:
print('B(%2i) =%*i/%i'% (i, width, b.numerator, b.denominator)) | 1,108Bernoulli numbers
| 3python
| cvj9q |
local bit = require"bit"
local vb = {
0, 1, -1, 2, -2, 0x12345678, 0x87654321,
0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55,
0x7fffffff, 0x80000000, 0xffffffff
}
local function cksum(name, s, r)
local z = 0
for i=1,#s do z = (z + string.byte(s, i)*i) % 2147483629 end
if z ~= r then
error("bit."..name.." test failed (got "..z..", expected "..r..")", 0)
end
end
local function check_unop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do s = s..","..tostring(f(x)) end
cksum(name, s, r)
end
local function check_binop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for _,y in ipairs(vb) do s = s..","..tostring(f(x, y)) end
end
cksum(name, s, r)
end
local function check_binop_range(name, r, yb, ye)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) or pcall(f, 1, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for y=yb,ye do s = s..","..tostring(f(x, y)) end
end
cksum(name, s, r)
end
local function check_shift(name, r)
check_binop_range(name, r, 0, 31)
end | 1,103Bitwise operations
| 1lua
| socq8 |
pbenford <- function(d){
return(log10(1+(1/d)))
}
get_lead_digit <- function(number){
return(as.numeric(substr(number,1,1)))
}
fib_iter <- function(n){
first <- 1
second <- 0
for(i in 1:n){
sum <- first + second
first <- second
second <- sum
}
return(sum)
}
fib_sequence <- mapply(fib_iter,c(1:1000))
lead_digits <- mapply(get_lead_digit,fib_sequence)
observed_frequencies <- table(lead_digits)/1000
expected_frequencies <- mapply(pbenford,c(1:9))
data <- data.frame(observed_frequencies,expected_frequencies)
colnames(data) <- c("digit","obs.frequency","exp.frequency")
dev_percentage <- abs((data$obs.frequency-data$exp.frequency)*100)
data <- data.frame(data,dev_percentage)
print(data) | 1,107Benford's law
| 13r
| so6qy |
library(pracma)
for (idx in c(1,2*0:30)) {
b <- bernoulli(idx)
d <- as.character(denominator(b))
n <- as.character(numerator(b))
cat("B(",idx,") = ",n,"/",d,"\n", sep = "")
} | 1,108Bernoulli numbers
| 13r
| 6943e |
import random
def count(w1,wnew):
return sum(c1==c2 for c1,c2 in zip(w1, wnew))
def best_shuffle(w):
wnew = list(w)
n = len(w)
rangelists = (list(range(n)), list(range(n)))
for r in rangelists:
random.shuffle(r)
rangei, rangej = rangelists
for i in rangei:
for j in rangej:
if i != j and wnew[j] != wnew[i] and w[i] != wnew[j] and w[j] != wnew[i]:
wnew[j], wnew[i] = wnew[i], wnew[j]
break
wnew = ''.join(wnew)
return wnew, count(w, wnew)
if __name__ == '__main__':
test_words = ('tree abracadabra seesaw elk grrrrrr up a '
+ 'antidisestablishmentarianism hounddogs').split()
test_words += ['aardvarks are ant eaters', 'immediately', 'abba']
for w in test_words:
wnew, c = best_shuffle(w)
print(% (w, wnew, c)) | 1,109Best shuffle
| 3python
| ba0kr |
Pixel = Struct.new(:x, :y)
class Pixmap
def draw_line(p1, p2, colour)
validate_pixel(p1.x, p2.y)
validate_pixel(p2.x, p2.y)
x1, y1 = p1.x, p1.y
x2, y2 = p2.x, p2.y
steep = (y2 - y1).abs > (x2 - x1).abs
if steep
x1, y1 = y1, x1
x2, y2 = y2, x2
end
if x1 > x2
x1, x2 = x2, x1
y1, y2 = y2, y1
end
deltax = x2 - x1
deltay = (y2 - y1).abs
error = deltax / 2
ystep = y1 < y2? 1: -1
y = y1
x1.upto(x2) do |x|
pixel = steep? [y,x]: [x,y]
self[*pixel] = colour
error -= deltay
if error < 0
y += ystep
error += deltax
end
end
end
end
bitmap = Pixmap.new(500, 500)
bitmap.fill(RGBColour::BLUE)
10.step(430, 60) do |a|
bitmap.draw_line(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW)
bitmap.draw_line(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW)
end
bitmap.draw_line(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW) | 1,100Bitmap/Bresenham's line algorithm
| 14ruby
| 8n501 |
fn expand(cp: &str) -> String {
let mut out = String::new();
for c in cp.chars() {
out.push_str(match c {
'N' => "north",
'E' => "east",
'S' => "south",
'W' => "west",
'b' => " by ",
_ => "-",
});
}
out
}
fn main() {
let cp = [
"N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN",
"E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE",
"S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS",
"W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW"
];
println!("Index Degrees Compass point");
println!("----- ------- -------------");
for i in 0..=32 {
let index = i% 32;
let heading = i as f32 * 11.25
+ match i% 3 {
1 => 5.62,
2 => -5.62,
_ => 0.0,
};
println!(
"{:2} {:6.2} {}",
index + 1,
heading,
expand(cp[index])
);
}
} | 1,096Box the compass
| 15rust
| 1wlpu |
struct Point {
x: i32,
y: i32
}
fn main() {
let mut points: Vec<Point> = Vec::new();
points.append(&mut get_coordinates(1, 20, 20, 28));
points.append(&mut get_coordinates(20, 28, 69, 0));
draw_line(points, 70, 30);
}
fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> {
let mut coordinates: Vec<Point> = vec![];
let dx:i32 = i32::abs(x2 - x1);
let dy:i32 = i32::abs(y2 - y1);
let sx:i32 = { if x1 < x2 { 1 } else { -1 } };
let sy:i32 = { if y1 < y2 { 1 } else { -1 } };
let mut error:i32 = (if dx > dy { dx } else { -dy }) / 2;
let mut current_x:i32 = x1;
let mut current_y:i32 = y1;
loop {
coordinates.push(Point { x: current_x, y: current_y });
if current_x == x2 && current_y == y2 { break; }
let error2:i32 = error;
if error2 > -dx {
error -= dy;
current_x += sx;
}
if error2 < dy {
error += dx;
current_y += sy;
}
}
coordinates
}
fn draw_line(line: std::vec::Vec<Point>, width: i32, height: i32) {
for col in 0..height {
for row in 0..width {
let is_point_in_line = line.iter().any(| point| point.x == row && point.y == col);
match is_point_in_line {
true => print!("@"),
_ => print!(".")
};
}
print!("\n");
}
} | 1,100Bitmap/Bresenham's line algorithm
| 15rust
| od483 |
object BoxingTheCompass extends App {
val cardinal = List("north", "east", "south", "west")
val pointDesc = List("1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1")
val pointDeg: Int => Double = i => {
val fswitch: Int => Int = i => i match {case 1 => 1; case 2 => -1; case _ => 0}
i*11.25+fswitch(i%3)*5.62
}
val deg2ind: Double => Int = deg => (deg*32/360+.5).toInt%32+1
val pointName: Int => String = ind => {
val i = ind - 1
val str1 = cardinal(i%32/8)
val str2 = cardinal((i%32/8+1)%4)
val strC = if ((str1 == "north") || (str1 == "south")) str1+str2 else str2+str1
pointDesc(i%32%8).replace("1", str1).replace("2", str2).replace("C", strC).capitalize
}
(0 to 32).map(i=>Triple(pointDeg(i),deg2ind(pointDeg(i)),pointName(deg2ind(pointDeg(i)))))
.map{t=>(printf("%s\t%18s\t%s\n",t._2,t._3,t._1))}
} | 1,096Box the compass
| 16scala
| wsues |
class RGBColour
def initialize(red, green, blue)
unless red.between?(0,255) and green.between?(0,255) and blue.between?(0,255)
raise ArgumentError,
end
@red, @green, @blue = red, green, blue
end
attr_reader :red, :green, :blue
alias_method :r, :red
alias_method :g, :green
alias_method :b, :blue
RED = RGBColour.new(255,0,0)
GREEN = RGBColour.new(0,255,0)
BLUE = RGBColour.new(0,0,255)
BLACK = RGBColour.new(0,0,0)
WHITE = RGBColour.new(255,255,255)
end
class Pixmap
def initialize(width, height)
@width = width
@height = height
@data = fill(RGBColour::WHITE)
end
attr_reader :width, :height
def fill(colour)
@data = Array.new(@width) {Array.new(@height, colour)}
end
def validate_pixel(x,y)
unless x.between?(0, @width-1) and y.between?(0, @height-1)
raise ArgumentError,
end
end
def [](x,y)
validate_pixel(x,y)
@data[x][y]
end
alias_method :get_pixel,:[]
def []=(x,y,colour)
validate_pixel(x,y)
@data[x][y] = colour
end
alias_method :set_pixel,:[]=
end | 1,102Bitmap
| 14ruby
| jbn7x |
object BitmapOps {
def bresenham(bm:RgbBitmap, x0:Int, y0:Int, x1:Int, y1:Int, c:Color)={
val dx=math.abs(x1-x0)
val sx=if (x0<x1) 1 else -1
val dy=math.abs(y1-y0)
val sy=if (y0<y1) 1 else -1
def it=new Iterator[Tuple2[Int,Int]]{
var x=x0; var y=y0
var err=(if (dx>dy) dx else -dy)/2
def next={
val res=(x,y)
val e2=err;
if (e2 > -dx) {err-=dy; x+=sx}
if (e2<dy) {err+=dx; y+=sy}
res;
}
def hasNext = (sx*x <= sx*x1 && sy*y <= sy*y1)
}
for((x,y) <- it)
bm.setPixel(x, y, c)
}
} | 1,100Bitmap/Bresenham's line algorithm
| 16scala
| dz7ng |
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub fn new(r: u8, g: u8, b: u8) -> Self {
Rgb { r, g, b }
}
pub const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 };
pub const RED: Rgb = Rgb { r: 255, g: 0, b: 0 };
pub const GREEN: Rgb = Rgb { r: 0, g: 255, b: 0 };
pub const BLUE: Rgb = Rgb { r: 0, g: 0, b: 255 };
}
#[derive(Clone, Debug)]
pub struct Image {
width: usize,
height: usize,
pixels: Vec<Rgb>,
}
impl Image {
pub fn new(width: usize, height: usize) -> Self {
Image {
width,
height,
pixels: vec![Rgb::BLACK; width * height],
}
}
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
pub fn fill(&mut self, color: Rgb) {
for pixel in &mut self.pixels {
*pixel = color;
}
}
pub fn get(&self, row: usize, col: usize) -> Option<&Rgb> {
if row >= self.width {
return None;
}
self.pixels.get(row * self.width + col)
}
pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut Rgb> {
if row >= self.width {
return None;
}
self.pixels.get_mut(row * self.width + col)
}
}
fn main() {
let mut image = Image::new(16, 9);
assert_eq!(Some(&Rgb::BLACK), image.get(3, 4));
assert!(image.get(22, 3).is_none());
image.fill(Rgb::RED);
assert_eq!(Some(&Rgb::RED), image.get(3, 4));
if let Some(pixel) = image.get_mut(3, 4) {
*pixel = Rgb::GREEN;
}
assert_eq!(Some(&Rgb::GREEN), image.get(3, 4));
if let Some(pixel) = image.get_mut(3, 4) {
pixel.g -= 100;
pixel.b = 20;
}
assert_eq!(Some(&Rgb::new(0, 155, 20)), image.get(3, 4));
} | 1,102Bitmap
| 15rust
| hpdj2 |
import java.awt.image.BufferedImage
import java.awt.Color
class RgbBitmap(val width:Int, val height:Int) {
val image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def fill(c:Color)={
val g=image.getGraphics()
g.setColor(c)
g.fillRect(0, 0, width, height)
}
def setPixel(x:Int, y:Int, c:Color)=image.setRGB(x, y, c.getRGB())
def getPixel(x:Int, y:Int)=new Color(image.getRGB(x, y))
} | 1,102Bitmap
| 16scala
| pezbj |
EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}
def fib(n)
a,b = 0,1
n.times.map{ret, a, b = a, b, a+b; ret}
end
def power_of_threes(n)
n.times.map{|k| 3**k}
end
def heads(s)
s.map{|a| a.to_s[0].to_i}
end
def show_dist(title, s)
s = heads(s)
c = Array.new(10, 0)
s.each{|x| c[x] += 1}
size = s.size.to_f
res = (1..9).map{|d| c[d]/size}
puts % title
res.zip(EXPECTED).each.with_index(1) do |(r, e), i|
puts % [i, r*100, e*100, (r - e).abs*100]
end
end
def random(n)
n.times.map{rand(1..n)}
end
show_dist(, fib(1000))
show_dist(, power_of_threes(1000))
show_dist(, random(10000)) | 1,107Benford's law
| 14ruby
| dz2ns |
def best_shuffle(s)
pos = []
g = s.length.times.group_by { |i| s[i] }
k = g.sort_by { |k, v| v.length }.map { |k, v| k }
until g.empty?
k.each do |letter|
g[letter] or next
pos.push(g[letter].pop)
g[letter].empty? and g.delete letter
end
end
letters = s.dup
new = * s.length
until letters.empty?
i, p = 0, pos.pop
i += 1 while letters[i] == s[p] and i < (letters.length - 1)
new[p] = letters.slice! i
end
score = new.chars.zip(s.chars).count { |c, d| c == d }
[new, score]
end
%w(abracadabra seesaw elk grrrrrr up a).each do |word|
puts % [word, *best_shuffle(word)]
end | 1,109Best shuffle
| 14ruby
| 1wopw |
extern crate num_traits;
extern crate num;
use num::bigint::{BigInt, ToBigInt};
use num_traits::{Zero, One};
use std::collections::HashMap; | 1,107Benford's law
| 15rust
| f3vd6 |
bernoulli = Enumerator.new do |y|
ar = []
0.step do |m|
ar << Rational(1, m+1)
m.downto(1){|j| ar[j-1] = j*(ar[j-1] - ar[j]) }
y << ar.first
end
end
b_nums = bernoulli.take(61)
width = b_nums.map{|b| b.numerator.to_s.size}.max
b_nums.each_with_index {|b,i| puts % [i, width, b.numerator, b.denominator] unless b.zero? } | 1,108Bernoulli numbers
| 14ruby
| 25klw |
extern crate permutohedron;
extern crate rand;
use std::cmp::{min, Ordering};
use std::env;
use rand::{thread_rng, Rng};
use std::str;
const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];
#[derive(Eq)]
struct Solution {
original: String,
shuffled: String,
score: usize,
} | 1,109Best shuffle
| 15rust
| axi14 |
null | 1,107Benford's law
| 16scala
| 3m4zy |
null | 1,108Bernoulli numbers
| 15rust
| v4b2t |
def coincidients(s1: Seq[Char], s2: Seq[Char]): Int = (s1, s2).zipped.count(p => (p._1 == p._2))
def freqMap(s1: List[Char]) = s1.groupBy(_.toChar).mapValues(_.size)
def estimate(s1: List[Char]): Int = if (s1 == Nil) 0 else List(0, freqMap(s1).maxBy(_._2)._2 - (s1.size / 2)).max
def bestShuffle(s: String): Pair[String, Int] = {
if (s == "") return ("", 0) else {}
val charList = s.toList
val estim = estimate(charList) | 1,109Best shuffle
| 16scala
| x0fwg |
String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
if(n==0) return "0";
String res="";
while(n>0) {
res=(n%2).toString()+res;
n=(n/2).toInt();
}
return res;
}
main() {
print(binary(0));
print(binary(1));
print(binary(5));
print(binary(10));
print(binary(50));
print(binary(9000));
print(binary(65535));
print(binary(0xaa5511ff));
print(binary(0x123456789abcde)); | 1,111Binary digits
| 18dart
| 1w0p0 |
case class BFraction( numerator:BigInt, denominator:BigInt ) {
require( denominator != BigInt(0), "Denominator cannot be zero" )
val gcd = numerator.gcd(denominator)
val num = numerator / gcd
val den = denominator / gcd
def unary_- = BFraction(-num, den)
def -( that:BFraction ) = that match {
case f if f.num == BigInt(0) => this
case f if f.den == this.den => BFraction(this.num - f.num, this.den)
case f => BFraction(((this.num * f.den) - (f.num * this.den)), this.den * f.den )
}
def *( that:Int ) = BFraction( num * that, den )
override def toString = num + " / " + den
}
def bernoulliB( n:Int ) : BFraction = {
val aa : Array[BFraction] = Array.ofDim(n+1)
for( m <- 0 to n ) {
aa(m) = BFraction(1,(m+1))
for( n <- m to 1 by -1 ) {
aa(n-1) = (aa(n-1) - aa(n)) * n
}
}
aa(0)
}
assert( {val b12 = bernoulliB(12); b12.num == -691 && b12.den == 2730 } )
val r = for( n <- 0 to 60; b = bernoulliB(n) if b.num != 0 ) yield (n, b)
val numeratorSize = r.map(_._2.num.toString.length).max | 1,108Bernoulli numbers
| 16scala
| 47a50 |
func binarySearch(a []float64, value float64, low int, high int) int {
if high < low {
return -1
}
mid := (low + high) / 2
if a[mid] > value {
return binarySearch(a, value, low, mid-1)
} else if a[mid] < value {
return binarySearch(a, value, mid+1, high)
}
return mid
} | 1,110Binary search
| 0go
| 5rbul |
-- Create table
CREATE TABLE benford (num INTEGER);
-- Seed table
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (2);
-- Populate table
INSERT INTO benford (num)
SELECT
ult + penult
FROM
(SELECT MAX(num) AS ult FROM benford),
(SELECT MAX(num) AS penult FROM benford WHERE num NOT IN (SELECT MAX(num) FROM benford))
-- Repeat as many times as desired
-- in Oracle SQL*Plus, press a lot of times
-- or wrap this in a loop, but that will require something db-specific...
-- Do sums
SELECT
digit,
COUNT(digit) / numbers AS actual,
log(10, 1 + 1 / digit) AS expected
FROM
(
SELECT
FLOOR(num/POWER(10,LENGTH(num)-1)) AS digit
FROM
benford
),
(
SELECT
COUNT(*) AS numbers
FROM
benford
)
GROUP BY digit, numbers
ORDER BY digit;
-- Tidy up
DROP TABLE benford; | 1,107Benford's law
| 19sql
| ml7yl |
def binSearchR | 1,110Binary search
| 7groovy
| cvr9i |
import Foundation
func readFromFile(fileName file:String) -> String{
var ret:String = ""
let path = Foundation.URL(string: "file: | 1,107Benford's law
| 17swift
| ntlil |
import Data.Array (Array, Ix, (!), listArray, bounds)
bSearch
:: Integral a
=> (a -> Ordering) -> (a, a) -> Maybe a
bSearch p (low, high)
| high < low = Nothing
| otherwise =
let mid = (low + high) `div` 2
in case p mid of
LT -> bSearch p (low, mid - 1)
GT -> bSearch p (mid + 1, high)
EQ -> Just mid
bSearchArray
:: (Ix i, Integral i, Ord e)
=> Array i e -> e -> Maybe i
bSearchArray a x = bSearch (compare x . (a !)) (bounds a)
axs
:: (Num i, Ix i)
=> Array i String
axs =
listArray
(0, 11)
[ "alpha"
, "beta"
, "delta"
, "epsilon"
, "eta"
, "gamma"
, "iota"
, "kappa"
, "lambda"
, "mu"
, "theta"
, "zeta"
]
main :: IO ()
main =
let e = "mu"
found = bSearchArray axs e
in putStrLn $
'\'':
e ++
case found of
Nothing -> "' Not found"
Just x -> "' found at index " ++ show x | 1,110Binary search
| 8haskell
| x0dw4 |
import BigInt
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> {
guard n!= 0 else {
return 1
}
var arr = [Frac<T>]()
for m in 0...n {
arr.append(Frac(numerator: 1, denominator: T(m) + 1))
for j in stride(from: m, through: 1, by: -1) {
arr[j-1] = (arr[j-1] - arr[j]) * Frac(numerator: T(j), denominator: 1)
}
}
return arr[0]
}
for n in 0...60 {
let b = bernoulli(n: n) as Frac<BigInt>
guard b!= 0 else {
continue
}
print("B(\(n)) = \(b)")
} | 1,108Bernoulli numbers
| 17swift
| luhc2 |
public class BinarySearchIterative {
public static int binarySearch(int[] nums, int check) {
int hi = nums.length - 1;
int lo = 0;
while (hi >= lo) {
int guess = (lo + hi) >>> 1; | 1,110Binary search
| 9java
| bask3 |
function binary_search_recursive(a, value, lo, hi) {
if (hi < lo) { return null; }
var mid = Math.floor((lo + hi) / 2);
if (a[mid] > value) {
return binary_search_recursive(a, value, lo, mid - 1);
}
if (a[mid] < value) {
return binary_search_recursive(a, value, mid + 1, hi);
}
return mid;
} | 1,110Binary search
| 10javascript
| wsne2 |
fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
var hi = size - 1
var lo = 0
while (hi >= lo) {
val guess = lo + (hi - lo) / 2
if (this[guess] > target) hi = guess - 1
else if (this[guess] < target) lo = guess + 1
else return guess
}
return -1
}
fun <T : Comparable<T>> Array<T>.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int {
if (hi < lo) return -1
val guess = (hi + lo) / 2
return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1)
else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi)
else guess
}
fun main(args: Array<String>) {
val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)
var target = 6
var r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 6
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
} | 1,110Binary search
| 11kotlin
| rhago |
use integer;
sub bitwise($$) {
($a, $b) = @_;
print 'a and b: '. ($a & $b) ."\n";
print 'a or b: '. ($a | $b) ."\n";
print 'a xor b: '. ($a ^ $b) ."\n";
print 'not a: '. (~$a) ."\n";
print 'a >> b: ', $a >> $b, "\n";
use integer;
print "after use integer:\n";
print 'a << b: ', $a << $b, "\n";
print 'a >> b: ', $a >> $b, "\n";
} | 1,103Bitwise operations
| 2perl
| v4w20 |
function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1);
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n';
echo '$a >> $b: ' . $a >> $b . '\n';
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n';
} | 1,103Bitwise operations
| 12php
| 0ilsp |
function binarySearch (list,value)
local low = 1
local high = #list
while low <= high do
local mid = math.floor((low+high)/2)
if list[mid] > value then high = mid - 1
elseif list[mid] < value then low = mid + 1
else return mid
end
end
return false
end | 1,110Binary search
| 1lua
| 7keru |
package main
import (
"fmt"
)
func main() {
for i := 0; i < 16; i++ {
fmt.Printf("%b\n", i)
}
} | 1,111Binary digits
| 0go
| v4j2m |
print '''
n binary
----- ---------------
'''
[5, 50, 9000].each {
printf('%5d%15s\n', it, Integer.toBinaryString(it))
} | 1,111Binary digits
| 7groovy
| ml5y5 |
def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f)
def rotr(width, a, n):
if n < 0:
return rotl(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n% width
return ((a >> n)
| ((a & ((1 << n) - 1))
<< (width - n)))
def rotl(width, a, n):
if n < 0:
return rotr(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n% width
return (((a << n) & mask)
| (a >> (width - n)))
def asr(width, a, n):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
if n < 0:
return (a << -n) & mask
elif n == 0:
return a
elif n >= width:
return mask if a & top_bit_mask else 0
else:
a = a & mask
if a & top_bit_mask:
signs = (1 << n) - 1
return a >> n | (signs << width - n)
else:
return a >> n
def helper_funcs(width, a):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
aa = a | top_bit_mask
print(f)
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27) | 1,103Bitwise operations
| 3python
| ugxvd |
import Data.List
import Numeric
import Text.Printf
toBin n = showIntAtBase 2 ("01" !!) n ""
toBin1 0 = []
toBin1 x = (toBin1 $ x `div` 2) ++ (show $ x `mod` 2)
toBin2 = foldMap show . reverse . toBase 2
toBase base = unfoldr modDiv
where modDiv 0 = Nothing
modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)
printToBin n = putStrLn $ printf "%4d %14s %14s" n (toBin n) (toBin1 n)
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000] | 1,111Binary digits
| 8haskell
| eqoai |
a <- 35
b <- 42
bitwAnd(a, b)
bitwOr(a, b)
bitwXor(a, b)
bitwNot(a)
bitwShiftL(a, 2)
bitwShiftR(a, 2) | 1,103Bitwise operations
| 13r
| cv195 |
public class Main {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(5));
System.out.println(Integer.toBinaryString(50));
System.out.println(Integer.toBinaryString(9000));
}
} | 1,111Binary digits
| 9java
| hpwjm |
function toBinary(number) {
return new Number(number)
.toString(2);
}
var demoValues = [5, 50, 9000];
for (var i = 0; i < demoValues.length; ++i) { | 1,111Binary digits
| 10javascript
| ax810 |
null | 1,111Binary digits
| 11kotlin
| 47b57 |
def bitwise(a, b)
form =
puts form % [, a]
puts form % [, b]
puts form % [, a & b]
puts form % [, a | b]
puts form % [, a ^ b]
puts form % [, ~a]
puts form % [, a << b]
puts form % [, a >> b]
end
bitwise(14,3) | 1,103Bitwise operations
| 14ruby
| 47s5p |
fn main() {
let a: u8 = 105;
let b: u8 = 91;
println!("a = {:0>8b}", a);
println!("b = {:0>8b}", b);
println!("a | b = {:0>8b}", a | b);
println!("a & b = {:0>8b}", a & b);
println!("a ^ b = {:0>8b}", a ^ b);
println!("!a = {:0>8b}",!a);
println!("a << 3 = {:0>8b}", a << 3);
println!("a >> 3 = {:0>8b}", a >> 3);
} | 1,103Bitwise operations
| 15rust
| gj04o |
def bitwise(a: Int, b: Int) {
println("a and b: " + (a & b))
println("a or b: " + (a | b))
println("a xor b: " + (a ^ b))
println("not a: " + (~a))
println("a << b: " + (a << b)) | 1,103Bitwise operations
| 16scala
| jbi7i |
sub binary_search {
my ($array_ref, $value, $left, $right) = @_;
while ($left <= $right) {
my $middle = int(($right + $left) >> 1);
if ($value == $array_ref->[$middle]) {
return $middle;
}
elsif ($value < $array_ref->[$middle]) {
$right = $middle - 1;
}
else {
$left = $middle + 1;
}
}
return -1;
} | 1,110Binary search
| 2perl
| dz9nw |
function binary_search( $array, $secret, $start, $end )
{
do
{
$guess = (int)($start + ( ( $end - $start ) / 2 ));
if ( $array[$guess] > $secret )
$end = $guess;
if ( $array[$guess] < $secret )
$start = $guess;
if ( $end < $start)
return -1;
} while ( $array[$guess] != $secret );
return $guess;
} | 1,110Binary search
| 12php
| jbw7z |
function dec2bin (n)
local bin = ""
while n > 0 do
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return bin
end
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000)) | 1,111Binary digits
| 1lua
| gjp4j |
func bitwise(a: Int, b: Int) { | 1,103Bitwise operations
| 17swift
| 5rqu8 |
def binary_search(l, value):
low = 0
high = len(l)-1
while low <= high:
mid = (low+high)
if l[mid] > value: high = mid-1
elif l[mid] < value: low = mid+1
else: return mid
return -1 | 1,110Binary search
| 3python
| f3cde |
BinSearch <- function(A, value, low, high) {
if ( high < low ) {
return(NULL)
} else {
mid <- floor((low + high) / 2)
if ( A[mid] > value )
BinSearch(A, value, low, mid-1)
else if ( A[mid] < value )
BinSearch(A, value, mid+1, high)
else
mid
}
} | 1,110Binary search
| 13r
| od684 |
class Array
def binary_search(val, low=0, high=(length - 1))
return nil if high < low
mid = (low + high) >> 1
case val <=> self[mid]
when -1
binary_search(val, low, mid - 1)
when 1
binary_search(val, mid + 1, high)
else mid
end
end
end
ary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]
[0,42,45,24324,99999].each do |val|
i = ary.binary_search(val)
if i
puts
else
puts
end
end | 1,110Binary search
| 14ruby
| zy2tw |
fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
let mut lower = 0 as usize;
let mut upper = v.len() - 1;
while upper >= lower {
let mid = (upper + lower) / 2;
if v[mid] == searchvalue {
return Some(searchvalue);
} else if searchvalue < v[mid] {
upper = mid - 1;
} else {
lower = mid + 1;
}
}
None
} | 1,110Binary search
| 15rust
| 3mvz8 |
def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
case _ if high < low => None
case mid if a(mid) > v => recurse(low, mid - 1)
case mid if a(mid) < v => recurse(mid + 1, high)
case mid => Some(mid)
}
recurse(0, a.size - 1)
} | 1,110Binary search
| 16scala
| ml4yc |
for (5, 50, 9000) {
printf "%b\n", $_;
} | 1,111Binary digits
| 2perl
| if6o3 |
<?php
echo decbin(5);
echo decbin(50);
echo decbin(9000); | 1,111Binary digits
| 12php
| rh1ge |
func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
var recurse: ((Int, Int) -> Int?)!
recurse = {(low, high) in switch (low + high) / 2 {
case _ where high < low: return nil
case let mid where xs[mid] > x: return recurse(low, mid - 1)
case let mid where xs[mid] < x: return recurse(mid + 1, high)
case let mid: return mid
}}
return recurse(0, xs.count - 1)
} | 1,110Binary search
| 17swift
| t6lfl |
>>> for i in range(16): print('{0:b}'.format(i))
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111 | 1,111Binary digits
| 3python
| ntyiz |
dec2bin <- function(num) {
ifelse(num == 0,
0,
sub("^0+","",paste(rev(as.integer(intToBits(num))), collapse = ""))
)
}
for (anumber in c(0, 5, 50, 9000)) {
cat(dec2bin(anumber),"\n")
} | 1,111Binary digits
| 13r
| 0itsg |
[5,50,9000].each do |n|
puts % n
end | 1,111Binary digits
| 14ruby
| f39dr |
fn main() {
for i in 0..8 {
println!("{:b}", i)
}
} | 1,111Binary digits
| 15rust
| t6cfd |
scala> (5 toBinaryString)
res0: String = 101
scala> (50 toBinaryString)
res1: String = 110010
scala> (9000 toBinaryString)
res2: String = 10001100101000 | 1,111Binary digits
| 16scala
| 69v31 |
for num in [5, 50, 9000] {
println(String(num, radix: 2))
} | 1,111Binary digits
| 17swift
| dzmnh |
declare -a encodeTable=(
62 -1 -1 -1 63 52 53 54 55 56 57 58 59 60 61 -1
-1 -1 -1 -1 -1 -1 0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
-1 -1 -1 -1 -1 -1 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
)
function a2b6()
{
if [ $1 -lt 43 -o $1 -gt 122 ]
then
echo -1
else
echo ${encodeTable[$(($1-43))]}
fi
}
function flush() {
for (( k=2; k>=4-CNT; k-- ))
do
(( b8=BUF>>(k*8)&255 ))
printf -v HEX %x $b8
printf \\x$HEX
done
}
while read INPUT
do
for (( i=0; i<${
do
printf -v NUM %d "'${INPUT:$i:1}"
if (( NUM==61 ))
then
flush
exit 0
else
DEC=$( a2b6 $NUM )
if (( DEC>=0 ))
then
(( BUF|=DEC<<6*(3-CNT) ))
if (( ++CNT==4 ))
then
flush
(( CNT=0, BUF=0 ))
fi
fi
fi
done
done | 1,112Base64 decode data
| 4bash
| 0ifsa |
typedef unsigned char ubyte;
const ubyte BASE64[] = ;
int findIndex(const ubyte val) {
if ('A' <= val && val <= 'Z') {
return val - 'A';
}
if ('a' <= val && val <= 'z') {
return val - 'a' + 26;
}
if ('0' <= val && val <= '9') {
return val - '0' + 52;
}
if (val == '+') {
return 62;
}
if (val == '/') {
return 63;
}
return -1;
}
int decode(const ubyte source[], ubyte sink[]) {
const size_t length = strlen(source);
const ubyte *it = source;
const ubyte *end = source + length;
int acc;
if (length % 4 != 0) {
return 1;
}
while (it != end) {
const ubyte b1 = *it++;
const ubyte b2 = *it++;
const ubyte b3 = *it++;
const ubyte b4 = *it++;
const int i1 = findIndex(b1);
const int i2 = findIndex(b2);
acc = i1 << 2;
acc |= i2 >> 4;
*sink++ = acc;
if (b3 != '=') {
const int i3 = findIndex(b3);
acc = (i2 & 0xF) << 4;
acc += i3 >> 2;
*sink++ = acc;
if (b4 != '=') {
const int i4 = findIndex(b4);
acc = (i3 & 0x3) << 6;
acc |= i4;
*sink++ = acc;
}
}
}
*sink = '\0';
return 0;
}
int main() {
ubyte data[] = ;
ubyte decoded[1024];
printf(, data);
decode(data, decoded);
printf(, decoded);
return 0;
} | 1,112Base64 decode data
| 5c
| odz80 |
(defn decode [str]
(String. (.decode (java.util.Base64/getDecoder) str)))
(decode "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=") | 1,112Base64 decode data
| 6clojure
| t69fv |
import 'dart:convert';
void main() {
var encoded = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
var decoded = utf8.decode(base64.decode(encoded));
print(decoded);
} | 1,112Base64 decode data
| 18dart
| wsoeo |
package main
import (
"encoding/base64"
"fmt"
)
func main() {
msg := "Rosetta Code Base64 decode data task"
fmt.Println("Original:", msg)
encoded := base64.StdEncoding.EncodeToString([]byte(msg))
fmt.Println("\nEncoded :", encoded)
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nDecoded :", string(decoded))
} | 1,112Base64 decode data
| 0go
| 47k52 |
import java.nio.charset.StandardCharsets
class Decode {
static void main(String[] args) {
String data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
Base64.Decoder decoder = Base64.getDecoder()
byte[] decoded = decoder.decode(data)
String decodedStr = new String(decoded, StandardCharsets.UTF_8)
System.out.println(decodedStr)
}
} | 1,112Base64 decode data
| 7groovy
| lugc1 |
import qualified Data.Map.Strict as Map (Map, lookup, fromList)
import Data.Maybe (fromJust, listToMaybe, mapMaybe)
import Numeric (readInt, showIntAtBase)
import Data.Char (chr, digitToInt)
import Data.List.Split (chunksOf)
byteToASCII :: String -> String
byteToASCII = map chr . decoder
decoder :: String -> [Int]
decoder =
map readBin .
takeWhile (\x -> length x == 8) .
chunksOf 8 . concatMap toBin . mapMaybe (`Map.lookup` table) . filter (/= '=')
toBin :: Int -> String
toBin n = leftPad $ showIntAtBase 2 ("01" !!) n ""
leftPad :: String -> String
leftPad a = replicate (6 - length a) '0' ++ a
readBin :: String -> Int
readBin = fromJust . fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
table :: Map.Map Char Int
table =
Map.fromList $
zip "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" [0 ..]
main :: IO ()
main =
putStrLn $
byteToASCII
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCi0tIFBhdWwgUi4gRWhybGljaA==" | 1,112Base64 decode data
| 8haskell
| q8nx9 |
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Decode {
public static void main(String[] args) {
String data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Base64.Decoder decoder = Base64.getDecoder();
byte[] decoded = decoder.decode(data);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
System.out.println(decodedStr);
}
} | 1,112Base64 decode data
| 9java
| peqb3 |
null | 1,112Base64 decode data
| 10javascript
| x0iw9 |
import java.util.Base64
fun main() {
val data =
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
val decoder = Base64.getDecoder()
val decoded = decoder.decode(data)
val decodedStr = String(decoded, Charsets.UTF_8)
println(decodedStr)
} | 1,112Base64 decode data
| 11kotlin
| 7k1r4 |
null | 1,112Base64 decode data
| 1lua
| jba71 |
sub decode_base64 {
my($d) = @_;
$d =~ tr!A-Za-z0-9+/!!cd;
$d =~ s/=+$//;
$d =~ tr!A-Za-z0-9+/! -_!;
my $r = '';
while( $d =~ /(.{1,60})/gs ){
my $len = chr(32 + length($1)*3/4);
$r .= unpack("u", $len . $1 );
}
$r;
}
$data = <<EOD;
J1R3YXMgYnJpbGxpZywgYW5kIHRoZSBzbGl0aHkgdG92ZXMKRGlkIGd5cmUgYW5kIGdpbWJsZSBp
biB0aGUgd2FiZToKQWxsIG1pbXN5IHdlcmUgdGhlIGJvcm9nb3ZlcywKQW5kIHRoZSBtb21lIHJh
dGhzIG91dGdyYWJlLgo=
EOD
print decode_base64($data) . "\n"; | 1,112Base64 decode data
| 2perl
| f3md7 |
double rms(double *v, int n)
{
int i;
double sum = 0.0;
for(i = 0; i < n; i++)
sum += v[i] * v[i];
return sqrt(sum / n);
}
int main(void)
{
double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
printf(, rms(v, sizeof(v)/sizeof(double)));
return 0;
} | 1,113Averages/Root mean square
| 5c
| 1wqpj |
$encoded = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw' .
'IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=';
echo
$encoded, PHP_EOL,
base64_decode($encoded), PHP_EOL; | 1,112Base64 decode data
| 12php
| hpejf |
import base64
data = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='
print(base64.b64decode(data).decode('utf-8')) | 1,112Base64 decode data
| 3python
| t69fw |
(defn rms [xs]
(Math/sqrt (/ (reduce + (map #(* % %) xs))
(count xs))))
(println (rms (range 1 11))) | 1,113Averages/Root mean square
| 6clojure
| q8ixt |
require 'base64'
raku_example ='
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2
9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
'
puts Base64.decode64 raku_example | 1,112Base64 decode data
| 14ruby
| 3mlz7 |
use std::str;
const INPUT: &str = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
const UPPERCASE_OFFSET: i8 = -65;
const LOWERCASE_OFFSET: i8 = 26 - 97;
const NUM_OFFSET: i8 = 52 - 48;
fn main() {
println!("Input: {}", INPUT);
let result = INPUT.chars()
.filter(|&ch| ch!= '=') | 1,112Base64 decode data
| 15rust
| 6923l |