code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"fmt"
"strings"
)
type ckey struct {
enc, dec func(rune) rune
}
func newCaesar(k int) (*ckey, bool) {
if k < 1 || k > 25 {
return nil, false
}
rk := rune(k)
return &ckey{
enc: func(c rune) rune {
if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk {
return c + rk
} else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' {
return c + rk - 26
}
return c
},
dec: func(c rune) rune {
if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' {
return c - rk
} else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk {
return c - rk + 26
}
return c
},
}, true
}
func (ck ckey) encipher(pt string) string {
return strings.Map(ck.enc, pt)
}
func (ck ckey) decipher(ct string) string {
return strings.Map(ck.dec, ct)
}
func main() {
pt := "The five boxing wizards jump quickly"
fmt.Println("Plaintext:", pt)
for _, key := range []int{0, 1, 7, 25, 26} {
ck, ok := newCaesar(key)
if !ok {
fmt.Println("Key", key, "invalid")
continue
}
ct := ck.encipher(pt)
fmt.Println("Key", key)
fmt.Println(" Enciphered:", ct)
fmt.Println(" Deciphered:", ck.decipher(ct))
}
} | 1,083Caesar cipher
| 0go
| x8xwf |
function ShuffleArray(array)
for i=1,#array-1 do
local t = math.random(i, #array)
array[i], array[t] = array[t], array[i]
end
end
function GenerateNumber()
local digits = {1,2,3,4,5,6,7,8,9}
ShuffleArray(digits)
return digits[1] * 1000 +
digits[2] * 100 +
digits[3] * 10 +
digits[4]
end
function IsMalformed(input)
local malformed = false
if #input == 4 then
local already_used = {}
for i=1,4 do
local digit = input:byte(i) - string.byte('0')
if digit < 1 or digit > 9 or already_used[digit] then
malformed = true
break
end
already_used[digit] = true
end
else
malformed = true
end
return malformed
end
math.randomseed(os.time())
math.randomseed(math.random(2^31-1)) | 1,082Bulls and cows
| 1lua
| 0n8sd |
def caesarEncode(cipherKey, text) {
def builder = new StringBuilder()
text.each { character ->
int ch = character[0] as char
switch(ch) {
case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break
case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break
}
builder << (ch as char)
}
builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } | 1,083Caesar cipher
| 7groovy
| pwpbo |
>>> import calendar
>>> help(calendar.prcal)
Help on method pryear in module calendar:
pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance
Print a years calendar.
>>> calendar.prcal(1969)
1969
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30
31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 4 1
7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2 3 4 5 6 7
6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 | 1,081Calendar
| 3python
| 8di0o |
module Caesar (caesar, uncaesar) where
import Data.Char
caesar, uncaesar :: (Integral a) => a -> String -> String
caesar k = map f
where f c = case generalCategory c of
LowercaseLetter -> addChar 'a' k c
UppercaseLetter -> addChar 'A' k c
_ -> c
uncaesar k = caesar (-k)
addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c | 1,083Caesar cipher
| 8haskell
| yly66 |
foo();
&foo();
foo($arg1, $arg2);
&foo($arg1, $arg2); | 1,077Call a function
| 2perl
| x8iw8 |
def factorial(n)
(1..n).reduce(1,:*)
end
def catalan_direct(n)
factorial(2*n) / (factorial(n+1) * factorial(n))
end
def catalan_rec1(n)
return 1 if n == 0
(0...n).inject(0) {|sum, i| sum + catalan_rec1(i) * catalan_rec1(n-1-i)}
end
def catalan_rec2(n)
return 1 if n == 0
2*(2*n - 1) * catalan_rec2(n-1) / (n+1)
end
require 'benchmark'
require 'memoize'
include Memoize
Benchmark.bm(17) do |b|
b.report('catalan_direct') {16.times {|n| catalan_direct(n)} }
b.report('catalan_rec1') {16.times {|n| catalan_rec1(n)} }
b.report('catalan_rec2') {16.times {|n| catalan_rec2(n)} }
memoize :catalan_rec1
b.report('catalan_rec1(memo)'){16.times {|n| catalan_rec1(n)} }
end
puts
16.times {|n| puts % [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} | 1,068Catalan numbers
| 14ruby
| 57quj |
fn c_n(n: u64) -> u64 {
match n {
0 => 1,
_ => c_n(n - 1) * 2 * (2 * n - 1) / (n + 1)
}
}
fn main() {
for i in 1..16 {
println!("c_n({}) = {}", i, c_n(i));
}
} | 1,068Catalan numbers
| 15rust
| 4js5u |
def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r'% (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
var_args(1, (2,3))
var_args()
fixed_args(y=2, x=1)
if 1:
no_args()
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
is_builtin(pow)
is_builtin(is_builtin)
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print(% (key, value))
wrapped_fn(*args, **kwargs) | 1,077Call a function
| 3python
| qonxi |
object CatalanNumbers {
def main(args: Array[String]): Unit = {
for (n <- 0 to 15) {
println("catalan(" + n + ") = " + catalan(n))
}
}
def catalan(n: BigInt): BigInt = factorial(2 * n) / (factorial(n + 1) * factorial(n))
def factorial(n: BigInt): BigInt = BigInt(1).to(n).foldLeft(BigInt(1))(_ * _)
} | 1,068Catalan numbers
| 16scala
| 7bor9 |
require 'date'
def cal(year, columns)
date = Date.new(year, 1, 1, Date::ENGLAND)
months = (1..12).collect do |month|
rows = [Date::MONTHNAMES[month].center(20), ]
days = []
date.wday.times { days.push }
while date.month == month
days.push( % date.mday)
date += 1
end
(42 - days.length).times { days.push }
days.each_slice(7) { |week| rows.push(week.join ) }
next rows
end
mpr = (columns + 2).div 22
mpr = 12.div((12 + mpr - 1).div mpr)
width = mpr * 22 - 2
rows = [.center(width), .center(width)]
months.each_slice(mpr) do |slice|
slice[0].each_index do |i|
rows.push(slice.map {|a| a[i]}.join )
end
end
return rows.join()
end
ARGV.length == 1 or abort
columns = begin Integer(ENV[] || )
rescue
begin require 'io/console'; IO.console.winsize[1]
rescue LoadError
begin Integer(`tput cols`)
rescue
80; end; end; end
puts cal(Integer(ARGV[0]), columns) | 1,081Calendar
| 14ruby
| itdoh |
public class Cipher {
public static void main(String[] args) {
String str = "The quick brown fox Jumped over the lazy Dog";
System.out.println( Cipher.encode( str, 12 ));
System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
}
public static String decode(String enc, int offset) {
return encode(enc, 26-offset);
}
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i: enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
} | 1,083Caesar cipher
| 9java
| d3dn9 |
null | 1,081Calendar
| 15rust
| nzfi4 |
function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
});
} | 1,083Caesar cipher
| 10javascript
| 6c638 |
import java.util.{ Calendar, GregorianCalendar }
import language.postfixOps
import collection.mutable.ListBuffer
object CalendarPrint extends App {
val locd = java.util.Locale.getDefault()
val cal = new GregorianCalendar
val monthsMax = cal.getMaximum(Calendar.MONTH)
def JDKweekDaysToISO(dn: Int) = {
val nday = dn - Calendar.MONDAY
if (nday < 0) (dn + Calendar.THURSDAY) else nday
}
def daysInMonth(year: Int, monthMinusOne: Int): Int = {
cal.set(year, monthMinusOne, 1)
cal.getActualMaximum(Calendar.DAY_OF_MONTH)
}
def namesOfMonths() = {
def f1(i: Int): String = {
cal.set(2013, i, 1)
cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locd)
}
(0 to monthsMax) map f1
}
def offsets(year: Int): List[Int] = {
val months = cal.getMaximum(Calendar.MONTH)
def get1stDayOfWeek(i: Int) = {
cal.set(year, i, 1)
cal.get(Calendar.DAY_OF_WEEK)
}
(0 to monthsMax).toList map get1stDayOfWeek map { i => JDKweekDaysToISO(i) }
}
def headerNameOfDays() = {
val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locd) | 1,081Calendar
| 16scala
| ty3fb |
no_args <- function() NULL
no_args()
fixed_args <- function(x, y) print(paste("x=", x, ", y=", y, sep=""))
fixed_args(1, 2)
fixed_args(y=2, x=1)
opt_args <- function(x=1) x
opt_args()
opt_args(3.141)
var_args <- function(...) print(list(...))
var_args(1, 2, 3)
var_args(1, c(2,3))
var_args()
fixed_args(y=2, x=1)
if (TRUE) no_args()
print(no_args)
return_something <- function() 1
x <- return_something()
x | 1,077Call a function
| 13r
| aq01z |
fn main() {
fn no_args() {}
no_args();
fn adds_one(num: i32) -> i32 {
num + 1
}
adds_one(1);
fn prints_argument(maybe: Option<i32>) {
match maybe {
Some(num) => println!(, num),
None => println!(),
};
}
prints_argument(Some(3));
prints_argument(None);
fn prints_argument_into<I>(maybe: I)
where I: Into<Option<i32>>
{
match maybe.into() {
Some(num) => println!(, num),
None => println!(),
};
}
prints_argument_into(3);
prints_argument_into(None);
adds_one(1) + adds_one(5);
let two = adds_one(1);
let mut v = vec![1, 2, 3, 4, 5, 6];
fn add_one_to_first_element(vector: &mut Vec<i32>) {
vector[0] += 1;
}
add_one_to_first_element(&mut v);
fn print_first_element(vector: &Vec<i32>) {
println!(, vector[0]);
}
print_first_element(&v);
fn consume_vector(vector: Vec<i32>) {
}
consume_vector(v);
fn average(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
let average_with_four = |y| average(4.0, y);
average_with_four(2.0);
} | 1,077Call a function
| 14ruby
| 0nfsu |
null | 1,083Caesar cipher
| 11kotlin
| 0n0sf |
fn main() { | 1,077Call a function
| 15rust
| 8dt07 |
def ??? = throw new NotImplementedError | 1,077Call a function
| 16scala
| nz6ic |
func catalan(_ n: Int) -> Int {
switch n {
case 0:
return 1
case _:
return catalan(n - 1) * 2 * (2 * n - 1) / (n + 1)
}
}
for i in 1..<16 {
print("catalan(\(i)) => \(catalan(i))")
} | 1,068Catalan numbers
| 17swift
| urxvg |
import Foundation
let monthWidth = 20
let monthGap = 2
let dayNames = "Su Mo Tu We Th Fr Sa"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
func rpad(string: String, width: Int) -> String {
return string.count >= width? string
: String(repeating: " ", count: width - string.count) + string
}
func lpad(string: String, width: Int) -> String {
return string.count >= width? string
: string + String(repeating: " ", count: width - string.count)
}
func centre(string: String, width: Int) -> String {
if string.count >= width {
return string
}
let c = (width - string.count)/2
return String(repeating: " ", count: c) + string
+ String(repeating: " ", count: width - string.count - c)
}
func formatMonth(year: Int, month: Int) -> [String] {
let calendar = Calendar.current
let dc = DateComponents(year: year, month: month, day: 1)
let date = calendar.date(from: dc)!
let firstDay = calendar.component(.weekday, from: date) - 1
let range = calendar.range(of: .day, in: .month, for: date)!
let daysInMonth = range.count
var lines: [String] = []
lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth))
lines.append(dayNames)
var padWidth = 2
var line = String(repeating: " ", count: 3 * firstDay)
for day in 1...daysInMonth {
line += rpad(string: String(day), width: padWidth)
padWidth = 3
if (firstDay + day)% 7 == 0 {
lines.append(line)
line = ""
padWidth = 2
}
}
if line.count > 0 {
lines.append(lpad(string: line, width: monthWidth))
}
return lines
}
func printCentred(string: String, width: Int) {
print(rpad(string: string, width: (width + string.count)/2))
}
public func printCalendar(year: Int, width: Int) {
let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap)))
let lineWidth = monthWidth * months + monthGap * (months - 1)
printCentred(string: "[Snoopy]", width: lineWidth)
printCentred(string: String(year), width: lineWidth)
var firstMonth = 1
while firstMonth <= 12 {
if firstMonth > 1 {
print()
}
let lastMonth = min(12, firstMonth + months - 1)
let monthCount = lastMonth - firstMonth + 1
var lines: [[String]] = []
var lineCount = 0
for month in firstMonth...lastMonth {
let monthLines = formatMonth(year: year, month: month)
lineCount = max(lineCount, monthLines.count)
lines.append(monthLines)
}
for i in 0..<lineCount {
var line = ""
for month in 0..<monthCount {
if month > 0 {
line.append(String(repeating: " ", count: monthGap))
}
line.append(i < lines[month].count? lines[month][i]
: String(repeating: " ", count: monthWidth))
}
print(line)
}
firstMonth = lastMonth + 1
}
}
printCalendar(year: 1969, width: 80) | 1,081Calendar
| 17swift
| ofn8k |
use Data::Random qw(rand_set);
use List::MoreUtils qw(uniq);
my $size = 4;
my $chosen = join "", rand_set set => ["1".."9"], size => $size;
print "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ( my $guesses = 1; ; $guesses++ ) {
my $guess;
while (1) {
print "\nNext guess [$guesses]: ";
$guess = <STDIN>;
chomp $guess;
checkguess($guess) and last;
print "$size digits, no repetition, no 0... retry\n";
}
if ( $guess eq $chosen ) {
print "You did it in $guesses attempts!\n";
last;
}
my $bulls = 0;
my $cows = 0;
for my $i (0 .. $size-1) {
if ( substr($guess, $i, 1) eq substr($chosen, $i, 1) ) {
$bulls++;
} elsif ( index($chosen, substr($guess, $i, 1)) >= 0 ) {
$cows++;
}
}
print "$cows cows, $bulls bulls\n";
}
sub checkguess
{
my $g = shift;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
} | 1,082Bulls and cows
| 2perl
| ur5vr |
null | 1,068Catalan numbers
| 20typescript
| w0yeu |
null | 1,077Call a function
| 17swift
| sidqt |
<?php
$size = 4;
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
echo ;
for ($guesses = 1; ; $guesses++) {
while (true) {
echo ;
$guess = rtrim(fgets(STDIN));
if (!checkguess($guess))
echo ;
else
break;
}
if ($guess == $chosen) {
echo ;
break;
} else {
$bulls = 0;
$cows = 0;
foreach (range(0, $size-1) as $i) {
if ($guess[$i] == $chosen[$i])
$bulls++;
else if (strpos($chosen, $guess[$i]) !== FALSE)
$cows++;
}
echo ;
}
}
function checkguess($g)
{
global $size;
return count(array_unique(str_split($g))) == $size &&
preg_match(, $g);
}
?> | 1,082Bulls and cows
| 12php
| 8do0m |
local function encrypt(text, key)
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
local r = t:byte() - base
r = r + key
r = r%26 | 1,083Caesar cipher
| 1lua
| 8d80e |
'''
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print '''I have chosen a number from%s unique digits from 1 to 9 arranged in a random order.
You need to input a%i digit, unique digit number as a guess at what I have chosen'''% (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: '% guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows'% (bulls, cows) | 1,082Bulls and cows
| 3python
| 574ux |
void print_jpg(image img, int qual); | 1,084Bitmap/PPM conversion through a pipe
| 5c
| zyftx |
target <- sample(1:9,4)
bulls <- 0
cows <- 0
attempts <- 0
while (bulls!= 4)
{
input <- readline("Guess a 4-digit number with no duplicate digits or 0s: ")
if (nchar(input) == 4)
{
input <- as.integer(strsplit(input,"")[[1]])
if ((sum(is.na(input)+sum(input==0))>=1) | (length(table(input))!= 4)) {print("Malformed input!")} else {
bulls <- sum(input == target)
cows <- sum(input%in% target)-bulls
cat("\n",bulls," Bull(s) and ",cows, " Cow(s)\n")
attempts <- attempts + 1
}
} else {print("Malformed input!")}
}
print(paste("You won in",attempts,"attempt(s)!")) | 1,082Bulls and cows
| 13r
| l52ce |
package main | 1,084Bitmap/PPM conversion through a pipe
| 0go
| k1jhz |
null | 1,084Bitmap/PPM conversion through a pipe
| 11kotlin
| 1wbpd |
use strict;
use warnings;
use Imager;
use Imager::Test 'test_image_raw';
my $img = test_image_raw();
my $IO = Imager::io_new_bufchain();
Imager::i_writeppm_wiol($img, $IO) or die;
my $raw = Imager::io_slurp($IO) or die;
open my $fh, '|-', '/usr/local/bin/convert - -compress none output.jpg' or die;
binmode $fh;
syswrite $fh, $raw or die;
close $fh; | 1,084Bitmap/PPM conversion through a pipe
| 2perl
| ml6yz |
from PIL import Image
im = Image.open()
im.save() | 1,084Bitmap/PPM conversion through a pipe
| 3python
| 92ymf |
def generate_word(len)
[*..].shuffle.first(len)
end
def get_guess(len)
loop do
print
guess = gets.strip
err = case
when guess.match(/[^1-9]/) ;
when guess.length!= len ;
when guess.split().uniq.length!= len;
else return guess.split()
end
puts
end
end
def score(word, guess)
bulls = cows = 0
guess.each_with_index do |num, idx|
if word[idx] == num
bulls += 1
elsif word.include? num
cows += 1
end
end
[bulls, cows]
end
word_length = 4
puts
word = generate_word(word_length)
count = 0
loop do
guess = get_guess(word_length)
count += 1
break if word == guess
puts % score(word, guess)
end
puts | 1,082Bulls and cows
| 14ruby
| ghr4q |
image read_image(const char *name); | 1,085Bitmap/Read an image through a pipe
| 5c
| 69t32 |
package main | 1,085Bitmap/Read an image through a pipe
| 0go
| pehbg |
class Pixmap
PIXMAP_FORMATS = [, ]
PIXMAP_BINARY_FORMATS = []
def write_ppm(ios, format=)
if not PIXMAP_FORMATS.include?(format)
raise NotImplementedError,
end
ios.puts format, ,
ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)
@height.times do |y|
@width.times do |x|
case format
when then ios.print @data[x][y].values.join(),
when then ios.print @data[x][y].values.pack('C3')
end
end
end
end
def save(filename, opts={:format=>})
File.open(filename, 'w') do |f|
write_ppm(f, opts[:format])
end
end
def print(opts={:format=>})
write_ppm($stdout, opts[:format])
end
def save_as_jpeg(filename, quality=75)
pipe = IO.popen(, 'w')
write_ppm(pipe)
pipe.close
end
end
image = Pixmap.open('file.ppm')
image.save_as_jpeg('file.jpg') | 1,084Bitmap/PPM conversion through a pipe
| 14ruby
| lu9cl |
use std::io;
use rand::{Rng,thread_rng};
extern crate rand;
const NUMBER_OF_DIGITS: usize = 4;
static DIGITS: [char; 9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
fn generate_digits() -> Vec<char> {
let mut temp_digits: Vec<_> = (&DIGITS[..]).into();
thread_rng().shuffle(&mut temp_digits);
return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();
}
fn parse_guess_string(guess: &str) -> Result<Vec<char>, String> {
let chars: Vec<char> = (&guess).chars().collect();
if!chars.iter().all(|c| DIGITS.contains(c)) {
return Err("only digits, please".to_string());
}
if chars.len()!= NUMBER_OF_DIGITS {
return Err(format!("you need to guess with {} digits", NUMBER_OF_DIGITS));
}
let mut uniques: Vec<char> = chars.clone();
uniques.dedup();
if uniques.len()!= chars.len() {
return Err("no duplicates, please".to_string());
}
return Ok(chars);
}
fn calculate_score(given_digits: &[char], guessed_digits: &[char]) -> (usize, usize) {
let mut bulls = 0;
let mut cows = 0;
for i in 0..NUMBER_OF_DIGITS {
let pos: Option<usize> = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]});
match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1
}
}
return (bulls, cows);
}
fn main() {
let reader = io::stdin();
loop {
let given_digits = generate_digits();
println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS);
loop {
let guess_string: String = {
let mut buf = String::new();
reader.read_line(&mut buf).unwrap();
buf.trim().into()
};
let digits_maybe = parse_guess_string(&guess_string);
match digits_maybe {
Err(msg) => {
println!("{}", msg);
continue;
},
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
},
(bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows)
}
}
}
}
}
} | 1,082Bulls and cows
| 15rust
| rk7g5 |
null | 1,085Bitmap/Read an image through a pipe
| 11kotlin
| eqpa4 |
import scala.util.Random
object BullCow {
def main(args: Array[String]): Unit = {
val number=chooseNumber
var guessed=false
var guesses=0
while(!guessed){
Console.print("Guess a 4-digit number with no duplicate digits: ")
val input=Console.readInt
val digits=input.toString.map(_.asDigit).toList
if(input>=1111 && input<=9999 && !hasDups(digits)){
guesses+=1
var bulls, cows=0
for(i <- 0 to 3)
if(number(i)==digits(i))
bulls+=1
else if(number.contains(digits(i)))
cows+=1
if(bulls==4)
guessed=true
else
println("%d Cows and%d Bulls.".format(cows, bulls))
}
}
println("You won after "+guesses+" guesses!");
}
def chooseNumber={
var digits=List[Int]()
while(digits.size<4){
val d=Random.nextInt(9)+1
if (!digits.contains(d))
digits=digits:+d
}
digits
}
def hasDups(input:List[Int])=input.size!=input.distinct.size
} | 1,082Bulls and cows
| 16scala
| h1kja |
function Bitmap:loadPPM(filename, fp)
if not fp then fp = io.open(filename, "rb") end
if not fp then return end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
end | 1,085Bitmap/Read an image through a pipe
| 1lua
| ws1ea |
use strict;
use warnings;
use Imager;
my $raw;
open my $fh, '-|', 'cat Lenna50.jpg' or die;
binmode $fh;
while ( sysread $fh , my $chunk , 1024 ) { $raw .= $chunk }
close $fh;
my $enable = $Imager::formats{"jpeg"};
my $IO = Imager::io_new_buffer $raw or die;
my $im = Imager::File::JPEG::i_readjpeg_wiol $IO or die;
open my $fh2, '>', 'output.ppm' or die;
binmode $fh2;
my $IO2 = Imager::io_new_fd(fileno $fh2);
Imager::i_writeppm_wiol $im, $IO2 ;
close $fh2;
undef($im); | 1,085Bitmap/Read an image through a pipe
| 2perl
| cvy9a |
from PIL import Image
im = Image.open()
im.save() | 1,085Bitmap/Read an image through a pipe
| 3python
| lumcv |
require_relative 'raster_graphics'
class Pixmap
def self.read_ppm(ios)
format = ios.gets.chomp
width, height = ios.gets.chomp.split.map(&:to_i)
max_colour = ios.gets.chomp
if!PIXMAP_FORMATS.include?(format) ||
(width < 1) || (height < 1) ||
(max_colour!= '255')
ios.close
raise StandardError,
end
ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)
bitmap = new(width, height)
height.times do |y|
width.times do |x|
red, green, blue = case format
when 'P3' then ios.gets.chomp.split
when 'P6' then ios.read(3).unpack('C3')
end
bitmap[x, y] = RGBColour.new(red, green, blue)
end
end
ios.close
bitmap
end
def self.open(filename)
read_ppm(File.open(filename, 'r'))
end
def self.open_from_jpeg(filename)
read_ppm(IO.popen(, 'r'))
end
end
bitmap = Pixmap.open_from_jpeg('foto.jpg')
bitmap.save('foto.ppm') | 1,085Bitmap/Read an image through a pipe
| 14ruby
| v4c2n |
sub caesar {
my ($message, $key, $decode) = @_;
$key = 26 - $key if $decode;
$message =~ s/([A-Z])/chr(((ord(uc $1) - 65 + $key) % 26) + 65)/geir;
}
my $msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $enc = caesar($msg, 10);
my $dec = caesar($enc, 10, 'decode');
print "msg: $msg\nenc: $enc\ndec: $dec\n"; | 1,083Caesar cipher
| 2perl
| 575u2 |
<?php
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
$ciphertext = ;
$ascii_a = ord( 'a' );
$ascii_z = ord( 'z' );
while( strlen( $plaintext ) ){
$char = ord( $plaintext );
if( $char >= $ascii_a && $char <= $ascii_z ){
$char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a;
}
$plaintext = substr( $plaintext, 1 );
$ciphertext .= chr( $char );
}
return $ciphertext;
}
echo caesarEncode( , 12 ), ;
?> | 1,083Caesar cipher
| 12php
| ofo85 |
import Foundation
func generateRandomNumArray(numDigits: Int = 4) -> [Int] {
guard numDigits > 0 else {
return []
}
let needed = min(9, numDigits)
var nums = Set<Int>()
repeat {
nums.insert(.random(in: 1...9))
} while nums.count!= needed
return Array(nums)
}
func parseGuess(_ guess: String) -> [Int]? {
guard guess.count == 4 else {
return nil
}
let guessArray = guess.map(String.init).map(Int.init).compactMap({ $0 })
guard Set(guessArray).count == 4 else {
return nil
}
return guessArray
}
while true {
let num = generateRandomNumArray()
var bulls = 0
var cows = 0
print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")
guard let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr) else {
print("Invalid input")
continue
}
for (guess, actual) in zip(guess, num) {
if guess == actual {
bulls += 1
} else if num.contains(guess) {
cows += 1
}
}
print("Actual number: \(num.map(String.init).joined())")
print("Your score: \(bulls) bulls and \(cows) cows\n")
print("Would you like to play again? (y): ")
guard readLine(strippingNewline: true)!.lowercased() == "y" else {
exit(0)
}
} | 1,082Bulls and cows
| 17swift
| 4jg5g |
image get_ppm(FILE *pf); | 1,086Bitmap/Read a PPM file
| 5c
| luycy |
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen(, );
(void) fprintf(fp, , dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256;
color[1] = j % 256;
color[2] = (i * j) % 256;
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
} | 1,087Bitmap/Write a PPM file
| 5c
| 7kurg |
def caesar(s, k, decode = False):
if decode: k = 26 - k
return .join([chr((ord(i) - 65 + k)% 26 + 65)
for i in s.upper()
if ord(i) >= 65 and ord(i) <= 90 ])
msg =
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True) | 1,083Caesar cipher
| 3python
| 4j45k |
typedef uint8_t byte;
typedef struct {
FILE *fp;
uint32_t accu;
int bits;
} bit_io_t, *bit_filter;
bit_filter b_attach(FILE *f)
{
bit_filter b = malloc(sizeof(bit_io_t));
b->bits = b->accu = 0;
b->fp = f;
return b;
}
void b_write(byte *buf, size_t n_bits, size_t shift, bit_filter bf)
{
uint32_t accu = bf->accu;
int bits = bf->bits;
buf += shift / 8;
shift %= 8;
while (n_bits || bits >= 8) {
while (bits >= 8) {
bits -= 8;
fputc(accu >> bits, bf->fp);
accu &= (1 << bits) - 1;
}
while (bits < 8 && n_bits) {
accu = (accu << 1) | (((128 >> shift) & *buf) >> (7 - shift));
--n_bits;
bits++;
if (++shift == 8) {
shift = 0;
buf++;
}
}
}
bf->accu = accu;
bf->bits = bits;
}
size_t b_read(byte *buf, size_t n_bits, size_t shift, bit_filter bf)
{
uint32_t accu = bf->accu;
int bits = bf->bits;
int mask, i = 0;
buf += shift / 8;
shift %= 8;
while (n_bits) {
while (bits && n_bits) {
mask = 128 >> shift;
if (accu & (1 << (bits - 1))) *buf |= mask;
else *buf &= ~mask;
n_bits--;
bits--;
if (++shift >= 8) {
shift = 0;
buf++;
}
}
if (!n_bits) break;
accu = (accu << 8) | fgetc(bf->fp);
bits += 8;
}
bf->accu = accu;
bf->bits = bits;
return i;
}
void b_detach(bit_filter bf)
{
if (bf->bits) {
bf->accu <<= 8 - bf->bits;
fputc(bf->accu, bf->fp);
}
free(bf);
}
int main()
{
unsigned char s[] = ;
unsigned char s2[11] = {0};
int i;
FILE *f = fopen(, );
bit_filter b = b_attach(f);
for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b);
b_detach(b);
fclose(f);
f = fopen(, );
b = b_attach(f);
for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b);
b_detach(b);
fclose(f);
printf(, s2);
return 0;
} | 1,088Bitwise IO
| 5c
| f30d3 |
ceasar <- function(x, key)
{
if (key < 0) {
key <- 26 + key
}
old <- paste(letters, LETTERS, collapse="", sep="")
new <- paste(substr(old, key * 2 + 1, 52), substr(old, 1, key * 2), sep="")
chartr(old, new, x)
}
print(ceasar("hi",2))
print(ceasar("hi",20))
key <- 3
plaintext <- "The five boxing wizards jump quickly."
cyphertext <- ceasar(plaintext, key)
decrypted <- ceasar(cyphertext, -key)
print(paste(" Plain Text: ", plaintext, sep=""))
print(paste(" Cypher Text: ", cyphertext, sep=""))
print(paste("Decrypted Text: ", decrypted, sep="")) | 1,083Caesar cipher
| 13r
| 242lg |
package raster
import (
"errors"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
) | 1,086Bitmap/Read a PPM file
| 0go
| x01wf |
import Bitmap
import Bitmap.RGB
import Bitmap.Gray
import Bitmap.Netpbm
import Control.Monad
import Control.Monad.ST
main =
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . toGrayImage >>=
writeNetpbm "new.pgm" | 1,086Bitmap/Read a PPM file
| 8haskell
| yct66 |
null | 1,086Bitmap/Read a PPM file
| 11kotlin
| 0iwsf |
function Read_PPM( filename )
local fp = io.open( filename, "rb" )
if fp == nil then return nil end
local data = fp:read( "*line" )
if data ~= "P6" then return nil end
repeat
data = fp:read( "*line" )
until string.find( data, "#" ) == nil
local image = {}
local size_x, size_y
size_x = string.match( data, "%d+" )
size_y = string.match( data, "%s%d+" )
data = fp:read( "*line" )
if tonumber(data) ~= 255 then return nil end
for i = 1, size_x do
image[i] = {}
end
for j = 1, size_y do
for i = 1, size_x do
image[i][j] = { string.byte( fp:read(1) ), string.byte( fp:read(1) ), string.byte( fp:read(1) ) }
end
end
fp:close()
return image
end | 1,086Bitmap/Read a PPM file
| 1lua
| 8nx0e |
null | 1,088Bitwise IO
| 0go
| jbu7d |
package raster
import (
"fmt"
"io"
"os"
) | 1,087Bitmap/Write a PPM file
| 0go
| dz0ne |
import Data.List
import Data.Char
import Control.Monad
import Control.Arrow
import System.Environment
int2bin :: Int -> [Int]
int2bin = unfoldr(\x -> if x==0 then Nothing
else Just (uncurry(flip(,)) (divMod x 2)))
bin2int :: [Int] -> Int
bin2int = foldr ((.(2 *)).(+)) 0
bitReader = map (chr.bin2int). takeWhile(not.null). unfoldr(Just. splitAt 7)
. (take =<< (7 *) . (`div` 7) . length)
bitWriter xs = tt ++ z00 where
tt = concatMap (take 7.(++repeat 0).int2bin.ord) xs
z00 = replicate (length xs `mod` 8) 0
main = do
(xs:_) <- getArgs
let bits = bitWriter xs
putStrLn "Text to compress:"
putStrLn $ '\t': xs
putStrLn $ "Uncompressed text length is " ++ show (length xs)
putStrLn $ "Compressed text has " ++ show (length bits `div` 8) ++ " bytes."
putStrLn "Read and decompress:"
putStrLn $ '\t': bitReader bits | 1,088Bitwise IO
| 8haskell
| odw8p |
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where
import Bitmap
import Data.Char
import System.IO
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
nil :: a
nil = undefined
readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c)
readNetpbm path = do
let die = fail "readNetpbm: bad format"
ppm <- readFile path
let (s, rest) = splitAt 2 ppm
unless (s == magicNumber) die
let getNum :: String -> IO (Int, String)
getNum ppm = do
let (s, rest) = span isDigit $ skipBlanks ppm
when (null s) die
return (read s, rest)
(width, rest) <- getNum rest
(height, rest) <- getNum rest
(_, c: rest) <-
if getMaxval then getNum rest else return (nil, rest)
unless (isSpace c) die
i <- stToIO $ listImage width height $
fromNetpbm $ map fromEnum rest
return i
where skipBlanks =
dropWhile isSpace .
until ((/= '#') . head) (tail . dropWhile (/= '\n')) .
dropWhile isSpace
magicNumber = netpbmMagicNumber (nil :: c)
getMaxval = not $ null $ netpbmMaxval (nil :: c)
writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO ()
writeNetpbm path i = withFile path WriteMode $ \h -> do
(width, height) <- stToIO $ dimensions i
let w = hPutStrLn h
w $ magicNumber
w $ show width ++ " " ++ show height
unless (null maxval) (w maxval)
stToIO (getPixels i) >>= hPutStr h . toNetpbm
where magicNumber = netpbmMagicNumber (nil :: c)
maxval = netpbmMaxval (nil :: c) | 1,087Bitmap/Write a PPM file
| 8haskell
| 5rcug |
class String
ALFABET = (..).to_a
def caesar_cipher(num)
self.tr(ALFABET.join, ALFABET.rotate(num).join)
end
end
encypted = .caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3) | 1,083Caesar cipher
| 14ruby
| rkrgs |
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PPMWriter {
public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
file.delete();
try (var os = new FileOutputStream(file, true);
var bw = new BufferedOutputStream(os)) {
var header = String.format("P6\n%d%d\n255\n",
bitmap.getWidth(), bitmap.getHeight());
bw.write(header.getBytes(StandardCharsets.US_ASCII));
for (var y = 0; y < bitmap.getHeight(); y++) {
for (var x = 0; x < bitmap.getWidth(); x++) {
var pixel = bitmap.getPixel(x, y);
bw.write(pixel.getRed());
bw.write(pixel.getGreen());
bw.write(pixel.getBlue());
}
}
}
}
} | 1,087Bitmap/Write a PPM file
| 9java
| 92zmu |
use strict;
use Image::Imlib2;
my $img = Image::Imlib2->load("out0.ppm");
$img->set_color(255, 255, 255, 255);
$img->draw_line(0,0, $img->width,$img->height);
$img->image_set_format("png");
$img->save("out1.png");
exit 0; | 1,086Bitmap/Read a PPM file
| 2perl
| 5rlu2 |
null | 1,088Bitwise IO
| 11kotlin
| bagkb |
null | 1,087Bitmap/Write a PPM file
| 11kotlin
| zyits |
use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};
fn main() {
let shift: u8 = env::args().nth(1)
.unwrap_or_else(|| exit_err("No shift provided", 2))
.parse()
.unwrap_or_else(|e| exit_err(e, 3));
let plain = get_input()
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));
let cipher = plain.chars()
.map(|c| {
let case = if c.is_uppercase() {'A'} else {'a'} as u8;
if c.is_alphabetic() { (((c as u8 - case + shift)% 26) + case) as char } else { c }
}).collect::<String>();
println!("Cipher text: {}", cipher.trim());
}
fn get_input() -> io::Result<String> {
print!("Plain text: ");
try!(io::stdout().flush());
let mut buf = String::new();
try!(io::stdin().read_line(&mut buf));
Ok(buf)
}
fn exit_err<T: Display>(msg: T, code: i32) ->! {
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
process::exit(code);
} | 1,083Caesar cipher
| 15rust
| 7b7rc |
local function BitWriter() return {
accumulator = 0, | 1,088Bitwise IO
| 1lua
| perbw |
null | 1,087Bitmap/Write a PPM file
| 1lua
| 3mnzo |
object Caesar {
private val alphaU='A' to 'Z'
private val alphaL='a' to 'z'
def encode(text:String, key:Int)=text.map{
case c if alphaU.contains(c) => rot(alphaU, c, key)
case c if alphaL.contains(c) => rot(alphaL, c, key)
case c => c
}
def decode(text:String, key:Int)=encode(text,-key)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
} | 1,083Caesar cipher
| 16scala
| kakhk |
use strict;
sub write_bits( $$$$ )
{
my ($out, $l, $num, $q) = @_;
$l .= substr(unpack("B*", pack("N", $num)),
-$q);
if ( (length($l) > 8) ) {
my $left = substr($l, 8);
print $out pack("B8", $l);
$l = $left;
}
return $l;
}
sub flush_bits( $$ )
{
my ($out, $b) = @_;
print $out pack("B*", $b);
}
sub read_bits( $$$ )
{
my ( $in, $b, $n ) = @_;
if ( $n > 32 ) { return 0; }
while ( length($b) < $n ) {
my $v;
my $red = read($in, $v, 1);
if ( $red < 1 ) { return ( 0, -1 ); }
$b .= substr(unpack("B*", $v), -8);
}
my $bits = "0" x ( 32-$n ) . substr($b, 0, $n);
my $val = unpack("N", pack("B32", $bits));
$b = substr($b, $n);
return ($val, $b);
} | 1,088Bitwise IO
| 2perl
| 69n36 |
import io
ppmtxt = '''P3
4 4
15
0 0 0 0 0 0 0 0 0 15 0 15
0 0 0 0 15 7 0 0 0 0 0 0
0 0 0 0 0 0 0 15 7 0 0 0
15 0 15 0 0 0 0 0 0 0 0 0
'''
def tokenize(f):
for line in f:
if line[0] != '
for t in line.split():
yield t
def ppmp3tobitmap(f):
t = tokenize(f)
nexttoken = lambda: next(t)
assert 'P3' == nexttoken(), 'Wrong filetype'
width, height, maxval = (int(nexttoken()) for i in range(3))
bitmap = Bitmap(width, height, Colour(0, 0, 0))
for h in range(height-1, -1, -1):
for w in range(0, width):
bitmap.set(w, h, Colour( *(int(nexttoken()) for i in range(3))))
return bitmap
print('Original Colour PPM file')
print(ppmtxt)
ppmfile = io.StringIO(ppmtxt)
bitmap = ppmp3tobitmap(ppmfile)
print('Grey PPM:')
bitmap.togreyscale()
ppmfileout = io.StringIO('')
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
'''
The print statements above produce the following output:
Original Colour PPM file
P3
4 4
15
0 0 0 0 0 0 0 0 0 15 0 15
0 0 0 0 15 7 0 0 0 0 0 0
0 0 0 0 0 0 0 15 7 0 0 0
15 0 15 0 0 0 0 0 0 0 0 0
Grey PPM:
P3
4 4
11
0 0 0 0 0 0 0 0 0 4 4 4
0 0 0 11 11 11 0 0 0 0 0 0
0 0 0 0 0 0 11 11 11 0 0 0
4 4 4 0 0 0 0 0 0 0 0 0
''' | 1,086Bitmap/Read a PPM file
| 3python
| 4725k |
typedef unsigned int histogram_t;
typedef histogram_t *histogram;
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h); | 1,089Bitmap/Histogram
| 5c
| 0i1st |
use Imager;
$image = Imager->new(xsize => 200, ysize => 200);
$image->box(filled => 1, color => red);
$image->box(filled => 1, color => black,
xmin => 50, ymin => 50,
xmax => 150, ymax => 150);
$image->write(file => 'bitmap.ppm') or die $image->errstr; | 1,087Bitmap/Write a PPM file
| 2perl
| bark4 |
class Pixmap
def self.open(filename)
bitmap = nil
File.open(filename, 'r') do |f|
header = [f.gets.chomp, f.gets.chomp, f.gets.chomp]
width, height = header[1].split.map {|n| n.to_i }
if header[0]!= 'P6' or header[2]!= '255' or width < 1 or height < 1
raise StandardError,
end
f.binmode
bitmap = self.new(width, height)
height.times do |y|
width.times do |x|
red, green, blue = f.read(3).unpack('C3')
bitmap[x,y] = RGBColour.new(red, green, blue)
end
end
end
bitmap
end
end
colour_bitmap = Pixmap.new(20, 30)
colour_bitmap.fill(RGBColour::BLUE)
colour_bitmap.height.times {|y| [9,10,11].each {|x| colour_bitmap[x,y]=RGBColour::GREEN}}
colour_bitmap.width.times {|x| [14,15,16].each {|y| colour_bitmap[x,y]=RGBColour::GREEN}}
colour_bitmap.save('testcross.ppm')
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm') | 1,086Bitmap/Read a PPM file
| 14ruby
| rhugs |
class BitWriter(object):
def __init__(self, f):
self.accumulator = 0
self.bcount = 0
self.out = f
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.flush()
def __del__(self):
try:
self.flush()
except ValueError:
pass
def _writebit(self, bit):
if self.bcount == 8:
self.flush()
if bit > 0:
self.accumulator |= 1 << 7-self.bcount
self.bcount += 1
def writebits(self, bits, n):
while n > 0:
self._writebit(bits & 1 << n-1)
n -= 1
def flush(self):
self.out.write(bytearray([self.accumulator]))
self.accumulator = 0
self.bcount = 0
class BitReader(object):
def __init__(self, f):
self.input = f
self.accumulator = 0
self.bcount = 0
self.read = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def _readbit(self):
if not self.bcount:
a = self.input.read(1)
if a:
self.accumulator = ord(a)
self.bcount = 8
self.read = len(a)
rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1
self.bcount -= 1
return rv
def readbits(self, n):
v = 0
while n > 0:
v = (v << 1) | self._readbit()
n -= 1
return v
if __name__ == '__main__':
import os
import sys
module_name = os.path.splitext(os.path.basename(__file__))[0]
bitio = __import__(module_name)
with open('bitio_test.dat', 'wb') as outfile:
with bitio.BitWriter(outfile) as writer:
chars = '12345abcde'
for ch in chars:
writer.writebits(ord(ch), 7)
with open('bitio_test.dat', 'rb') as infile:
with bitio.BitReader(infile) as reader:
chars = []
while True:
x = reader.readbits(7)
if not reader.read:
break
chars.append(chr(x))
print(''.join(chars)) | 1,088Bitwise IO
| 3python
| ycd6q |
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];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, );
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$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));
$b->writeP6('p6.ppm'); | 1,087Bitmap/Write a PPM file
| 12php
| 69d3g |
parser.rs:
use super::{Color, ImageFormat};
use std::str::from_utf8;
use std::str::FromStr;
pub fn parse_version(input: &[u8]) -> nom::IResult<&[u8], ImageFormat> {
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::line_ending;
use nom::combinator::map;
use nom::sequence::terminated; | 1,086Bitmap/Read a PPM file
| 15rust
| 7k5rc |
import scala.io._
import scala.swing._
import java.io._
import java.awt.Color
import javax.swing.ImageIcon
object Pixmap {
private case class PpmHeader(format:String, width:Int, height:Int, maxColor:Int)
def load(filename:String):Option[RgbBitmap]={
implicit val in=new BufferedInputStream(new FileInputStream(filename))
val header=readHeader
if(header.format=="P6")
{
val bm=new RgbBitmap(header.width, header.height);
for(y <- 0 until bm.height; x <- 0 until bm.width; c=readColor)
bm.setPixel(x, y, c)
return Some(bm)
}
None
}
private def readHeader(implicit in:InputStream)={
var format=readLine
var line=readLine
while(line.startsWith("#")) | 1,086Bitmap/Read a PPM file
| 16scala
| k1rhk |
bool? value = null | 1,090Boolean values
| 5c
| dzxnv |
void quad_bezier(
image img,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2,
unsigned int x3, unsigned int y3,
color_component r,
color_component g,
color_component b ); | 1,091Bitmap/Bézier curves/Quadratic
| 5c
| eqrav |
function putpixel {
echo -en "\e[$2;$1H
}
function drawcircle {
x0=$1
y0=$2
radius=$3
for y in $( seq $((y0-radius)) $((y0+radius)) )
do
echo -en "\e[${y}H"
for x in $( seq $((x0+radius)) )
do
echo -n "-"
done
done
x=$((radius-1))
y=0
dx=1
dy=1
err=$((dx-(radius<<1)))
while [ $x -ge $y ]
do
putpixel $(( x0 + x )) $(( y0 + y ))
putpixel $(( x0 + y )) $(( y0 + x ))
putpixel $(( x0 - y )) $(( y0 + x ))
putpixel $(( x0 - x )) $(( y0 + y ))
putpixel $(( x0 - x )) $(( y0 - y ))
putpixel $(( x0 - y )) $(( y0 - x ))
putpixel $(( x0 + y )) $(( y0 - x ))
putpixel $(( x0 + x )) $(( y0 - y ))
if [ $err -le 0 ]
then
((++y))
((err+=dy))
((dy+=2))
fi
if [ $err -gt 0 ]
then
((--x))
((dx+=2))
((err+=dx-(radius<<1)))
fi
done
}
clear
drawcircle 13 13 11
echo -en "\e[H" | 1,092Bitmap/Midpoint circle algorithm
| 4bash
| eqga3 |
foreach(var 1 42 ON yes True y Princess
0 OFF no False n Princess-NOTFOUND)
if(var)
message(STATUS "${var} is true.")
else()
message(STATUS "${var} is false.")
endif()
endforeach(var) | 1,090Boolean values
| 6clojure
| 69o3q |
package raster
import "math"
func (g *Grmap) Histogram(bins int) []int {
if bins <= 0 {
bins = g.cols
}
h := make([]int, bins)
for _, p := range g.px {
h[int(p)*(bins-1)/math.MaxUint16]++
}
return h
}
func (g *Grmap) Threshold(t uint16) {
for i, p := range g.px {
if p < t {
g.px[i] = 0
} else {
g.px[i] = math.MaxUint16
}
}
} | 1,089Bitmap/Histogram
| 0go
| ugyvt |
module Bitmap.BW(module Bitmap.BW) where
import Bitmap
import Control.Monad.ST
newtype BW = BW Bool deriving (Eq, Ord)
instance Color BW where
luminance (BW False) = 0
luminance _ = 255
black = BW False
white = BW True
toNetpbm [] = ""
toNetpbm l = init (concatMap f line) ++ "\n" ++ toNetpbm rest
where (line, rest) = splitAt 35 l
f (BW False) = "1 "
f _ = "0 "
fromNetpbm = map f
where f 1 = black
f _ = white
netpbmMagicNumber _ = "P1"
netpbmMaxval _ = ""
toBWImage :: Color c => Image s c -> ST s (Image s BW)
toBWImage = toBWImage' 128
toBWImage' :: Color c => Int -> Image s c -> ST s (Image s BW)
toBWImage' darkestWhite = mapImage $ f . luminance
where f x | x < darkestWhite = black
| otherwise = white | 1,089Bitmap/Histogram
| 8haskell
| wshed |
void raster_circle(
image img,
unsigned int x0,
unsigned int y0,
unsigned int radius,
color_component r,
color_component g,
color_component b ); | 1,092Bitmap/Midpoint circle algorithm
| 5c
| x07wu |
def crunch(ascii)
bitstring = ascii.bytes.collect {|b| % b}.join
[bitstring].pack()
end
def expand(binary)
bitstring = binary.unpack()[0]
bitstring.scan(/[01]{7}/).collect {|b| b.to_i(2).chr}.join
end
original =
puts
filename =
File.open(filename, ) do |fh|
fh.binmode
fh.print crunch(original)
end
filesize = File.size(filename)
puts
expanded = File.open(filename, ) do |fh|
fh.binmode
expand(fh.read)
end
if original == expanded
puts
else
puts
end | 1,088Bitwise IO
| 14ruby
| 92tmz |
import io
ppmfileout = io.StringIO('')
def writeppmp3(self, f):
self.writeppm(f, ppmformat='P3')
def writeppm(self, f, ppmformat='P6'):
assert ppmformat in ['P3', 'P6'], 'Format wrong'
magic = ppmformat + '\n'
comment = '
maxval = max(max(max(bit) for bit in row) for row in self.map)
assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'
if ppmformat == 'P6':
fwrite = lambda s: f.write(bytes(s, 'UTF-8'))
maxval = 255
else:
fwrite = f.write
numsize=len(str(maxval))
fwrite(magic)
fwrite(comment)
fwrite('%i%i\n%i\n'% (self.width, self.height, maxval))
for h in range(self.height-1, -1, -1):
for w in range(self.width):
r, g, b = self.get(w, h)
if ppmformat == 'P3':
fwrite(' %*i%*i%*i'% (numsize, r, numsize, g, numsize, b))
else:
fwrite('%c%c%c'% (r, g, b))
if ppmformat == 'P3':
fwrite('\n')
Bitmap.writeppmp3 = writeppmp3
Bitmap.writeppm = writeppm
bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
'''
The print statement above produces the following output:
P3
4 4
255
0 0 0 0 0 0 0 0 0 127 0 63
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0
'''
ppmfileout = open('tmp.ppm', 'wb')
bitmap.writeppm(ppmfileout)
ppmfileout.close() | 1,087Bitmap/Write a PPM file
| 3python
| pe7bm |
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImageProcessing {
;
public static void main(String[] args) throws IOException {
BufferedImage img = ImageIO.read(new File("example.png"));
BufferedImage bwimg = toBlackAndWhite(img);
ImageIO.write(bwimg, "png", new File("example-bw.png"));
}
private static int luminance(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return (r + b + g) / 3;
}
private static BufferedImage toBlackAndWhite(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = computeHistogram(img);
int median = getMedian(width * height, histo);
BufferedImage bwimg = new BufferedImage(width, height, img.getType());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000);
}
}
return bwimg;
}
private static int[] computeHistogram(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int[] histo = new int[256];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
histo[luminance(img.getRGB(x, y))]++;
}
}
return histo;
}
private static int getMedian(int total, int[] histo) {
int median = 0;
int sum = 0;
for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) {
sum += histo[i];
median++;
}
return median;
}
} | 1,089Bitmap/Histogram
| 9java
| k15hm |
pub trait Codec<Input = u8> {
type Output: Iterator<Item = u8>;
fn accept(&mut self, input: Input) -> Self::Output;
fn finish(self) -> Self::Output;
}
#[derive(Debug)]
pub struct BitDiscard {
buf: u16, | 1,088Bitwise IO
| 15rust
| cvz9z |
library(pixmap)
pixmap::write.pnm
write.pnm(theimage, filename) | 1,087Bitmap/Write a PPM file
| 13r
| jb578 |
func usage(_ e:String) {
print("error: \(e)")
print("./caeser -e 19 a-secret-string")
print("./caeser -d 19 tskxvjxlskljafz")
}
func charIsValid(_ c:Character) -> Bool {
return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) | 1,083Caesar cipher
| 17swift
| ghg49 |
null | 1,089Bitmap/Histogram
| 11kotlin
| gjc4d |
package raster
const b2Seg = 20
func (b *Bitmap) Bzier2(x1, y1, x2, y2, x3, y3 int, p Pixel) {
var px, py [b2Seg + 1]int
fx1, fy1 := float64(x1), float64(y1)
fx2, fy2 := float64(x2), float64(y2)
fx3, fy3 := float64(x3), float64(y3)
for i := range px {
c := float64(i) / b2Seg
a := 1 - c
a, b, c := a*a, 2 * c * a, c*c
px[i] = int(a*fx1 + b*fx2 + c*fx3)
py[i] = int(a*fy1 + b*fy2 + c*fy3)
}
x0, y0 := px[0], py[0]
for i := 1; i <= b2Seg; i++ {
x1, y1 := px[i], py[i]
b.Line(x0, y0, x1, y1, p)
x0, y0 = x1, y1
}
}
func (b *Bitmap) Bzier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) {
b.Bzier2(x1, y1, x2, y2, x3, y3, c.Pixel())
} | 1,091Bitmap/Bézier curves/Quadratic
| 0go
| 92nmt |
import Bitmap
import Bitmap.Line
import Control.Monad
import Control.Monad.ST
type Point = (Double, Double)
fromPixel (Pixel (x, y)) = (toEnum x, toEnum y)
toPixel (x, y) = Pixel (round x, round y)
pmap :: (Double -> Double) -> Point -> Point
pmap f (x, y) = (f x, f y)
onCoordinates :: (Double -> Double -> Double) -> Point -> Point -> Point
onCoordinates f (xa, ya) (xb, yb) = (f xa xb, f ya yb)
instance Num Point where
(+) = onCoordinates (+)
(-) = onCoordinates (-)
(*) = onCoordinates (*)
negate = pmap negate
abs = pmap abs
signum = pmap signum
fromInteger i = (i', i')
where i' = fromInteger i
bzier:: Color c =>
Image s c -> Pixel -> Pixel -> Pixel -> c -> Int ->
ST s ()
bzier
i
(fromPixel -> p1) (fromPixel -> p2) (fromPixel -> p3)
c samples =
zipWithM_ f ts (tail ts)
where ts = map (/ top) [0 .. top]
where top = toEnum $ samples - 1
curvePoint t =
pt (t' ^^ 2) p1 +
pt (2 * t * t') p2 +
pt (t ^^ 2) p3
where t' = 1 - t
pt n p = pmap (*n) p
f (curvePoint -> p1) (curvePoint -> p2) =
line i (toPixel p1) (toPixel p2) c | 1,091Bitmap/Bézier curves/Quadratic
| 8haskell
| bauk2 |
(defn draw-circle [draw-function x0 y0 radius]
(letfn [(put [x y m]
(let [x+ (+ x0 x)
x- (- x0 x)
y+ (+ y0 y)
y- (- y0 y)
x0y+ (+ x0 y)
x0y- (- x0 y)
xy0+ (+ y0 x)
xy0- (- y0 x)]
(draw-function x+ y+)
(draw-function x+ y-)
(draw-function x- y+)
(draw-function x- y-)
(draw-function x0y+ xy0+)
(draw-function x0y+ xy0-)
(draw-function x0y- xy0+)
(draw-function x0y- xy0-)
(let [[y m] (if (pos? m)
[(dec y) (- m (* 8 y))]
[y m])]
(when (<= x y)
(put (inc x)
y
(+ m 4 (* 8 x)))))))]
(put 0 radius (- 5 (* 4 radius))))) | 1,092Bitmap/Midpoint circle algorithm
| 6clojure
| odp8j |
function Histogram( image )
local size_x, size_y = #image, #image[1]
local histo = {}
for i = 0, 255 do
histo[i] = 0
end
for i = 1, size_x do
for j = 1, size_y do
histo[ image[i][j] ] = histo[ image[i][j] ] + 1
end
end
return histo
end
function FindMedian( histogram )
local sum_l, sum_r = 0, 0
local left, right = 0, 255
repeat
if sum_l < sum_r then
sum_l = sum_l + histogram[left]
left = left + 1
else
sum_r = sum_r + histogram[right]
right = right - 1
end
until left == right
return left
end
bitmap = Read_PPM( "inputimage.ppm" )
gray_im = ConvertToGrayscaleImage( bitmap )
histogram = Histogram( gray_im )
median = FindMedian( histogram )
for i = 1, #gray_im do
for j = 1, #gray_im[1] do
if gray_im[i][j] < median then
gray_im[i][j] = 0
else
gray_im[i][j] = 255
end
end
end
bitmap = ConvertToColorImage( gray_im )
Write_PPM( "outputimage.ppm", bitmap ) | 1,089Bitmap/Histogram
| 1lua
| rhlga |
class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts , ,
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end | 1,087Bitmap/Write a PPM file
| 14ruby
| axh1s |
use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
} | 1,087Bitmap/Write a PPM file
| 15rust
| eqkaj |
object Pixmap {
def save(bm:RgbBitmap, filename:String)={
val out=new DataOutputStream(new FileOutputStream(filename))
out.writeBytes("P6\u000a%d%d\u000a%d\u000a".format(bm.width, bm.height, 255))
for(y <- 0 until bm.height; x <- 0 until bm.width; c=bm.getPixel(x, y)){
out.writeByte(c.getRed)
out.writeByte(c.getGreen)
out.writeByte(c.getBlue)
}
}
} | 1,087Bitmap/Write a PPM file
| 16scala
| q81xw |
Subsets and Splits