task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Objeck | Objeck |
class Caesar {
function : native : Encode(enc : String, offset : Int) ~ String {
offset := offset % 26 + 26;
encoded := "";
enc := enc->ToLower();
each(i : enc) {
c := enc->Get(i);
if(c->IsChar()) {
j := (c - 'a' + offset) % 26;
encoded->Append(j + 'a');
}
else {
encoded->Append(c);
};
};
return encoded;
}
function : Decode(enc : String, offset : Int) ~ String {
return Encode(enc, offset * -1);
}
function : Main(args : String[]) ~ Nil {
enc := Encode("The quick brown fox Jumped over the lazy Dog", 12);
enc->PrintLine();
Decode(enc, 12)->PrintLine();
}
}
|
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #zkl | zkl | img:=PPM.readPPMFile("fractal.ppm");
p:=System.popen(0'|convert ppm:- jpg:"fractal.jpg"|,"w");
img.write(p); p.close(); |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Scheme | Scheme |
;generate a random non-repeating list of 4 digits, 1-9 inclusive
(define (get-num)
(define (gen lst)
(if (= (length lst) 4) lst
(let ((digit (+ (random 9) 1)))
(if (member digit lst) ;make sure the new digit isn't in the
;list
(gen lst)
(gen (cons digit lst))))))
(string->list (apply string-append (map number->string (gen '())))))
;is g a valid guess (that is, non-repeating, four digits 1-9
;inclusive?)
(define (valid-guess? g)
(let ((g-num (string->number (apply string g))))
;does the same digit appear twice in lst?
(define (repeats? lst)
(cond ((null? lst) #f)
((member (car lst) (cdr lst)) #t)
(else (repeats? (cdr lst)))))
(and g-num
(> g-num 1233)
(< g-num 9877)
(not (repeats? g)))))
;return '(cows bulls) for the given guess
(define (score answer guess)
;total cows + bulls
(define (cows&bulls a g)
(cond ((null? a) 0)
((member (car a) g) (+ 1 (cows&bulls (cdr a) g)))
(else (cows&bulls (cdr a) g))))
;bulls only
(define (bulls a g)
(cond ((null? a) 0)
((equal? (car a) (car g)) (+ 1 (bulls (cdr a) (cdr g))))
(else (bulls (cdr a) (cdr g)))))
(list (- (cows&bulls answer guess) (bulls answer guess)) (bulls answer guess)))
;play the game
(define (bull-cow answer)
;get the user's guess as a list
(define (get-guess)
(let ((e (read)))
(if (number? e)
(string->list (number->string e))
(string->list (symbol->string e)))))
(display "Enter a guess: ")
(let ((guess (get-guess)))
(if (valid-guess? guess)
(let ((bulls (cadr (score answer guess)))
(cows (car (score answer guess))))
(if (= bulls 4)
(display "You win!\n")
(begin
(display bulls)
(display " bulls, ")
(display cows)
(display " cows.\n")
(bull-cow answer))))
(begin
(display "Invalid guess.\n")
(bull-cow answer)))))
(bull-cow (get-num))
|
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #OCaml | OCaml | let read_image ~filename =
if not(Sys.file_exists filename)
then failwith(Printf.sprintf "the file %s does not exist" filename);
let cmd = Printf.sprintf "convert \"%s\" ppm:-" filename in
let ic, oc = Unix.open_process cmd in
let img = read_ppm ~ic in
(img)
;; |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Perl | Perl | # 20211226 Perl programming solution
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"}; # some kind of tie ?
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); |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #OCaml | OCaml | let islower c =
c >= 'a' && c <= 'z'
let isupper c =
c >= 'A' && c <= 'Z'
let rot x str =
let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and lowchars = "abcdefghijklmnopqrstuvwxyz" in
let rec decal x =
if x < 0 then decal (x + 26) else x
in
let x = (decal x) mod 26 in
let decal_up = x - (int_of_char 'A')
and decal_low = x - (int_of_char 'a') in
String.map (fun c ->
if islower c then
let j = ((int_of_char c) + decal_low) mod 26 in
lowchars.[j]
else if isupper c then
let j = ((int_of_char c) + decal_up) mod 26 in
upchars.[j]
else
c
) str |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Scratch | Scratch | $ include "seed7_05.s7i";
const proc: main is func
local
const integer: size is 4;
var set of char: digits is {'1' .. '9'};
var string: chosen is " " mult size;
var integer: guesses is 0;
var string: guess is "";
var integer: pos is 0;
var integer: bulls is 0;
var integer: cows is 0;
var boolean: okay is FALSE;
begin
for pos range 1 to 4 do
chosen @:= [pos] rand(digits);
excl(digits, chosen[pos]);
end for;
writeln("I have chosen a number from " <& size <& " unique digits from 1 to 9 arranged in a random order.");
writeln("You need to input a " <& size <& " digit, unique digit number as a guess at what I have chosen");
repeat
incr(guesses);
repeat
write("Next guess [" <& guesses <& "]: ");
readln(guess);
okay := length(guess) = size;
for key pos range guess do
okay := okay and guess[pos] in {'1' .. '9'} and pos(guess[succ(pos) ..], guess[pos]) = 0;
end for;
if not okay then
writeln("Problem, try again. You need to enter " <& size <& " unique digits from 1 to 9");
end if;
until okay;
if guess <> chosen then
bulls := 0;
cows := 0;
for key pos range chosen do
if guess[pos] = chosen[pos] then
incr(bulls);
elsif pos(chosen, guess[pos]) <> 0 then
incr(cows);
end if;
end for;
writeln(" " <& bulls <& " Bulls");
writeln(" " <& cows <& " Cows");
end if;
until guess = chosen;
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
end func; |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Phix | Phix | -- demo\rosetta\Bitmap_Read_an_image_through_a_pipe.exw
without js -- file i/o, system_exec(), pipes[!!]
include builtins\pipeio.e
include ppm.e -- read_ppm(), write_ppm()
sequence pipes = repeat(0,3)
pipes[PIPOUT] = create_pipe(INHERIT_READ)
-- Create the child process, with replacement stdout.
string cmd = sprintf("%s viewppm -load test.jpg",{get_interpreter(true)})
atom hProc = system_exec(cmd, 12, pipes),
hPipe = pipes[PIPOUT][READ_PIPE]
string ppm = read_from_pipe(hPipe, hProc)
while true do
object chunk = read_from_pipe(hPipe, hProc)
if chunk=-1 then exit end if
ppm &= chunk
end while
pipes = close_handles(pipes)
if 0 then
sequence img = read_ppm(ppm,bText:=true)
write_ppm("Lenapipe.ppm", img)
else -- or
integer fn = open("Lenapipe.ppm","wb")
puts(fn,ppm)
close(fn)
end if
?"done"
{} = wait_key()
|
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #PicoLisp | PicoLisp | (setq *Ppm (ppmRead '("convert" "img.jpg" "ppm:-"))) |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Oforth | Oforth | : ceasar(c, key)
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;
: cipherE(s, key) s map(#[ key ceasar ]) charsAsString ;
: cipherD(s, key) cipherE(s, 26 key - ) ; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const integer: size is 4;
var set of char: digits is {'1' .. '9'};
var string: chosen is " " mult size;
var integer: guesses is 0;
var string: guess is "";
var integer: pos is 0;
var integer: bulls is 0;
var integer: cows is 0;
var boolean: okay is FALSE;
begin
for pos range 1 to 4 do
chosen @:= [pos] rand(digits);
excl(digits, chosen[pos]);
end for;
writeln("I have chosen a number from " <& size <& " unique digits from 1 to 9 arranged in a random order.");
writeln("You need to input a " <& size <& " digit, unique digit number as a guess at what I have chosen");
repeat
incr(guesses);
repeat
write("Next guess [" <& guesses <& "]: ");
readln(guess);
okay := length(guess) = size;
for key pos range guess do
okay := okay and guess[pos] in {'1' .. '9'} and pos(guess[succ(pos) ..], guess[pos]) = 0;
end for;
if not okay then
writeln("Problem, try again. You need to enter " <& size <& " unique digits from 1 to 9");
end if;
until okay;
if guess <> chosen then
bulls := 0;
cows := 0;
for key pos range chosen do
if guess[pos] = chosen[pos] then
incr(bulls);
elsif pos(chosen, guess[pos]) <> 0 then
incr(cows);
end if;
end for;
writeln(" " <& bulls <& " Bulls");
writeln(" " <& cows <& " Cows");
end if;
until guess = chosen;
writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
end func; |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Python | Python |
"""
Adapted from https://stackoverflow.com/questions/26937143/ppm-to-jpeg-jpg-conversion-for-python-3-4-1
Requires pillow-5.3.0 with Python 3.7.1 32-bit on Windows.
Sample ppm graphics files from http://www.cs.cornell.edu/courses/cs664/2003fa/images/
"""
from PIL import Image
# boxes_1.jpg is the jpg version of boxes_1.ppm
im = Image.open("boxes_1.jpg")
im.save("boxes_1v2.ppm")
|
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Racket | Racket |
(define (read-ppm port)
(parameterize ([current-input-port port])
(define magic (read-line))
(match-define (list w h) (string-split (read-line) " "))
(define width (string->number w))
(define height (string->number h))
(define maxcol (string->number (read-line)))
(define bm (make-object bitmap% width height))
(define dc (new bitmap-dc% [bitmap bm]))
(send dc set-smoothing 'unsmoothed)
(define (adjust v) (* 255 (/ v maxcol)))
(for/list ([x width])
(for/list ([y height])
(define red (read-byte))
(define green (read-byte))
(define blue (read-byte))
(define color (make-object color% (adjust red) (adjust green) (adjust blue)))
(send dc set-pen color 1 'solid)
(send dc draw-point x y)))
bm))
(define (image->bmp filename)
(define command (format "convert ~a ppm:-" filename))
(match-define (list in out pid err ctrl) (process command))
(define bmp (read-ppm in))
(close-input-port in)
(close-output-port out)
bmp)
(image->bmp "input.jpg") |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Raku | Raku | class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @.data;
}
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
sub getline ( $proc ) {
my $line = '#'; # skip comment when reading a .png
$line = $proc.out.get while $line.substr(0,1) eq '#';
$line;
}
my $filename = './camelia.png';
my $proc = run 'convert', $filename, 'ppm:-', :enc('ISO-8859-1'), :out;
my $type = getline($proc);
my ($width, $height) = getline($proc).split: ' ';
my $depth = getline($proc);
my Bitmap $b = Bitmap.new( width => $width.Int, height => $height.Int) but PPM;
$b.data = $proc.out.slurp.ords.rotor(3).map:
{ Pixel.new(R => .[0], G => .[1], B => .[2]) };
'./camelia.ppm'.IO.open(:bin, :w).write: $b.P6; |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #OOC | OOC | main: func (args: String[]) {
shift := args[1] toInt()
if (args length != 3) {
"Usage: #{args[0]} [number] [sentence]" println()
"Incorrect number of arguments." println()
} else if (!shift && args[1] != "0"){
"Usage: #{args[0]} [number] [sentence]" println()
"Number is not a valid number." println()
} else {
str := ""
for (c in args[2]) {
if (c alpha?()) {
c = (c lower?() ? 'a' : 'A') + (26 + c toLower() - 'a' + shift) % 26
}
str += c
}
str println()
}
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #SenseTalk | SenseTalk | repeat forever
repeat forever
put random(1111,9999) into num
if character 1 of num is not equal to character 2 of num
if character 1 of num is not equal to character 3 of num
if character 1 of num is not equal to character 4 of num
if character 2 of num is not equal to character 3 of num
if character 2 of num is not equal to character 4 of num
if character 3 of num is not equal to character 4 of num
if num does not contain 0
exit repeat
end if
end if
end if
end if
end if
end if
end if
end repeat
set description to "Guess the 4 digit number" & newline & "- zero's excluded" & newline & "- each digit is unique" & newline & newline & "Receive 1 Bull for each digit that equals the corresponding digit in the random number." & newline & newline & "Receive 1 Cow for each digit that appears in the wrong position." & newline
repeat forever
repeat forever
Ask "Guess the number" title "Bulls & Cows" message description
put it into guess
if number of characters in guess is equal to 4
exit repeat
else if guess is ""
Answer "" with "Play" or "Quit" title "Quit Bulls & Cows?"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
end if
end repeat
set score to {
bulls: {
qty: 0,
values: []
},
cows: {
qty: 0,
values: []
}
}
repeat the number of characters in num times
if character the counter of guess is equal to character the counter of num
add 1 to score.bulls.qty
insert character the counter of guess into score.bulls.values
else
if num contains character the counter of guess
if character the counter of guess is not equal to character the counter of num
if score.bulls.values does not contain character the counter of guess and score.cows.values does not contain character the counter of guess
add 1 to score.cows.qty
insert character the counter of guess into score.cows.values
end if
end if
end if
end if
end repeat
set showScores to "Your score is:" & newline & newline & "Bulls:" && score.bulls.qty & newline & newline & "Cows:" && score.cows.qty
if guess is not equal to num
Answer showScores with "Guess Again" or "Quit" title "Score"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
else
set winShowScores to showScores & newline & newline & "Your Guess:" && guess & newline & "Random Number:" && num & newline
Answer winShowScores with "Play Again" or "Quit" title "You Win!"
put it into myAnswer
if myAnswer is "Quit"
exit all
end if
exit repeat
end if
end repeat
end repeat |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Ruby | Ruby | # frozen_string_literal: true
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, "file '#{filename}' does not start with the expected header"
end
ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)
bitmap = new(width, height)
height.times do |y|
width.times do |x|
# read 3 bytes
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("convert jpg:#{filename} ppm:-", 'r'))
end
end
bitmap = Pixmap.open_from_jpeg('foto.jpg')
bitmap.save('foto.ppm')
|
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Tcl | Tcl | package require Tk
proc magickalReadImage {bufferImage fileName} {
set f [open |[list convert [file normalize $fileName] ppm:-] "rb"]
try {
$bufferImage put [read $f] -format ppm
} finally {
close $f
}
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PARI.2FGP | PARI/GP | enc(s,n)={
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k+n-97)%26+97, if(k>64&&k<91, (k+n-65)%26+65, k)),
Vec(Vecsmall(s)))))
};
dec(s,n)=enc(s,-n); |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Shale | Shale | #!/usr/local/bin/shale
maths library
file library
string library
n0 var
n1 var
n2 var
n3 var
g0 var
g1 var
g2 var
g3 var
init dup var {
c guess:: var
} =
getNum dup var {
random maths::() 15 >> 9 % 1 +
} =
game dup var {
haveWon dup var false =
ans var
i var
c var
b var
c guess:: 0 =
n0 getNum() =
n1 getNum() =
{ n1 n0 == } {
n1 getNum() =
} while
n2 getNum() =
{ n2 n0 == n2 n1 == or } {
n2 getNum() =
} while
n3 getNum() =
{ n3 n0 == n3 n1 == n3 n2 == or or } {
n3 getNum() =
} while
"New game" println
{ haveWon not } {
"> " print
stdin file:: fgets file::() {
ans swap atoi string::() =
g3 ans 10 % =
g2 ans 10 / 10 % =
g1 ans 100 / 10 % =
g0 ans 1000 / 10 % =
g0 0 > g0 10 < and g1 0 > g1 10 < and g2 0 > g2 10 < and g3 0 > g3 10 < and and and and {
c 0 =
b 0 =
g0 n0 == {
b++
} {
g0 n1 == g0 n2 == g0 n3 == or or { c++ } ifthen
} if
g1 n1 == {
b++
} {
g1 n0 == g1 n2 == g1 n3 == or or { c++ } ifthen
} if
g2 n2 == {
b++
} {
g2 n0 == g2 n1 == g2 n3 == or or { c++ } ifthen
} if
g3 n3 == {
b++
} {
g3 n0 == g3 n1 == g3 n2 == or or { c++ } ifthen
} if
i c guess:: =
i.value guess:: guess:: defined not {
i.value guess:: guess:: var
i.value cow:: guess:: var
i.value bull:: guess:: var
} ifthen
i.value guess:: guess:: ans =
i.value cow:: guess:: c =
i.value bull:: guess:: b =
c guess::++
"Go Guess Cows Bulls" println
i 0 =
{ i c guess:: < } {
i.value bull:: guess:: i.value cow:: guess:: i.value guess:: guess:: i 1 + "%2d %d %4d %5d\n" printf
i++
} while
b 4 == { haveWon true = } ifthen
} {
"Illegal input" println
} if
} {
0 exit
} if
} while
} =
play dup var {
{ true } {
game()
} while
} =
init()
play() |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Wren | Wren | import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
import "plugin" for Plugin
Plugin.load("pipeconv")
import "pipeconv" for PipeConv
class Bitmap {
construct new(fileName, fileName2, fileName3, width, height) {
Window.title = "Bitmap - read image via pipe"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_fn3 = fileName3
// convert .jpg file to .ppm via a pipe
PipeConv.convert(fileName, fileName2)
// load the .ppm file
loadPPMFile(fileName2)
}
init() {
toGrayScale()
// display gray scale image
_bmp2.draw(0, 0)
// save it to file
_bmp2.saveToFile(_fn3)
}
loadPPMFile(fileName) {
var ppm = FileSystem.load(fileName)
if (ppm[0..1] != "P6") {
System.print("The loaded file is not a P6 file.")
Process.exit()
}
var lines = ppm.split("\n")
if (Num.fromString(lines[2]) > 255) {
System.print("The maximum color value can't exceed 255.")
Process.exit()
}
var wh = lines[1].split(" ")
var w = Num.fromString(wh[0])
var h = Num.fromString(wh[1])
_bmp = ImageData.create(fileName, w, h)
var bytes = ppm.bytes
var i = bytes.count - 3 * w * h
for (y in 0...h) {
for (x in 0...w) {
var r = bytes[i]
var g = bytes[i+1]
var b = bytes[i+2]
var c = Color.rgb(r, g, b)
pset(x, y, c)
i = i + 3
}
}
}
toGrayScale() {
_bmp2 = ImageData.create("gray scale", _bmp.width, _bmp.height)
for (x in 0..._bmp.width) {
for (y in 0..._bmp.height) {
var c1 = _bmp.pget(x, y)
var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor
var c2 = Color.rgb(lumin, lumin,lumin, c1.a)
_bmp2.pset(x, y, c2)
}
}
}
pset(x, y, col) { _bmp.pset(x, y, col) }
pget(x, y) { _bmp.pget(x, y) }
update() {}
draw(alpha) {}
}
var Game = Bitmap.new("output_piped.jpg", "output_piped.ppm", "output_piped_gs.jpg", 350, 350) |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Pascal | Pascal | Program CaesarCipher(output);
procedure encrypt(var message: string; key: integer);
var
i: integer;
begin
for i := 1 to length(message) do
case message[i] of
'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') + key) mod 26);
'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') + key) mod 26);
end;
end;
procedure decrypt(var message: string; key: integer);
var
i: integer;
begin
for i := 1 to length(message) do
case message[i] of
'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') - key + 26) mod 26);
'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') - key + 26) mod 26);
end;
end;
var
key: integer;
message: string;
begin
key := 3;
message := 'The five boxing wizards jump quickly';
writeln ('Original message: ', message);
encrypt(message, key);
writeln ('Encrypted message: ', message);
decrypt(message, key);
writeln ('Decrypted message: ', message);
readln;
end. |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Sidef | Sidef | var size = 4
var num = @(1..9).shuffle.first(size)
for (var guesses = 1; true; guesses++) {
var bulls = 0
var cows = 0
var input =
read("Input: ", String).chars \
.uniq \
.grep(/^[1-9]$/) \
.map{.to_n}
if (input.len != size) {
warn "Invalid input!\n"
guesses--
next
}
if (input == num) {
printf("You did it in %d attempts!\n", guesses)
break
}
for i (^num) {
if (num[i] == input[i]) {
bulls++
}
elsif (num.contains(input[i])) {
cows++
}
}
"Bulls: %d; Cows: %d\n".printf(bulls, cows)
} |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #zkl | zkl | p:=System.popen(0'|convert "fractalTree.jpg" ppm:-|,"r");
img:=PPM.readPPM(p); p.close(); |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Perl | Perl | 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";
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Smalltalk | Smalltalk | Object subclass: BullsCows [
|number|
BullsCows class >> new: secretNum [ |i|
i := self basicNew.
(self isValid: secretNum)
ifFalse: [ SystemExceptions.InvalidArgument
signalOn: secretNum
reason: 'You need 4 unique digits from 1 to 9' ].
i setNumber: secretNum.
^ i
]
BullsCows class >> new [ |b| b := Set new.
[ b size < 4 ]
whileTrue: [ b add: ((Random between: 1 and: 9) displayString first) ].
^ self new: (b asString)
]
BullsCows class >> isValid: num [
^ (num asSet size = 4) & ((num asSet includes: $0) not)
]
setNumber: num [ number := num ]
check: guess [ |bc| bc := Bag new.
1 to: 4 do: [ :i |
(number at: i) = (guess at: i)
ifTrue: [ bc add: 'bulls' ]
ifFalse: [
(number includes: (guess at: i))
ifTrue: [ bc add: 'cows' ]
]
].
^ bc
]
].
'Guess the 4-digits number (digits from 1 to 9, no repetition)' displayNl.
|guessMe d r tries|
[
tries := 0.
guessMe := BullsCows new.
[
[
'Write 4 digits: ' display.
d := stdin nextLine.
(BullsCows isValid: d)
] whileFalse: [
'Insert 4 digits, no repetition, exclude the digit 0' displayNl
].
r := guessMe check: d.
tries := tries + 1.
(r occurrencesOf: 'bulls') = 4
] whileFalse: [
('%1 cows, %2 bulls' % { r occurrencesOf: 'cows'. r occurrencesOf: 'bulls' })
displayNl.
].
('Good, you guessed it in %1 tries!' % { tries }) displayNl.
'Do you want to play again? [y/n]' display.
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ]. |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #11l | 11l | T Colour
Byte r, g, b
F (r, g, b)
.r = r
.g = g
.b = b
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)
T Bitmap
Int width, height
Colour background
[[Colour]] map
F (width = 40, height = 40, background = white)
assert(width > 0 & height > 0)
.width = width
.height = height
.background = background
.map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))
F fillrect(x, y, width, height, colour = black)
assert(x >= 0 & y >= 0 & width > 0 & height > 0)
L(h) 0 .< height
L(w) 0 .< width
.map[y + h][x + w] = colour
F set(x, y, colour = black)
.map[y][x] = colour
F get(x, y)
R .map[y][x]
F togreyscale()
L(h) 0 .< .height
L(w) 0 .< .width
V (r, g, b) = .get(w, h)
V l = Int(0.2126 * r + 0.7152 * g + 0.0722 * b)
.set(w, h, Colour(l, l, l))
F writeppmp3()
V magic = "P3\n"
V comment = "# generated from Bitmap.writeppmp3\n"
V s = magic‘’comment‘’("#. #.\n#.\n".format(.width, .height, 255))
L(h) (.height - 1 .< -1).step(-1)
L(w) 0 .< .width
V (r, g, b) = .get(w, h)
s ‘’= ‘ #3 #3 #3’.format(r, g, b)
s ‘’= "\n"
R s
F tokenize(fstr)
[String] tokens
L(line) fstr.split("\n")
I !line.starts_with(‘#’)
L(t) line.split(‘ ’, group_delimiters' 1B)
tokens.append(t)
R tokens
F ppmp3tobitmap(fstr)
V tokens = tokenize(fstr)
V tokeni = -1
F nexttoken()
@tokeni++
R @tokens[@tokeni]
assert(‘P3’ == nexttoken(), ‘Wrong filetype’)
V width = Int(nexttoken())
V height = Int(nexttoken())
V maxval = Int(nexttoken())
V bitmap = Bitmap(width, height, Colour(0, 0, 0))
L(h) (height - 1 .< -1).step(-1)
L(w) 0 .< width
V r = Int(nexttoken())
V g = Int(nexttoken())
V b = Int(nexttoken())
bitmap.set(w, h, Colour(r, g, b))
R bitmap
V ppmtxt = |‘P3
# feep.ppm
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
’
V bitmap = ppmp3tobitmap(ppmtxt)
print(‘Grey PPM:’)
bitmap.togreyscale()
print(bitmap.writeppmp3()) |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Phix | Phix | with javascript_semantics
sequence alpha_b = repeat(0,255)
alpha_b['A'..'Z'] = 'A'
alpha_b['a'..'z'] = 'a'
function caesar(string s, integer key)
integer ch, base
for i=1 to length(s) do
ch = s[i]
base = alpha_b[ch]
if base then
s[i] = base+remainder(ch-base+key,26)
end if
end for
return s
end function
string s = "One fine day in the middle of the night, two dead men got up to fight. \n"&
"Back to back they faced each other, drew their swords and shot each other. %^&*()[",
e = caesar(s,5),
r = caesar(e,26-5) ?e ?r
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Smart_BASIC | Smart BASIC |
'by rbytes, January 2017
OPTION BASE 1
P(" B U L L S A N D C O W S")!l
P("A secret 4-digit number has been created, with")
P("no repeats and no zeros. You must guess the number.")
P("After each guess, you will be shown how many of your")
P("digits are correct and in the matching location (bulls),")
P("and how many are correct but in a different location (cows).")
p("See how many tries it takes you to get the right answer.")
' generate a 4-digit number with no repeats
guesses = 0
1 WHILE LEN(sec$) <4
c$ =CHR$( INTEG(RND(1) *9) +49)
IF INSTR(sec$, c$)=-1 THEN sec$&=c$
ENDWHILE!l
2 PRINT "Your guess: "
INPUT "FOUR DIGITS": guess$!l
IF guess$="" THEN ' check if entry is null
P("Please enter something!")!l
GOTO 2
ENDIF
P(guess$)!l
IF LEN(guess$)<>4 THEN ' check if entry is exactly 4 characters
P("Please enter exactly 4 digits.")!l
GOTO 2
ENDIF
FOR t=1 TO 4 ' check if all characters are digits 1 - 9
IF INSTR("123456789",MID$(guess$,t,1))=-1 THEN
P("You have entered at least one illegal character")!l
GOTO 2
ENDIF
NEXT t
rep = check(guess$) ' check if any digits are repeated
IF check.chk THEN
P("Please enter a number with no repeated digits.")!l
GOTO 2
ENDIF
guesses+=1
r$=score$(guess$,sec$)
P(r$)!l
IF guess$=sec$ THEN
P("W I N N E R ! ! !")!l
IF guesses>1 THEN gs$="guesses!" ELSE gs$="guess!"
P("You won after "&guesses&" "&gs$)
P("Thanks for playing!")!l
PAUSE 2
P("A G A I N with a new secret number")!l
guesses=0
END IF
GOTO 1
END ' _____________________________________________________________
DEF P(p$) ' function to print a string
PRINT p$
END DEF
DEF L() ' function to print an empty line
PRINT
END DEF
DEF check(i$) ' check=0 if digit is not repeated, else=1
chk=0
FOR i =1 TO 3
FOR j =i +1 TO 4
IF MID$( i$, i, 1)=MID$( i$, j, 1) THEN chk =1
NEXT j
NEXT i
END DEF
DEF score$(a$,b$) ' calculate the numbers of bulls & cows.
bulls=0!cows=0
FOR i = 1 TO 4
c$ = MID$( a$, i, 1)
IF MID$( b$, i, 1)=c$ THEN
bulls+=1
ELSE
IF INSTR( b$, c$) <>-1 AND INSTR( b$, c$) <>i THEN
cows+=1
END IF
END IF
NEXT i
r$ ="Bulls: "&STR$( bulls)& ", "& "Cows: " &STR$( cows)
RETURN r$
END DEF
END
|
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Action.21 | Action! | INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image
PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
BYTE i
width^=ValB(s)
i=1
WHILE i<=s(0) AND s(i)#32
DO
s(i)=32
i==+1
OD
height^=ValB(s)
RETURN
PROC LoadHeader(RgbImage POINTER img
CHAR ARRAY format BYTE dev)
CHAR ARRAY line(255)
BYTE header,size,max,width,height
header=0 size=0 max=0
WHILE max=0
DO
InputSD(dev,line)
IF line(0)>0 AND line(1)#'# THEN
IF header=0 THEN
IF SCompare(format,format)#0 THEN
Break()
FI
header=1
ELSEIF size=0 THEN
DecodeSize(line,@width,@height)
IF width=0 OR height=0 THEN
Break()
FI
img.w=width img.h=height
size=1
ELSEIF max=0 THEN
max=ValB(line)
IF max#255 THEN
Break()
FI
FI
FI
OD
RETURN
PROC LoadPPM6(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y
RGB c
Close(dev)
Open(dev,path,4)
LoadHeader(img,"P6",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
c.r=GetD(dev)
c.g=GetD(dev)
c.b=GetD(dev)
SetRgbPixel(img,x,y,c)
OD
OD
Close(dev)
RETURN
PROC SaveHeader(GrayImage POINTER img
CHAR ARRAY format BYTE dev)
PrintDE(dev,format)
PrintBD(dev,img.w)
PutD(dev,32)
PrintBDE(dev,img.h)
PrintBDE(dev,255)
RETURN
PROC SavePPM2(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y,c
Close(dev)
Open(dev,path,8)
SaveHeader(img,"P2",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
c=GetGrayPixel(img,x,y)
PrintBD(dev,c)
IF x=img.w-1 THEN
PutDE(dev)
ELSE
PutD(dev,32)
FI
OD
OD
Close(dev)
RETURN
PROC Load(CHAR ARRAY path)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,path,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
PrintE(line)
OD
Close(dev)
RETURN
PROC Main()
BYTE ARRAY rgbdata(300),graydata(100)
RgbImage rgbimg
GrayImage grayimg
CHAR ARRAY path2="D:PPM2.PPM"
CHAR ARRAY path6="D:PPM6.PPM"
Put(125) PutE() ;clear the screen
InitRgbImage(rgbimg,0,0,rgbdata)
InitRgbToGray()
PrintF("Loading %S...%E%E",path6)
LoadPPM6(rgbimg,path6)
PrintF("Converting RGB to grayscale...%E%E")
InitGrayImage(grayimg,rgbimg.w,rgbimg.h,graydata)
RgbToGray(rgbimg,grayimg)
PrintF("Saving %S...%E%E",path2)
SavePPM2(grayimg,path2)
PrintF("Loading %S...%E%E",path2)
Load(path2)
RETURN |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Ada | Ada | with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
function Get_PPM (File : File_Type) return Image is
use Ada.Characters.Latin_1;
use Ada.Integer_Text_IO;
function Get_Line return String is -- Skips comments
Byte : Character;
Buffer : String (1..80);
begin
loop
for I in Buffer'Range loop
Character'Read (Stream (File), Byte);
if Byte = LF then
exit when Buffer (1) = '#';
return Buffer (1..I - 1);
end if;
Buffer (I) := Byte;
end loop;
if Buffer (1) /= '#' then
raise Data_Error;
end if;
end loop;
end Get_Line;
Height : Integer;
Width : Integer;
begin
if Get_Line /= "P6" then
raise Data_Error;
end if;
declare
Line : String := Get_Line;
Start : Integer := Line'First;
Last : Positive;
begin
Get (Line, Width, Last); Start := Start + Last;
Get (Line (Start..Line'Last), Height, Last); Start := Start + Last;
if Start <= Line'Last then
raise Data_Error;
end if;
if Width < 1 or else Height < 1 then
raise Data_Error;
end if;
end;
if Get_Line /= "255" then
raise Data_Error;
end if;
declare
Result : Image (1..Height, 1..Width);
Buffer : String (1..Width * 3);
Index : Positive;
begin
for I in Result'Range (1) loop
String'Read (Stream (File), Buffer);
Index := Buffer'First;
for J in Result'Range (2) loop
Result (I, J) :=
( R => Luminance (Character'Pos (Buffer (Index))),
G => Luminance (Character'Pos (Buffer (Index + 1))),
B => Luminance (Character'Pos (Buffer (Index + 2)))
);
Index := Index + 3;
end loop;
end loop;
return Result;
end;
end Get_PPM; |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PHP | PHP | <?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( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?> |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Swift | Swift | 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)
}
} |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #AutoHotkey | AutoHotkey | img := ppm_read("lena50.ppm") ;
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
msgbox % x.rgb() " " y.rgb()
img.write("lena50copy.ppm")
return
ppm_read(filename, ppmo=0) ; only ppm6 files supported
{
if !ppmo ; if image not already in memory, read from filename
fileread, ppmo, % filename
index := 1
pos := 1
loop, parse, ppmo, `n, `r
{
if (substr(A_LoopField, 1, 1) == "#")
continue
loop,
{
if !pos := regexmatch(ppmo, "\d+", pixel, pos)
break
bitmap%A_Index% := pixel
if (index == 4)
Break
pos := regexmatch(ppmo, "\s", x, pos)
index ++
}
}
type := bitmap1
width := bitmap2
height := bitmap3
maxcolor := bitmap4
bitmap := Bitmap(width, height, color(0,0,0))
index := 1
i := 1
j := 1
bits := pos
loop % width * height
{
bitmap[i, j, "r"] := numget(ppmo, 3 * A_Index + bits, "uchar")
bitmap[i, j, "g"] := numget(ppmo, 3 * A_Index + bits + 1, "uchar")
bitmap[i, j, "b"] := numget(ppmo, 3 * A_Index + bits + 2, "uchar")
if (j == width)
{
j := 1
i += 1
}
else
j++
}
return bitmap
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Picat | Picat | main =>
S = "All human beings are born free and equal in dignity and rights.",
println(S),
println(caesar(S,5)),
println(caesar(caesar(S,5),-5)),
nl.
caesar(String, N) = Cipher =>
Lower = [chr(I): I in 97..122],
Upper = [chr(I): I in 65..90],
M = create_map(Lower, Upper, N),
% If a char is not in a..zA..z then show it as it is.
Cipher := [M.get(C,C) : C in String].
create_map(Lower,Upper, N) = M =>
M = new_map(),
Len = Lower.length,
foreach(I in 1..Len)
II = (N+I) mod Len,
if II == 0 then II := Len end, % Adjust for 1 based
M.put(Upper[I],Upper[II]),
M.put(Lower[I],Lower[II])
end.
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Tcl | Tcl | proc main {} {
fconfigure stdout -buffering none
set length 4
puts "I have chosen a number from $length unique digits from 1 to 9 arranged in a random order.
You need to input a $length digit, unique digit number as a guess at what I have chosen
"
while true {
set word [generateWord $length]
set count 1
while {[set guess [getGuess $length]] ne $word} {
printScore $length $word $guess
incr count
}
puts "You guessed correctly in $count tries."
if {[yn "Play again?"] eq "n"} break
}
}
proc generateWord {length} {
set chars 123456789
for {set i 1} {$i <= $length} {incr i} {
set idx [expr {int(rand() * [string length $chars])}]
append word [string index $chars $idx]
set chars [string replace $chars $idx $idx]
}
return $word
# here's another way to generate word with no duplications
set word ""
while {[string length $word] < $length} {
set char [expr {int(1 + 9*rand())}]
if {[string first $char $word] == -1} {
append word $char
}
}
}
proc getGuess {length} {
puts -nonewline "Enter your guess: "
while true {
gets stdin guess
if {[string match [string repeat {[1-9]} $length] $guess]} {
return $guess
}
if {[string tolower [string trim $guess]] eq "quit"} {
puts Bye
exit
}
puts "The word must be $length digits between 1 and 9 inclusive. Try again."
}
}
proc printScore {length word guess} {
set bulls 0
set cows 0
for {set i 0} {$i < $length} {incr i} {
if {[string index $word $i] eq [string index $guess $i]} {
incr bulls
set word [string replace $word $i $i +]
}
}
puts " $bulls bulls"
for {set i 0} {$i < $length} {incr i} {
if {[set j [string first [string index $guess $i] $word]] != -1} {
incr cows
set word [string replace $word $j $j -]
}
}
puts " $cows cows"
}
proc yn {msg} {
while true {
puts -nonewline "$msg \[y/n] "
gets stdin ans
set char [string tolower [string index [string trim $ans] 0]]
if {$char eq "y" || $char eq "n"} {
return $char
}
}
}
main |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #11l | 11l | T Colour
Byte r, g, b
F (r, g, b)
.r = r
.g = g
.b = b
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)
T Bitmap
Int width, height
Colour background
[[Colour]] map
F (width = 40, height = 40, background = white)
assert(width > 0 & height > 0)
.width = width
.height = height
.background = background
.map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))
F fillrect(x, y, width, height, colour = black)
assert(x >= 0 & y >= 0 & width > 0 & height > 0)
L(h) 0 .< height
L(w) 0 .< width
.map[y + h][x + w] = colour
F set(x, y, colour = black)
.map[y][x] = colour
F get(x, y)
R .map[y][x]
F writeppmp3()
V magic = "P3\n"
V comment = "# generated from Bitmap.writeppmp3\n"
V s = magic‘’comment‘’("#. #.\n#.\n".format(.width, .height, 255))
L(h) (.height - 1 .< -1).step(-1)
L(w) 0 .< .width
V (r, g, b) = .get(w, h)
s ‘’= ‘ #3 #3 #3’.format(r, g, b)
s ‘’= "\n"
R s
F writeppmp6()
V magic = "P6\n"
V comment = "# generated from Bitmap.writeppmp6\n"
[Byte] b
b [+]= magic.encode()
b [+]= comment.encode()
b [+]= ("#. #.\n#.\n".format(.width, .height, 255)).encode()
L(h) (.height - 1 .< -1).step(-1)
L(w) 0 .< .width
V (r, g, bl) = .get(w, h)
b [+]= [r, g, bl]
R b
V bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
print(bitmap.writeppmp3())
File(‘tmp.ppm’, ‘w’).write_bytes(bitmap.writeppmp6()) |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #BBC_BASIC | BBC BASIC | f% = OPENIN("c:\lena.ppm")
IF f%=0 ERROR 100, "Failed to open input file"
IF GET$#f% <> "P6" ERROR 101, "File is not in P6 format"
REPEAT
in$ = GET$#f%
UNTIL LEFT$(in$,1) <> "#"
size$ = in$
max$ = GET$#f%
Width% = VAL(size$)
space% = INSTR(size$, " ")
Height% = VALMID$(size$, space%)
VDU 23,22,Width%;Height%;8,16,16,128
FOR y% = Height%-1 TO 0 STEP -1
FOR x% = 0 TO Width%-1
r% = BGET#f% : g% = BGET#f% : b% = BGET#f%
l% = INT(0.3*r% + 0.59*g% + 0.11*b% + 0.5)
PROCsetpixel(x%,y%,l%,l%,l%)
NEXT
NEXT y%
END
DEF PROCsetpixel(x%,y%,r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #C | C | image get_ppm(FILE *pf); |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PicoLisp | PicoLisp | (setq *Letters (apply circ (mapcar char (range 65 90))))
(de caesar (Str Key)
(pack
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(chop (uppc Str)) ) ) ) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Transd | Transd |
#lang transd
MainModule: {
contains-duplicates: (λ s String() -> Bool()
(with str String(s) (sort str)
(ret (neq (find-adjacent str) (end str))))
),
play: (λ
syms "0123456789"
len 4
thenum String()
guess String()
(shuffle syms)
(= thenum (substr syms 0 len))
(textout "Your guess: ")
(while (getline guess)
(if (eq guess "q") break)
(if (or (neq (size guess) len)
(neq (find-first-not-of guess syms) -1)
(contains-duplicates guess))
(lout guess " is not valid guess")
(textout "Your guess: ")
continue
)
(with bulls 0 cows 0 pl 0
(for i in Range(len) do
(= pl (find thenum (subn guess i)))
(if (eq pl i) (+= bulls 1)
elsif (neq pl -1) (+= cows 1))
)
(lout "bulls: " bulls ", cows: " cows)
(if (eq bulls len)
(lout "Congratulations! You have found out the number!")
(ret null)
else (textout "Your guess: "))
)
)
(lout "You quit the game.")
),
_start: (λ s String()
(lout "Welcome to \"Bulls and cows\"!")
(while true
(while true
(textout "Do you want to play? (yes|no) : ")
(textin s 3)
(if (not (size s))
(lout "Didn't receive an answer. Exiting.") (exit)
elsif (== (sub (tolower s) 0 1) "n") (lout "Bye!")(exit)
elsif (== (sub (tolower s) 0 1) "y") break
else (lout "(Hint: \"yes\" or \"no\".)"))
)
(play)
(lout "Another game?")
)
)
}
|
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Action.21 | Action! | INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap
PROC SaveHeader(RgbImage POINTER img
CHAR ARRAY format BYTE dev)
PrintDE(dev,format)
PrintBD(dev,img.w)
PutD(dev,32)
PrintBDE(dev,img.h)
PrintBDE(dev,255)
RETURN
PROC SavePPM3(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y
RGB c
Close(dev)
Open(dev,path,8)
SaveHeader(img,"P3",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
GetRgbPixel(img,x,y,c)
PrintBD(dev,c.r) PutD(dev,32)
PrintBD(dev,c.g) PutD(dev,32)
PrintBD(dev,c.b)
IF x=img.w-1 THEN
PutDE(dev)
ELSE
PutD(dev,32)
FI
OD
OD
Close(dev)
RETURN
PROC SavePPM6(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y
RGB c
Close(dev)
Open(dev,path,8)
SaveHeader(img,"P6",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
GetRgbPixel(img,x,y,c)
PutD(dev,c.r)
PutD(dev,c.g)
PutD(dev,c.b)
OD
OD
Close(dev)
RETURN
PROC Load(CHAR ARRAY path)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,path,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
PrintE(line)
OD
Close(dev)
RETURN
PROC Main()
BYTE ARRAY rgbdata=[
0 0 0 0 0 255 0 255 0
255 0 0 0 255 255 255 0 255
255 255 0 255 255 255 31 63 127
63 31 127 127 31 63 127 63 31]
BYTE width=[3],height=[4]
RgbImage img
CHAR ARRAY path3="D:PPM3.PPM"
CHAR ARRAY path6="D:PPM6.PPM"
Put(125) PutE() ;clear the screen
InitRgbImage(img,width,height,rgbdata)
PrintF("Saving %S...%E%E",path3)
SavePPM3(img,path3)
PrintF("Saving %S...%E%E",path6)
SavePPM6(img,path6)
PrintF("Loading %S...%E%E",path3)
Load(path3)
RETURN |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Ada | Ada | with Ada.Characters.Latin_1;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
procedure Put_PPM (File : File_Type; Picture : Image) is
use Ada.Characters.Latin_1;
Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1));
Buffer : String (1..Picture'Length (2) * 3);
Color : Pixel;
Index : Positive;
begin
String'Write (Stream (File), "P6" & LF);
String'Write (Stream (File), Size (2..Size'Last) & LF);
String'Write (Stream (File), "255" & LF);
for I in Picture'Range (1) loop
Index := Buffer'First;
for J in Picture'Range (2) loop
Color := Picture (I, J);
Buffer (Index) := Character'Val (Color.R);
Buffer (Index + 1) := Character'Val (Color.G);
Buffer (Index + 2) := Character'Val (Color.B);
Index := Index + 3;
end loop;
String'Write (Stream (File), Buffer);
end loop;
Character'Write (Stream (File), LF);
end Put_PPM; |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #C.23 | C# | using System.IO;
class PPMReader
{
public static Bitmap ReadBitmapFromPPM(string file)
{
var reader = new BinaryReader(new FileStream(file, FileMode.Open));
if (reader.ReadChar() != 'P' || reader.ReadChar() != '6')
return null;
reader.ReadChar(); //Eat newline
string widths = "", heights = "";
char temp;
while ((temp = reader.ReadChar()) != ' ')
widths += temp;
while ((temp = reader.ReadChar()) >= '0' && temp <= '9')
heights += temp;
if (reader.ReadChar() != '2' || reader.ReadChar() != '5' || reader.ReadChar() != '5')
return null;
reader.ReadChar(); //Eat the last newline
int width = int.Parse(widths),
height = int.Parse(heights);
Bitmap bitmap = new Bitmap(width, height);
//Read in the pixels
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
bitmap.SetPixel(x, y, new Bitmap.Color()
{
Red = reader.ReadByte(),
Green = reader.ReadByte(),
Blue = reader.ReadByte()
});
return bitmap;
}
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Pike | Pike | object c = Crypto.Substitution()->set_rot_key(2);
string msg = "The quick brown fox jumped over the lazy dogs";
string msg_s2 = c->encrypt(msg);
c->set_rot_key(11);
string msg_s11 = c->encrypt(msg);
string decoded = c->decrypt(msg_s11);
write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded); |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #TUSCRIPT | TUSCRIPT |
$$ MODE tuscript
SET nr1=RANDOM_NUMBERS (1,9,1)
LOOP
SET nr2=RANDOM_NUMBERS (1,9,1)
IF (nr2!=nr1) EXIT
ENDLOOP
LOOP
SET nr3=RANDOM_NUMBERS (1,9,1)
IF (nr3!=nr1,nr2) EXIT
ENDLOOP
LOOP
SET nr4=RANDOM_NUMBERS (1,9,1)
IF (nr4!=nr1,nr2,nr3) EXIT
ENDLOOP
SET nr=JOIN(nr1,"'",nr2,nr3,nr4), limit=10
LOOP r=1,limit
SET bulls=cows=0
ASK "round {r} insert a number":guessnr=""
SET length=LENGTH(guessnr), checknr=STRINGS (guessnr,":>/:")
LOOP n=nr,y=checknr
IF (length!=4) THEN
PRINT "4-letter digit required"
EXIT
ELSEIF (n==y) THEN
SET bulls=bulls+1
ELSEIF (nr.ct.":{y}:") THEN
SET cows=cows+1
ENDIF
ENDLOOP
PRINT "bulls=",bulls," cows=",cows
IF (bulls==4) THEN
PRINT "BINGO"
EXIT
ELSEIF (r==limit) THEN
PRINT "BETTER NEXT TIME"
EXIT
ENDIF
ENDLOOP
|
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Aime | Aime | integer i, h, j, w;
file f;
w = 640;
h = 320;
f.create("out.ppm", 00644);
f.form("P6\n~ ~\n255\n", w, h);
j = 0;
do {
srand(j >> 4);
i = 0;
do {
16.times(f_bytes, f, drand(255), drand(255), drand(255));
} while ((i += 16) < w);
} while ((j += 1) < h); |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Applesoft_BASIC | Applesoft BASIC | 100 W = 8
110 H = 8
120 BA = 24576
130 HIMEM: 8192
140 D$ = CHR$ (4)
150 M$ = CHR$ (13)
160 P6$ = "P6" + M$ + STR$ (W) + " " + STR$ (H) + M$ + "255" + M$
170 FOR I = 1 TO LEN (P6$)
180 POKE BA + I - 1, ASC ( MID$ (P6$,I,1))
190 NEXT I
200 BB = BA + I - 1
210 BL = (BB + W * H * 3) - BA
220 C = 255 + 255 * 256 + 0 * 65536: GOSUB 600FILL
230 X = 4:Y = 5:C = 127 + 127 * 256 + 255 * 65536: GOSUB 500"SET PIXEL"
240 PRINT D$"BSAVE BITMAP.PPM,A"BA",L"BL
250 END
500 R = C - INT (C / 256) * 256:B = INT (C / 65536):G = INT (C / 256) - B * 256:A = BB + X * 3 + Y * W * 3: POKE A,R: POKE A + 1,G: POKE A + 2,B: RETURN
600 FOR Y = 0 TO H - 1: FOR X = 0 TO W - 1: GOSUB 500: NEXT X,Y: RETURN |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Common_Lisp | Common Lisp |
(in-package #:rgb-pixel-buffer)
(defparameter *whitespaces-chars* '(#\SPACE #\RETURN #\TAB #\NEWLINE #\LINEFEED))
(defun read-header-chars (stream &optional (delimiter-list *whitespaces-chars*))
(do ((c (read-char stream nil :eof)
(read-char stream nil :eof))
(vals nil (if (or (null c) (char= c #\#)) vals (cons c vals)))) ;;don't collect comment chars
((or (eql c :eof) (member c delimiter-list)) (map 'string #'identity (nreverse vals))) ;;return strings
(when (char= c #\#) ;;skip comments
(read-line stream))))
(defun read-ppm-file-header (file)
(with-open-file (s file :direction :input)
(do ((failure-count 0 (1+ failure-count))
(tokens nil (let ((t1 (read-header-chars s)))
(if (> (length t1) 0)
(cons t1 tokens)
tokens))))
((>= (length tokens) 4) (values (nreverse tokens)
(file-position s)))
(when (>= failure-count 10)
(error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file)))
(when (= (length tokens) 1)
(when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3")))
(error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens))))))))
(defun read-ppm-image (file)
(flet ((image-data-reader (stream start-position width height image-build-function read-function)
(file-position stream start-position)
(dotimes (row height)
(dotimes (col width)
(funcall image-build-function row col (funcall read-function stream))))))
(multiple-value-bind (header file-pos) (read-ppm-file-header file)
(let* ((image-type (first header))
(width (parse-integer (second header) :junk-allowed t))
(height (parse-integer (third header) :junk-allowed t))
(max-value (parse-integer (fourth header) :junk-allowed t))
(image (make-rgb-pixel-buffer width height)))
(when (> max-value 255)
(error "unsupported depth - convert to 1byte depth with pamdepth"))
(cond ((string= "P6" image-type)
(with-open-file (stream file :direction :input :element-type '(unsigned-byte 8))
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read-byte stream)
(read-byte stream)
(read-byte stream))))
image))
((string= "P3" image-type)
(with-open-file (stream file :direction :input)
(image-data-reader stream
file-pos
width
height
#'(lambda (w h val)
(setf (rgb-pixel image w h) val))
#'(lambda (stream)
(make-rgb-pixel (read stream)
(read stream)
(read stream))))
image))
(t 'unsupported))
image))))
(export 'read-ppm-image)
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PL.2FI | PL/I | caesar: procedure options (main);
declare cypher_string character (52) static initial
((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
declare (text, encyphered_text) character (100) varying,
offset fixed binary;
get edit (text) (L); /* Read in one line of text */
get list (offset);
if offset < 1 | offset > 25 then signal error;
put skip list ('Plain text=', text);
encyphered_text = translate(text, substr(cypher_string, offset+1, 26),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' );
put skip list ('Encyphered text=', encyphered_text);
text = translate(encyphered_text, substr(cypher_string, 27-offset, 26),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' );
put skip list ('Decyphered text=', text);
end caesar; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #uBasic.2F4tH | uBasic/4tH | Local(2) ' Let's use no globals
Proc _Initialize ' Get our secret number
Do ' Repeat until it's guessed
Do
Input "Enter your guess: ";a@ ' Enter your guess
While FUNC(_Invalid(a@)) ' but make sure it's a valid guess
Loop
a@ = FUNC(_Bulls) ' Count the number of bulls
b@ = FUNC(_Cows) ' Count the number of cows
' Now give some feedback
Print : Print "\tThere were ";a@;" bulls and ";b@;" cows." : Print
Until a@ = 4 ' Until the secret is guessed
Loop
Print "You win!" ' Yes, you guessed it
End
_Initialize ' Make a secret
Local (1)
Do
a@ = 1234 + RND(8643) ' Get a valid number
While FUNC(_Invalid(a@)) ' and accept it unless invalid
Loop
For a@ = 0 to 3 ' Now save it at the proper place
@(a@+4) = @(a@)
Next
Return
_Invalid Param(1) ' Check whether a number is valid
Local(2)
' Ok, these can't be right at all
If (a@ < 1234) + (a@ > 9876) Then Return (1)
' Now break 'em up in different digits
For b@ = 3 To 0 Step -1
@(b@) = a@ % 10 ' A digit of zero can't be right
If @(b@) = 0 Then Unloop : Return (1)
a@ = a@ / 10
Next
For b@ = 0 To 2 ' Now compare all digits
For c@ = b@ + 1 To 3 ' The others were already compared
If @(b@) = @(c@) Then Unloop : Unloop : Return (1)
Next ' Wrong, we found similar digits
Next
Return (0) ' All digits are different
_Bulls ' Count the number of valid guesses
Local (2)
b@ = 0 ' Start with zero
For a@ = 0 to 3 ' Increment with each valid guess
If @(a@) = @(a@+4) Then b@ = b@ + 1
Next
Return (b@) ' Return number of valid guesses
_Cows
Local (3) ' Count the number of proper digits
c@ = 0 ' Start with zero
For a@ = 0 To 3 ' All the players guesses
For b@ = 4 To 7 ' All the computers secrets
If (a@+4) = b@ Then Continue ' Skip the bulls
If @(a@) = @(b@) Then c@ = c@ + 1
Next ' Increment with valid digits
Next
Return (c@) ' Return number of valid digits |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #AutoHotkey | AutoHotkey |
cyan := color(0,255,255) ; r,g,b
cyanppm := Bitmap(10, 10, cyan) ; width, height, background-color
Bitmap_write_ppm3(cyanppm, "cyan.ppm")
run, cyan.ppm
return
#include bitmap_storage.ahk ; see basic bitmap storage task
Bitmap_write_ppm3(bitmap, filename)
{
file := FileOpen(filename, 0x11) ; utf-8, write
file.seek(0,0) ; overwrite BOM created with fileopen()
file.write("P3`n" ; `n = \n in ahk
. bitmap.width . " " . bitmap.height . "`n"
. "255`n")
loop % bitmap.height
{
height := A_Index
loop % bitmap.width
{
width := A_Index
color := bitmap[height, width]
file.Write(color.R . " ")
file.Write(color.G . " ")
file.Write(color.B . " ")
}
file.write("`n")
}
file.close()
return 0
}
|
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #D | D |
program BtmAndPpm;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Graphics;
type
TBitmapHelper = class helper for TBitmap
private
public
procedure SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);
procedure LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);
end;
function ColorToGray(Color: TColor): TColor;
var
L: Byte;
begin
L := round(0.2126 * GetRValue(Color) + 0.7152 * GetGValue(Color) + 0.0722 *
GetBValue(Color));
Result := RGB(L, L, L);
end;
{ TBitmapHelper }
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
if useGrayScale then
color := ColorToGray(ColorToRGB(Self.Canvas.Pixels[i, j]))
else
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
procedure TBitmapHelper.LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);
var
p: Integer;
ppm: TMemoryStream;
sW, sH: string;
temp: AnsiChar;
W, H: Integer;
Color: TColor;
function ReadChar: AnsiChar;
begin
ppm.Read(Result, 1);
end;
begin
ppm := TMemoryStream.Create;
ppm.LoadFromFile(FileName);
if ReadChar + ReadChar <> 'P6' then
exit;
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sW := sW + temp;
until temp = ' ';
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sH := sH + temp;
until temp = #10;
W := StrToInt(sW);
H := StrToInt(sH);
if ReadChar + ReadChar + ReadChar <> '255' then
exit;
ReadChar(); //skip newLine
SetSize(W, H);
p := 0;
while ppm.Read(Color, 3) > 0 do
begin
if useGrayScale then
Color := ColorToGray(Color);
Canvas.Pixels[p mod W, p div W] := Color;
inc(p);
end;
ppm.Free;
end;
begin
with TBitmap.Create do
begin
// Load bmp
LoadFromFile('Input.bmp');
// Save as ppm
SaveAsPPM('Output.ppm');
// Load as ppm and convert in grayscale
LoadFromPPM('Output.ppm', True);
// Save as bmp
SaveToFile('Output.bmp');
Free;
end;
end.
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PowerShell | PowerShell | # Author: M. McNabb
function Get-CaesarCipher
{
Param
(
[Parameter(
Mandatory=$true,ValueFromPipeline=$true)]
[string]
$Text,
[ValidateRange(1,25)]
[int]
$Key = 1,
[switch]
$Decode
)
begin
{
$LowerAlpha = [char]'a'..[char]'z'
$UpperAlpha = [char]'A'..[char]'Z'
}
process
{
$Chars = $Text.ToCharArray()
function encode
{
param
(
$Char,
$Alpha = [char]'a'..[char]'z'
)
$Index = $Alpha.IndexOf([int]$Char)
$NewIndex = ($Index + $Key) - $Alpha.Length
$Alpha[$NewIndex]
}
function decode
{
param
(
$Char,
$Alpha = [char]'a'..[char]'z'
)
$Index = $Alpha.IndexOf([int]$Char)
$int = $Index - $Key
if ($int -lt 0) {$NewIndex = $int + $Alpha.Length}
else {$NewIndex = $int}
$Alpha[$NewIndex]
}
foreach ($Char in $Chars)
{
if ([int]$Char -in $LowerAlpha)
{
if ($Decode) {$Char = decode $Char}
else {$Char = encode $Char}
}
elseif ([int]$Char -in $UpperAlpha)
{
if ($Decode) {$Char = decode $Char $UpperAlpha}
else {$Char = encode $Char $UpperAlpha}
}
$Char = [char]$Char
[string]$OutText += $Char
}
$OutText
$OutText = $null
}
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #UNIX_Shell | UNIX Shell | #!/bin/bash
rand() {
local min=${1:-0}
local max=${2:-32767}
[ ${min} -gt ${max} ] &&
min=$(( min ^ max )) &&
max=$(( min ^ max )) &&
min=$(( min ^ max ))
echo -n $(( ( $RANDOM % $max ) + $min ))
}
in_arr() {
local quandry="${1}"
shift
local arr=( $@ )
local i=''
for i in ${arr[*]}
do
[ "${quandry}" == "${i}" ] && return 0 && break
done
return 1
}
delete_at() {
local idx="$(( $1 + 1 ))"
shift
local arr=( "sentinel" $@ )
echo -n "${arr[@]:1:$(( idx - 1 ))} ${arr[@]:$((idx + 1)):$(( ${#arr[@]} - idx - 1))}"
}
delete_first() {
local meanie="${1}"
shift
local arr=( $@ )
local i=0
for (( i = 0; i < ${#arr[@]} ; i++ ))
do
[ "${arr[${i}]}" == "${meanie}" ] && arr=( $( delete_at ${i} ${arr[*]} ) )
done
echo -n "${arr[*]}"
}
to_arr() {
local string="${1}"
local arr=()
while [ "${#string}" -gt 0 ]
do
arr=( ${arr[*]} ${string:0:1} )
string="${string:1}"
done
echo -n "${arr[*]}"
}
choose_idx() {
local arr=( $@ )
echo -n "$( rand 0 $(( ${#arr[@]} - 1 )) )"
}
locate_bulls() {
local secret=( $( to_arr "${1}" ) )
local guess=( $( to_arr "${2}" ) )
local hits=()
local i=0
for (( i=0; i<4; i++ ))
do
[ "${secret[${i}]}" -eq "${guess[${i}]}" ] && hits=( ${hits[*]} ${i} )
done
echo -n "${hits[*]}"
}
bulls() {
local secret="${1}"
local guess="${2}"
local bulls=( $( locate_bulls "${secret}" "${guess}" ) )
echo -n "${#bulls[@]}"
}
cows() {
local secret=( $( to_arr "${1}" ) )
local guess=( $( to_arr "${2}" ) )
local bulls=( $( locate_bulls "${1}" "${2}" ) )
local hits=0
local i=''
# Avoid double-counting bulls
for i in ${bulls[*]}
do
secret=( $( delete_at ${i} ${secret[*]} ) )
done
# Process the guess against what's left of the secret
for i in ${guess[*]}
do
in_arr "${i}" ${secret[*]} &&
secret=( $( delete_first "${i}" ${secret[*]} ) ) &&
(( hits++ ))
done
echo -n ${hits}
}
malformed() {
local guess=( $( to_arr "${1}" ) )
local i=''
[ ${#guess[@]} -ne 4 ] &&
return 0
for i in ${guess[*]}
do
if ! in_arr ${i} 1 2 3 4 5 6 7 8 9
then
return 0
break
fi
done
return 1
}
candidates=( 1 2 3 4 5 6 7 8 9 )
secret=''
while [ "${#secret}" -lt 4 ]
do
cidx=$( choose_idx ${candidates[*]} )
secret="${secret}${candidates[${cidx}]}"
candidates=( $(delete_at ${cidx} ${candidates[*]} ) )
done
while read -p "Enter a four-digit guess: " guess
do
malformed "${guess}" && echo "Malformed guess" && continue
[ "${guess}" == "${secret}" ] && echo "You win!" && exit
echo "Score: $( bulls "${secret}" "${guess}" ) Bulls, $( cows "${secret}" "${guess}" ) Cows"
done |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
split("255,0,0,255,255,0",R,",");
split("0,255,0,255,255,0",G,",");
split("0,0,255,0,0,0",B,",");
outfile = "P3.ppm";
printf("P3\n2 3\n255\n") >outfile;
for (k=1; k<=length(R); k++) {
printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile
}
close(outfile);
} |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #BBC_BASIC | BBC BASIC | Width% = 200
Height% = 200
VDU 23,22,Width%;Height%;8,16,16,128
*display c:\lena
f% = OPENOUT("c:\lena.ppm")
IF f%=0 ERROR 100, "Failed to open output file"
BPUT #f%, "P6"
BPUT #f%, "# Created using BBC BASIC"
BPUT #f%, STR$(Width%) + " " +STR$(Height%)
BPUT #f%, "255"
FOR y% = Height%-1 TO 0 STEP -1
FOR x% = 0 TO Width%-1
rgb% = FNgetpixel(x%,y%)
BPUT #f%, rgb% >> 16
BPUT #f%, (rgb% >> 8) AND &FF
BPUT #f%, rgb% AND &FF
NEXT
NEXT y%
CLOSE#f%
END
DEF FNgetpixel(x%,y%)
LOCAL col%
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col% |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Delphi | Delphi |
program BtmAndPpm;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Graphics;
type
TBitmapHelper = class helper for TBitmap
private
public
procedure SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);
procedure LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);
end;
function ColorToGray(Color: TColor): TColor;
var
L: Byte;
begin
L := round(0.2126 * GetRValue(Color) + 0.7152 * GetGValue(Color) + 0.0722 *
GetBValue(Color));
Result := RGB(L, L, L);
end;
{ TBitmapHelper }
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
if useGrayScale then
color := ColorToGray(ColorToRGB(Self.Canvas.Pixels[i, j]))
else
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
procedure TBitmapHelper.LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);
var
p: Integer;
ppm: TMemoryStream;
sW, sH: string;
temp: AnsiChar;
W, H: Integer;
Color: TColor;
function ReadChar: AnsiChar;
begin
ppm.Read(Result, 1);
end;
begin
ppm := TMemoryStream.Create;
ppm.LoadFromFile(FileName);
if ReadChar + ReadChar <> 'P6' then
exit;
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sW := sW + temp;
until temp = ' ';
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sH := sH + temp;
until temp = #10;
W := StrToInt(sW);
H := StrToInt(sH);
if ReadChar + ReadChar + ReadChar <> '255' then
exit;
ReadChar(); //skip newLine
SetSize(W, H);
p := 0;
while ppm.Read(Color, 3) > 0 do
begin
if useGrayScale then
Color := ColorToGray(Color);
Canvas.Pixels[p mod W, p div W] := Color;
inc(p);
end;
ppm.Free;
end;
begin
with TBitmap.Create do
begin
// Load bmp
LoadFromFile('Input.bmp');
// Save as ppm
SaveAsPPM('Output.ppm');
// Load as ppm and convert in grayscale
LoadFromPPM('Output.ppm', True);
// Save as bmp
SaveToFile('Output.bmp');
Free;
end;
end.
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Prolog | Prolog | :- use_module(library(clpfd)).
caesar :-
L1 = "The five boxing wizards jump quickly",
writef("Original : %s\n", [L1]),
% encryption of the sentence
encoding(3, L1, L2) ,
writef("Encoding : %s\n", [L2]),
% deciphering on the encoded sentence
encoding(3, L3, L2),
writef("Decoding : %s\n", [L3]).
% encoding/decoding of a sentence
encoding(Key, L1, L2) :-
maplist(caesar_cipher(Key), L1, L2).
caesar_cipher(_, 32, 32) :- !.
caesar_cipher(Key, V1, V2) :-
V #= Key + V1,
% we verify that we are in the limits of A-Z and a-z.
((V1 #=< 0'Z #/\ V #> 0'Z) #\/ (V1 #=< 0'z #/\ V #> 0'z)
#\/
(V1 #< 0'A #/\ V2 #>= 0'A)#\/ (V1 #< 0'a #/\ V2 #>= 0'a)) #==> A,
% if we are not in these limits A is 1, otherwise 0.
V2 #= V - A * 26,
% compute values of V1 and V2
label([A, V1, V2]). |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #11l | 11l | T BitWriter
File out
accumulator = 0
bcount = 0
F (fname)
.out = File(fname, ‘w’)
F _writebit(bit)
I .bcount == 8
.flush()
I bit > 0
.accumulator [|]= 1 << (7 - .bcount)
.bcount++
F writebits(bits, =n)
L n > 0
._writebit(bits [&] 1 << (n - 1))
n--
F flush()
.out.write_bytes([Byte(.accumulator)])
.accumulator = 0
.bcount = 0
F close()
.flush()
.out.close()
T BitReader
File input
accumulator = 0
bcount = 0
read = 0
F (fname)
.input = File(fname, ‘r’)
F _readbit()
I .bcount == 0
V a = .input.read_bytes(1)
I !a.empty
.accumulator = a[0]
.bcount = 8
.read = a.len
V rv = (.accumulator [&] (1 << (.bcount - 1))) >> (.bcount - 1)
.bcount--
R rv
F readbits(=n)
V v = 0
L n > 0
v = (v << 1) [|] ._readbit()
n--
R v
V writer = BitWriter(‘bitio_test.dat’)
V chars = ‘12345abcde’
L(ch) chars
writer.writebits(ch.code, 7)
writer.close()
V reader = BitReader(‘bitio_test.dat’)
[Char] charsa
L
V x = reader.readbits(7)
I reader.read == 0
L.break
charsa.append(Char(code' x))
print(charsa.join(‘’)) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #VBA | VBA |
Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25 'the max of lines supported by MsgBox
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
|
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #C | C | #include <stdlib.h>
#include <stdio.h>
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen("first.ppm", "wb"); /* b - binary mode */
(void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256; /* red */
color[1] = j % 256; /* green */
color[2] = (i * j) % 256; /* blue */
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #E | E | def chr := <import:java.lang.makeCharacter>.asChar
def readPPM(inputStream) {
# Proper native-to-E stream IO facilities have not been designed and
# implemented yet, so we are borrowing Java's. Poorly. This *will* be
# improved eventually.
# Reads one header token, skipping comments and whitespace, and exactly
# one trailing whitespace character
def readToken() {
var token := ""
var c := chr(inputStream.read())
while (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '#') {
if (c == '#') {
while (c != '\n') { c := chr(inputStream.read()) }
}
# skip over initial whitespace
c := chr(inputStream.read())
}
while (!(c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
if (c == '#') {
while (c != '\n') { c := chr(inputStream.read()) }
} else {
token += E.toString(c)
c := chr(inputStream.read())
}
}
return token
}
# Header
require(readToken() == "P6")
def width := __makeInt(readToken())
def height := __makeInt(readToken())
def maxval := __makeInt(readToken())
def size := width * height * 3
# Body
# See [[Basic bitmap storage]] for the definition and origin of sign()
def data := <elib:tables.makeFlexList>.fromType(<type:java.lang.Byte>, size)
if (maxval >= 256) {
for _ in 1..size {
data.push(sign((inputStream.read() * 256 + inputStream.read()) * 255 // maxval))
}
} else {
for _ in 1..size {
data.push(sign(inputStream.read() * 255 // maxval))
}
}
def image := makeImage(width, height)
image.replace(data.snapshot())
return image
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #PureBasic | PureBasic | Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
Static alphabet$ = "ABCEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
Protected result.s, i, length = Len(plainText), letter.s, legal
If key < 1 Or key > 25: ProcedureReturn: EndIf ;keep key in range
For i = 1 To length
letter = Mid(plainText, i, 1)
legal = FindString(alphabet$, letter, 1 + reverse)
If legal
result + Mid(alphabet$, legal + key, 1)
Else
result + letter
EndIf
Next
ProcedureReturn result
EndProcedure
Procedure.s CC_decrypt(cypherText.s, key)
ProcedureReturn CC_encrypt(cypherText, key, 1)
EndProcedure
If OpenConsole()
Define key, plainText.s, encryptedText.s, decryptedText.s
key = Random(24) + 1 ;get a random key in the range 1 -> 25
plainText = "The quick brown fox jumped over the lazy dogs.": PrintN(RSet("Plain text = ", 17) + #DQUOTE$ + plainText + #DQUOTE$)
encryptedText = CC_encrypt(plainText, key): PrintN(RSet("Encrypted text = ", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)
decryptedText = CC_decrypt(encryptedText, key): PrintN(RSet("Decrypted text = ", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #6502_Assembly | 6502 Assembly |
define StringRam $1200 ;not actually used in the code, but it's here for clarity.
define z_BC $00 ;fake Z80-style register for pseudo-16-bit operations.
define z_C $00 ;6502 uses the low byte as the reference point for indirect lookups.
define z_B $01 ;high byte
define tempMath $02 ;temp storage of input
define tempBitMask $03 ;temp storage of the bit filter
lda #$12
sta z_B
lda #$00
sta z_C ;load address $1200 into zero page memory for an indirect lookup.
lda #$0F ;test value
LDY #0 ;initialize offset to zero
jsr Hex2BinAscii
brk ;on easy6502 this terminates the program.
Hex2BinAscii:
sta tempMath ;store our input, in this case #$0F
lda #%10000000
sta tempBitMask
loop_Hex2BinAscii:
lda tempMath ;load input into accumulator.
and tempBitMask ;filter out all bits except the one we are checking this pass of the loop
bne bitIsOne
lda #$30 ;ascii for zero
bne StoreBit
bitIsOne:
lda #$31 ;ascii for one
StoreBit:
sta (z_BC),y ;store in StringRam+Y
loopOverhead:
iny ;y++
lsr tempBitMask ;shift to next bit in sequence
beq loop_Hex2BinAscii ;if mask is zero, we are done. BCC would have worked here as well.
lda #$00 ;load the null terminator
sta (z_BC),y ;store the null terminator after the string
rts |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #Ada | Ada | with Ada.Streams; use Ada.Streams;
with Ada.Finalization;
package Bit_Streams is
type Bit is range 0..1;
type Bit_Array is array (Positive range <>) of Bit;
type Bit_Stream (Channel : not null access Root_Stream_Type'Class) is limited private;
procedure Read (Stream : in out Bit_Stream; Data : out Bit_Array);
procedure Write (Stream : in out Bit_Stream; Data : Bit_Array);
private
type Bit_Stream (Channel : not null access Root_Stream_Type'Class) is
new Ada.Finalization.Limited_Controlled with
record
Read_Count : Natural := 0;
Write_Count : Natural := 0;
Input : Stream_Element_Array (1..1);
Output : Stream_Element_Array (1..1);
end record;
overriding procedure Finalize (Stream : in out Bit_Stream);
end Bit_Streams; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #VBScript | VBScript |
randomize timer
fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same")
p=dopuzzle()
wscript.echo "Bulls and Cows. Guess my 4 figure number!"
do
do
wscript.stdout.write vbcrlf & "your move ": s=trim(wscript.stdin.readline)
c=checkinput(s)
if not isarray (c) then wscript.stdout.write fail(c) :exit do
bu=c(0)
wscript.stdout.write "bulls: " & c(0) & " | cows: " & c(1)
loop while 0
loop until bu=4
wscript.stdout.write vbcrlf & "You won! "
function dopuzzle()
dim b(10)
for i=1 to 4
do
r=fix(rnd*10)
loop until b(r)=0
b(r)=1:dopuzzle=dopuzzle+chr(r+48)
next
end function
function checkinput(s)
dim c(10)
bu=0:co=0
if len(s)<>4 then checkinput=0:exit function
for i=1 to 4
b=mid(s,i,1)
if instr("0123456789",b)=0 then checkinput=1 :exit function
if c(asc(b)-48)<>0 then checkinput=2 :exit function
c(asc(b)-48)=1
for j=1 to 4
if asc(b)=asc(mid(p,j,1)) then
if i=j then bu=bu+1 else co=co+1
end if
next
next
checkinput=array(bu,co)
end function
|
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #C.23 | C# | using System;
using System.IO;
class PPMWriter
{
public static void WriteBitmapToPPM(string file, Bitmap bitmap)
{
//Use a streamwriter to write the text part of the encoding
var writer = new StreamWriter(file);
writer.WriteLine("P6");
writer.WriteLine($"{bitmap.Width} {bitmap.Height}");
writer.WriteLine("255");
writer.Close();
//Switch to a binary writer to write the data
var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
for (int x = 0; x < bitmap.Height; x++)
for (int y = 0; y < bitmap.Width; y++)
{
Color color = bitmap.GetPixel(y, x);
writerB.Write(color.R);
writerB.Write(color.G);
writerB.Write(color.B);
}
writerB.Close();
}
} |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Erlang | Erlang |
% This module provides basic operations on ppm files:
% Read from file, create ppm in memory (from generic bitmap) and save to file.
% Writing PPM files was introduced in roseta code task 'Bitmap/Write a PPM file'
% but the same code is included here to provide whole set of operations on ppm
% needed for purposes of this task.
-module(ppm).
-export([ppm/1, write/2, read/1]).
% constants for writing ppm file
-define(WHITESPACE, <<10>>).
-define(SPACE, <<32>>).
% constants for reading ppm file
-define(WHITESPACES, [9, 10, 13, 32]).
-define(PPM_HEADER, "P6").
% data structure introduced in task Bitmap (module ros_bitmap.erl)
-record(bitmap, {
mode = rgb,
pixels = nil,
shape = {0, 0}
}).
%%%%%%%%% API %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read ppm file from file
read(Filename) ->
{ok, File} = file:read_file(Filename),
parse(File).
% create ppm image from bitmap record
ppm(Bitmap) ->
{Width, Height} = Bitmap#bitmap.shape,
Pixels = ppm_pixels(Bitmap),
Maxval = 255, % original ppm format maximum
list_to_binary([
header(), width_and_height(Width, Height), maxval(Maxval), Pixels]).
% write bitmap as ppm file
write(Bitmap, Filename) ->
Ppm = ppm(Bitmap),
{ok, File} = file:open(Filename, [binary, write]),
file:write(File, Ppm),
file:close(File).
%%%%%%%%% Reading PPM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
parse(Binary) ->
{?PPM_HEADER, Data} = get_next_token(Binary),
{Width, HeightAndRest} = get_next_token(Data),
{Height, MaxValAndRest} = get_next_token(HeightAndRest),
{_MaxVal, RawPixels} = get_next_token(MaxValAndRest),
Shape = {list_to_integer(Width), list_to_integer(Height)},
Pixels = load_pixels(RawPixels),
#bitmap{pixels=Pixels, shape=Shape}.
% load binary as a list of RGB triplets
load_pixels(Binary) when is_binary(Binary)->
load_pixels([], Binary).
load_pixels(Acc, <<>>) ->
array:from_list(lists:reverse(Acc));
load_pixels(Acc, <<R, G, B, Rest/binary>>) ->
load_pixels([<<R,G,B>>|Acc], Rest).
is_whitespace(Byte) ->
lists:member(Byte, ?WHITESPACES).
% get next part of PPM file, skip whitespaces, and return the rest of a binary
get_next_token(Binary) ->
get_next_token("", true, Binary).
get_next_token(CurrentToken, false, <<Byte, Rest/binary>>) ->
case is_whitespace(Byte) of
true ->
{lists:reverse(CurrentToken), Rest};
false ->
get_next_token([Byte | CurrentToken], false, Rest)
end;
get_next_token(CurrentToken, true, <<Byte, Rest/binary>>) ->
case is_whitespace(Byte) of
true ->
get_next_token(CurrentToken, true, Rest);
false ->
get_next_token([Byte | CurrentToken], false, Rest)
end.
%%%%%%%%% Writing PPM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
header() ->
[<<"P6">>, ?WHITESPACE].
width_and_height(Width, Height) ->
[encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE].
maxval(Maxval) ->
[encode_decimal(Maxval), ?WHITESPACE].
ppm_pixels(Bitmap) ->
% 24 bit color depth
array:to_list(Bitmap#bitmap.pixels).
encode_decimal(Number) ->
integer_to_list(Number).
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Python | Python | 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 = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True) |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #ALGOL_68 | ALGOL 68 | # NIBBLEs are of any width, eg 1-bit OR 4-bits etc. #
MODE NIBBLE = STRUCT(INT width, BITS bits);
PRIO << = 8, >> = 8; # define C style shift opertors #
OP << = (BITS bits, INT shift)BITS: bits SHL shift;
OP >> = (BITS bits, INT shift)BITS: bits SHR shift;
# define nibble opertors for left/right shift and append #
OP << = (NIBBLE nibble, INT shift)NIBBLE:
(width OF nibble + shift, bits OF nibble << shift);
OP >> = (NIBBLE nibble, INT shift)NIBBLE:
(width OF nibble - shift, bits OF nibble >> shift);
OP +:= = (REF NIBBLE lhs, NIBBLE rhs)REF NIBBLE: (
BITS rhs mask := BIN(ABS(2r1 << width OF rhs)-1);
lhs := ( width OF lhs + width OF rhs, bits OF lhs << width OF rhs OR bits OF rhs AND rhs mask)
);
# define MODEs for generating NIBBLE streams and yielding NIBBLEs #
MODE YIELDNIBBLE = PROC(NIBBLE)VOID;
MODE GENNIBBLE = PROC(YIELDNIBBLE)VOID;
PROC gen resize nibble = (
INT out width,
GENNIBBLE gen nibble,
YIELDNIBBLE yield
)VOID:(
NIBBLE buf := (0, 2r0), out;
BITS out mask := BIN(ABS(2r1 << out width)-1);
# FOR NIBBLE nibble IN # gen nibble( # ) DO #
## (NIBBLE in nibble)VOID:(
buf +:= in nibble;
WHILE width OF buf >= out width DO
out := buf >> ( width OF buf - out width);
width OF buf -:= out width; # trim 'out' from buf #
yield((out width, bits OF out AND out mask))
OD
# OD # ))
);
# Routines for joining strings and generating a stream of nibbles #
PROC gen nibble from 7bit chars = (STRING string, YIELDNIBBLE yield)VOID:
FOR key FROM LWB string TO UPB string DO yield((7, BIN ABS string[key])) OD;
PROC gen nibble from 8bit chars = (STRING string, YIELDNIBBLE yield)VOID:
FOR key FROM LWB string TO UPB string DO yield((8,BIN ABS string[key])) OD;
PROC gen join = ([]STRING strings, STRING new line, YIELDNIBBLE yield)VOID:
FOR key FROM LWB strings TO UPB strings DO
gen nibble from 8bit chars(strings[key]+new line, yield)
OD;
# Two tables for uuencoding 6bits in printable ASCII chacters #
[0:63]CHAR encode uue 6bit:= # [0:63] => CHAR64 #
"`!""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_"[@0];
[0:255]BITS decode uue 6bit; # CHAR64 => [0:63] #
FOR key FROM LWB encode uue 6bit TO UPB encode uue 6bit DO
decode uue 6bit[ABS encode uue 6bit[key]] := BIN key
OD;
decode uue 6bit[ABS " "] := 2r0; # extra #
# Some basic examples #
PROC example uudecode nibble stream = VOID:(
[]STRING encoded uue 6bit hello world = (
":&5L;&\L('=O<FQD""DAE;&QO+""!W;W)L9""$*1V]O9&)Y92P@8W)U96P@=V]R",
";&0*22=M(&QE879I;F<@>6]U('1O9&%Y""D=O;V1B>64L(&=O;V1B>64L(&=O",
";V1B>64@""@``"
);
PROC gen join hello world = (YIELDNIBBLE yield)VOID:
# FOR NIBBLE nibble IN # gen join(encoded uue 6bit hello world, "", # ) DO #
## (NIBBLE nibble)VOID:(
yield((6, decode uue 6bit[ABS bits OF nibble]))
# OD # ));
print(("Decode uue 6bit NIBBLEs into 8bit CHARs:", new line));
# FOR NIBBLE nibble IN # gen resize nibble(8, gen join hello world, # ) DO ( #
## (NIBBLE nibble)VOID:(
print(REPR ABS bits OF nibble)
# OD # ))
);
PROC example uuencode nibble stream = VOID: (
[]STRING hello world = (
"hello, world",
"Hello, world!",
"Goodbye, cruel world",
"I'm leaving you today",
"Goodbye, goodbye, goodbye "
);
PROC gen join hello world = (YIELDNIBBLE yield)VOID:
gen join(hello world, REPR ABS 8r12, yield); # 8r12 = ASCII new line #
print((new line, "Encode 8bit CHARs into uue 6bit NIBBLEs:", new line));
INT count := 0;
# FOR NIBBLE nibble IN # gen resize nibble(6, gen join hello world, # ) DO ( #
## (NIBBLE nibble)VOID:(
print(encode uue 6bit[ABS bits OF nibble]);
count+:=1;
IF count MOD 60 = 0 THEN print(newline) FI
# OD # ));
print(new line); print(new line)
);
PROC example compress 7bit chars = VOID: (
STRING example 7bit string = "STRING & ABACUS";
print(("Convert 7bit ASCII CHARS to a 1bit stream: ",new line,
example 7bit string + " => "));
PROC gen example 7bit string = (YIELDNIBBLE yield)VOID:
gen nibble from 7bit chars(example 7bit string,yield);
# FOR NIBBLE nibble IN # gen resize nibble(1, gen example 7bit string, # ) DO ( #
## (NIBBLE nibble)VOID: (
print(whole(ABS bits OF nibble,0))
# OD # ));
print(new line)
);
example uudecode nibble stream;
example uuencode nibble stream;
example compress 7bit chars |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Vedit_macro_language | Vedit macro language | Buf_Switch(Buf_Free)
#90 = Time_Tick // seed for random number generator
#91 = 10 // random numbers in range 0 to 9
while (EOB_pos < 4) { // 4 digits needed
Call("RANDOM")
BOF Ins_Char(Return_Value + '0')
Replace("(.)(.*)\1", "\1\2", REGEXP+BEGIN+NOERR) // remove any duplicate
}
#3 = 0
repeat (99) {
Get_Input(10, "Guess a 4-digit number with no duplicate digits: ", NOCR)
if (Reg_Size(10) == 0) { Break } // empty string = exit
Num_Eval_Reg(10) // check for numeric digits
if (Chars_Matched != 4) {
M("You should enter 4 numeric digits\n")
Continue
}
Goto_Pos(4) // count bulls
Reg_Ins(10, OVERWRITE)
#1 = Search("(.)...\1", REGEXP+BEGIN+ALL+NOERR)
RS(10, "[", INSERT) // count cows
RS(10, "]", APPEND)
#2 = Search_Block(@10, 0, 4, REGEXP+BEGIN+ALL+NOERR) - #1
#3++
NT(#1, NOCR) M(" bulls,") NT(#2, NOCR) M(" cows\n")
if (#1 == 4) {
M("You won after") NT(#3, NOCR) M(" guesses!\n")
Break
}
}
Buf_Quit(OK)
Return
//--------------------------------------------------------------
// Generate random numbers in range 0 <= Return_Value < #91
// #90 = Seed (0 to 0x7fffffff)
// #91 = Scaling (0 to 0x10000)
:RANDOM:
#92 = 0x7fffffff / 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000) |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #C.2B.2B | C++ | #include <fstream>
#include <cstdio>
int main() {
constexpr auto dimx = 800u, dimy = 800u;
using namespace std;
ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl;
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); // red, green, blue
ofs.close();
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Euphoria | Euphoria | include get.e
function get2(integer fn)
sequence temp
temp = get(fn)
return temp[2] - temp[1]*temp[1]
end function
function read_ppm(sequence filename)
sequence image, line
integer dimx, dimy, maxcolor
atom fn
fn = open(filename, "rb")
if fn < 0 then
return -1 -- unable to open
end if
line = gets(fn)
if not equal(line,"P6\n") then
return -1 -- only ppm6 files are supported
end if
dimx = get2(fn)
if dimx < 0 then
return -1
end if
dimy = get2(fn)
if dimy < 0 then
return -1
end if
maxcolor = get2(fn)
if maxcolor != 255 then
return -1 -- maxcolors other then 255 are not supported
end if
image = repeat(repeat(0,dimy),dimx)
for y = 1 to dimy do
for x = 1 to dimx do
image[x][y] = getc(fn)*#10000 + getc(fn)*#100 + getc(fn)
end for
end for
close(fn)
return image
end function |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #QBasic | QBasic | LET dec$ = ""
LET tipo$ = "cleartext "
PRINT "If decrypting enter 'd' -- else press enter ";
INPUT dec$
PRINT "Enter offset ";
INPUT llave
IF dec$ = "d" THEN
LET llave = 26 - llave
LET tipo$ = "ciphertext "
END IF
PRINT "Enter "; tipo$;
INPUT cadena$
LET cadena$ = UCASE$(cadena$)
LET longitud = LEN(cadena$)
FOR i = 1 TO longitud
LET iTemp = ASC(MID$(cadena$,i,1)) 'QBasic
'LET itemp = ORD((cadena$)[i:i+1-1][1:1]) 'True BASIC
IF iTemp > 64 AND iTemp < 91 THEN
LET iTemp = ((iTemp - 65) + llave) MOD 26 'QBasic
'LET iTemp = MOD(((iTemp - 65) + llave), 26) 'True BASIC
PRINT CHR$(iTemp + 65);
ELSE
PRINT CHR$(iTemp);
END IF
NEXT i
END |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #AutoHotkey | AutoHotkey | file = %A_WorkingDir%\z.dat
IfExist, %A_WorkingDir%\z.dat
FileDelete %file%
IfNotEqual ErrorLevel,0, MsgBox Can't delete file "%file%"`nErrorLevel = "%ErrorLevel%"
res := BinWrite(file,"000102030405060708090a0b0c0d0e0f00")
MsgBox ErrorLevel = %ErrorLevel%`nBytes Written = %res%
res := BinRead(file,data)
MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%"
res := BinWrite(file,"aa00bb",0,2)
MsgBox ErrorLevel = %ErrorLevel%`nBytes Written = %res%
res := BinRead(file,data)
MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%"
res := BinRead(file,data,3,-2)
MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%"
ExitApp
/* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BinWrite ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| - Open binary file
| - (Over)Write n bytes (n = 0: all)
| - From offset (offset < 0: counted from end)
| - Close file
| data -> file[offset + 0..n-1], rest of file unchanged
| Return #bytes actually written
*/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
BinWrite(file, data, n=0, offset=0)
{
; Open file for WRITE (0x40..), OPEN_ALWAYS (4): creates only if it does not exists
h := DllCall("CreateFile","str",file,"Uint",0x40000000,"Uint",0,"UInt",0,"UInt",4,"Uint",0,"UInt",0)
IfEqual h,-1, SetEnv, ErrorLevel, -1
IfNotEqual ErrorLevel,0,Return,0 ; couldn't create the file
m = 0 ; seek to offset
IfLess offset,0, SetEnv,m,2
r := DllCall("SetFilePointerEx","Uint",h,"Int64",offset,"UInt *",p,"Int",m)
IfEqual r,0, SetEnv, ErrorLevel, -3
IfNotEqual ErrorLevel,0, {
t = %ErrorLevel% ; save ErrorLevel to be returned
DllCall("CloseHandle", "Uint", h)
ErrorLevel = %t% ; return seek error
Return 0
}
TotalWritten = 0
m := Ceil(StrLen(data)/2)
If (n <= 0 or n > m)
n := m
Loop %n%
{
StringLeft c, data, 2 ; extract next byte
StringTrimLeft data, data, 2 ; remove used byte
c = 0x%c% ; make it number
result := DllCall("WriteFile","UInt",h,"UChar *",c,"UInt",1,"UInt *",Written,"UInt",0)
TotalWritten += Written ; count written
if (!result or Written < 1 or ErrorLevel)
break
}
IfNotEqual ErrorLevel,0, SetEnv,t,%ErrorLevel%
h := DllCall("CloseHandle", "Uint", h)
IfEqual h,-1, SetEnv, ErrorLevel, -2
IfNotEqual t,,SetEnv, ErrorLevel, %t%
Return TotalWritten
}
/* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BinRead ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| - Open binary file
| - Read n bytes (n = 0: all)
| - From offset (offset < 0: counted from end)
| - Close file
| data (replaced) <- file[offset + 0..n-1]
| Return #bytes actually read
*/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
BinRead(file, ByRef data, n=0, offset=0)
{
h := DllCall("CreateFile","Str",file,"Uint",0x80000000,"Uint",3,"UInt",0,"UInt",3,"Uint",0,"UInt",0)
IfEqual h,-1, SetEnv, ErrorLevel, -1
IfNotEqual ErrorLevel,0,Return,0 ; couldn't open the file
m = 0 ; seek to offset
IfLess offset,0, SetEnv,m,2
r := DllCall("SetFilePointerEx","Uint",h,"Int64",offset,"UInt *",p,"Int",m)
IfEqual r,0, SetEnv, ErrorLevel, -3
IfNotEqual ErrorLevel,0, {
t = %ErrorLevel% ; save ErrorLevel to be returned
DllCall("CloseHandle", "Uint", h)
ErrorLevel = %t% ; return seek error
Return 0
}
TotalRead = 0
data =
IfEqual n,0, SetEnv n,0xffffffff ; almost infinite
format = %A_FormatInteger% ; save original integer format
SetFormat Integer, Hex ; for converting bytes to hex
Loop %n%
{
result := DllCall("ReadFile","UInt",h,"UChar *",c,"UInt",1,"UInt *",Read,"UInt",0)
if (!result or Read < 1 or ErrorLevel)
break
TotalRead += Read ; count read
c += 0 ; convert to hex
StringTrimLeft c, c, 2 ; remove 0x
c = 0%c% ; pad left with 0
StringRight c, c, 2 ; always 2 digits
data = %data%%c% ; append 2 hex digits
}
IfNotEqual ErrorLevel,0, SetEnv,t,%ErrorLevel%
h := DllCall("CloseHandle", "Uint", h)
IfEqual h,-1, SetEnv, ErrorLevel, -2
IfNotEqual t,,SetEnv, ErrorLevel, %t%
SetFormat Integer, %format% ; restore original format
Totalread += 0 ; convert to original format
Return TotalRead
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Visual_Basic_.NET | Visual Basic .NET | Imports System
Imports System.Text.RegularExpressions
Module Bulls_and_Cows
Function CreateNumber() As String
Dim random As New Random()
Dim sequence As Char() = {"1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c}
For i As Integer = 0 To sequence.Length - 1
Dim j As Integer = random.Next(sequence.Length)
Dim temp As Char = sequence(i) : sequence(i) = sequence(j) : sequence(j) = temp
Next
Return New String(sequence, 0, 4)
End Function
Function IsFourDigitNumber(ByVal number As String) As Boolean
Return Regex.IsMatch(number, "^[1-9]{4}$")
End Function
Sub Main()
Dim chosenNumber As String = CreateNumber()
Dim attempt As Integer = 0
Console.WriteLine("Number is chosen")
Dim gameOver As Boolean = False
Do
attempt += 1
Console.WriteLine("Attempt #{0}. Enter four digit number: ", attempt)
Dim number As String = Console.ReadLine()
Do While Not IsFourDigitNumber(number)
Console.WriteLine("Invalid number: type four characters. Every character must digit be between '1' and '9'.")
number = Console.ReadLine()
Loop
Dim bulls As Integer = 0
Dim cows As Integer = 0
For i As Integer = 0 To number.Length - 1
Dim j As Integer = chosenNumber.IndexOf(number(i))
If i = j Then
bulls += 1
ElseIf j >= 0 Then
cows += 1
End If
Next
If bulls < chosenNumber.Length Then
Console.WriteLine("The number '{0}' has {1} bulls and {2} cows", _
number, bulls, cows)
Else
gameOver = True
End If
Loop Until gameOver
Console.WriteLine("The number was guessed in {0} attempts. Congratulations!", attempt)
End Sub
End Module |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Common_Lisp | Common Lisp | (defun write-rgb-buffer-to-ppm-file (filename buffer)
(with-open-file (stream filename
:element-type '(unsigned-byte 8)
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(let* ((dimensions (array-dimensions buffer))
(width (first dimensions))
(height (second dimensions))
(header (format nil "P6~A~D ~D~A255~A"
#\newline
width height #\newline
#\newline)))
(loop
:for char :across header
:do (write-byte (char-code char) stream)) #| Assumes char-codes match ASCII |#
(loop
:for x :upfrom 0 :below width
:do (loop :for y :upfrom 0 :below height
:do (let ((pixel (rgb-pixel buffer x y)))
(let ((red (rgb-pixel-red pixel))
(green (rgb-pixel-green pixel))
(blue (rgb-pixel-blue pixel)))
(write-byte red stream)
(write-byte green stream)
(write-byte blue stream)))))))
filename) |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #FBSL | FBSL | #ESCAPECHARS ON
DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
DIM head, tail, r, g, b, l, ptr, blobsize
FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' Load buffer
blobsize = INSTR(FILEGET, "\n255\n") + 4 ' Get sizeof PPM header
head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' Set loop bounds
FOR ptr = head TO tail STEP 3 ' Transform color triplets
r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order
g = PEEK(ptr + 1, 1)
b = PEEK(ptr + 2, 1)
l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance
POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale
NEXT
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Quackery | Quackery | [ dup upper != ] is lower? ( c --> b )
[ dup lower != ] is upper? ( c --> b )
[ swap $ "" unrot witheach
[ dup lower? iff
[ over +
dup lower? not if
[ 26 - ] ]
else
[ dup upper? if
[ over +
dup upper? not if
[ 26 - ] ] ]
rot swap join swap ]
drop ] is caesar ( $ --> $ )
[ 26 swap - ] is decode ( n --> n )
$ "Fere libenter homines id quod volunt credunt."
dup echo$ cr
23 caesar dup echo$ cr
23 decode caesar echo$ cr |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #BBC_BASIC | BBC BASIC | file$ = @tmp$ + "bitwise.tmp"
test$ = "Hello, world!"
REM Write to file, 7 bits per character:
file% = OPENOUT(file$)
FOR i% = 1 TO LEN(test$)
PROCwritebits(file%, ASCMID$(test$,i%), 7)
NEXT
PROCwritebits(file%, 0, 0)
CLOSE #file%
REM Read from file, 7 bits per character:
file% = OPENIN(file$)
REPEAT
ch% = FNreadbits(file%, 7)
VDU ch%
UNTIL ch% = 0
PRINT
CLOSE #file%
END
REM Write n% bits from b% to file f% (n% = 0 to flush):
DEF PROCwritebits(f%, b%, n%)
PRIVATE a%, c%
IF n% = 0 BPUT #f%,a% : a% = 0 : c% = 0
WHILE n%
IF c% = 8 BPUT #f%,a% : a% = 0 : c% = 0
n% -= 1
c% += 1
IF b% AND 1 << n% THEN a% OR= 1 << (8 - c%)
ENDWHILE
ENDPROC
REM Read n% bits from file f%:
DEF FNreadbits(f%, n%)
PRIVATE a%, c% : LOCAL v%
WHILE n%
IF c% = 0 a% = BGET#f% : c% = 8
n% -= 1
c% -= 1
v% = v% << 1 OR (a% >> c%) AND 1
ENDWHILE
= v% |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
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[] = "abcdefghijk";
unsigned char s2[11] = {0};
int i;
FILE *f = fopen("test.bin", "wb");
bit_filter b = b_attach(f);
/* for each byte in s, write 7 bits skipping 1 */
for (i = 0; i < 10; i++) b_write(s + i, 7, 1, b);
b_detach(b);
fclose(f);
/* read 7 bits and expand to each byte of s2 skipping 1 bit */
f = fopen("test.bin", "rb");
b = b_attach(f);
for (i = 0; i < 10; i++) b_read(s2 + i, 7, 1, b);
b_detach(b);
fclose(f);
printf("%10s\n", s2); /* should be the same first 10 bytes as in s */
return 0;
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Wren | Wren | import "random" for Random
import "/set" for Set
import "/ioutil" for Input
var MAX_GUESSES = 20 // say
var r = Random.new()
var num
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
while (true) {
num = (1234 + r.int(8643)).toString
if (!num.contains("0") && Set.new(num).count == 4) break
}
System.print("All guesses should have exactly 4 distinct digits excluding zero.")
System.print("Keep guessing until you guess the chosen number (maximum %(MAX_GUESSES) valid guesses).\n")
var guesses = 0
while (true) {
var guess = Input.text("Enter your guess : ")
if (guess == num) {
System.print("You've won with %(guesses+1) valid guesses!")
return
}
var n = Num.fromString(guess)
if (!n) {
System.print("Not a valid number")
} else if (guess.contains("-") || guess.contains("+")) {
System.print("Can't contain a sign")
} else if (guess.contains("0")) {
System.print("Can't contain zero")
} else if (guess.count != 4) {
System.print("Must have exactly 4 digits")
} else if (Set.new(guess).count < 4) {
System.print("All digits must be distinct")
} else {
var bulls = 0
var cows = 0
var i = 0
for (c in guess) {
if (num[i] == c) {
bulls = bulls + 1
} else if (num.contains(c)) {
cows = cows + 1
}
i = i + 1
}
System.print("Your score for this guess: Bulls = %(bulls) Cows = %(cows)")
guesses = guesses + 1
if (guesses == MAX_GUESSES) {
System.print("You've now had %(guesses) valid guesses, the maximum allowed")
return
}
}
} |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #D | D |
program btm2ppm;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
Vcl.Graphics;
type
TBitmapHelper = class helper for TBitmap
public
procedure SaveAsPPM(FileName: TFileName);
end;
{ TBitmapHelper }
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
begin
with TBitmap.Create do
begin
LoadFromFile('Input.bmp');
SaveAsPPM('Output.ppm');
Free;
end;
end.
|
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Forth | Forth | : read-ppm { fid -- bmp }
pad dup 80 fid read-line throw 0= abort" Partial line"
s" P6" compare abort" Only P6 supported."
pad dup 80 fid read-line throw 0= abort" Partial line"
0. 2swap >number
1 /string \ skip space
0. 2swap >number
2drop drop nip ( w h )
bitmap { bmp }
pad dup 80 fid read-line throw 0= abort" Partial line"
s" 255" compare abort" Only 8-bits per color channel supported"
0 pad !
bmp bdim
0 do
dup 0 do
pad 3 fid read-file throw
3 - abort" Not enough pixel data in file"
pad @ i j bmp b!
loop
loop drop
bmp ;
\ testing round-trip
4 3 bitmap value test
red test bfill
green 1 2 test b!
s" red.ppm" w/o create-file throw
test over write-ppm
close-file throw
s" red.ppm" r/o open-file throw
dup read-ppm value test2
close-file throw
: bsize ( bmp -- len ) bdim * pixels bdata ;
test dup bsize test2 dup bsize compare . \ 0 if identical |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Fortran | Fortran | subroutine read_ppm(u, img)
integer, intent(in) :: u
type(rgbimage), intent(out) :: img
integer :: i, j, ncol, cc
character(2) :: sign
character :: ccode
img%width = 0
img%height = 0
nullify(img%red)
nullify(img%green)
nullify(img%blue)
read(u, '(A2)') sign
read(u, *) img%width, img%height
read(u, *) ncol
write(0,*) sign
write(0,*) img%width, img%height
write(0,*) ncol
if ( ncol /= 255 ) return
call alloc_img(img, img%width, img%height)
if ( valid_image(img) ) then
do j=1, img%height
do i=1, img%width
read(u, '(A1)', advance='no', iostat=status) ccode
cc = iachar(ccode)
img%red(i,j) = cc
read(u, '(A1)', advance='no', iostat=status) ccode
cc = iachar(ccode)
img%green(i,j) = cc
read(u, '(A1)', advance='no', iostat=status) ccode
cc = iachar(ccode)
img%blue(i,j) = cc
end do
end do
end if
end subroutine read_ppm |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #R | R |
# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
ceasar <- function(x, key)
{
# if key is negative, wrap to be positive
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)
}
# simple examples from description
print(ceasar("hi",2))
print(ceasar("hi",20))
# more advanced example
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=""))
|
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #C.23 | C# | using System;
using System.IO;
public class BitReader
{
uint readData = 0;
int startPosition = 0;
int endPosition = 0;
public int InBuffer
{
get { return endPosition - startPosition; }
}
private Stream stream;
public Stream BaseStream
{
get { return stream; }
}
public BitReader(Stream stream)
{
this.stream = stream;
}
void EnsureData(int bitCount)
{
int readBits = bitCount - InBuffer;
while (readBits > 0)
{
int b = BaseStream.ReadByte();
if (b < 0) throw new InvalidOperationException("Unexpected end of stream");
readData |= checked((uint)b << endPosition);
endPosition += 8;
readBits -= 8;
}
}
public bool ReadBit()
{
return Read(1) > 0;
}
public int Read(int bitCount)
{
EnsureData(bitCount);
int result = (int)(readData >> startPosition) & ((1 << bitCount) - 1);
startPosition += bitCount;
if (endPosition == startPosition)
{
endPosition = startPosition = 0;
readData = 0;
}
else if (startPosition >= 8)
{
readData >>= startPosition;
endPosition -= startPosition;
startPosition = 0;
}
return result;
}
public void Align()
{
endPosition = startPosition = 0;
readData = 0;
}
}
public class BitWriter
{
uint data = 0;
int dataLength = 0;
Stream stream;
public Stream BaseStream
{
get { return stream; }
}
public int BitsToAligment
{
get { return (32 - dataLength) % 8; }
}
public BitWriter(Stream stream)
{
this.stream = stream;
}
public void WriteBit(bool value)
{
Write(value ? 1 : 0, 1);
}
public void Write(int value, int length)
{
uint currentData = data | checked((uint)value << dataLength);
int currentLength = dataLength + length;
while (currentLength >= 8)
{
BaseStream.WriteByte((byte)currentData);
currentData >>= 8;
currentLength -= 8;
}
data = currentData;
dataLength = currentLength;
}
public void Align()
{
if (dataLength > 0)
{
BaseStream.WriteByte((byte)data);
data = 0;
dataLength = 0;
}
}
}
class Program
{
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream();
BitWriter writer = new BitWriter(ms);
writer.WriteBit(true);
writer.Write(5, 3);
writer.Write(0x0155, 11);
writer.Align();
ms.Position = 0;
BitReader reader = new BitReader(ms);
Console.WriteLine(reader.ReadBit());
Console.WriteLine(reader.Read(3));
Console.WriteLine(reader.Read(11).ToString("x4"));
reader.Align();
}
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #zkl | zkl | d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4);
abcd:=d.keys.shuffle();
while(1){
guess:=ask("4 digits: ")-" ,";
if(guess.len()!=4 or guess.unique().len()!=4) continue;
bulls:=abcd.zipWith('==,guess).sum(0);
cows:=guess.split("").enumerate()
.reduce('wrap(s,[(n,c)]){ s + (d.find(c,False) and abcd[n]!=c) },0);
if(bulls==4) { println("You got it!"); break; }
"%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println();
}
fcn s(n){ (n!=1) and "s" or "" } |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Delphi | Delphi |
program btm2ppm;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
Vcl.Graphics;
type
TBitmapHelper = class helper for TBitmap
public
procedure SaveAsPPM(FileName: TFileName);
end;
{ TBitmapHelper }
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
begin
with TBitmap.Create do
begin
LoadFromFile('Input.bmp');
SaveAsPPM('Output.ppm');
Free;
end;
end.
|
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Go | Go | package raster
import (
"errors"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
)
// ReadFrom constructs a Bitmap object from an io.Reader.
func ReadPpmFrom(r io.Reader) (b *Bitmap, err error) {
var all []byte
all, err = ioutil.ReadAll(r)
if err != nil {
return
}
bss := rxHeader.FindSubmatch(all)
if bss == nil {
return nil, errors.New("unrecognized ppm header")
}
x, _ := strconv.Atoi(string(bss[3]))
y, _ := strconv.Atoi(string(bss[6]))
maxval, _ := strconv.Atoi(string(bss[9]))
if maxval > 255 {
return nil, errors.New("16 bit ppm not supported")
}
allCmts := append(append(append(bss[1], bss[4]...), bss[7]...), bss[10]...)
b = NewBitmap(x, y)
b.Comments = rxComment.FindAllString(string(allCmts), -1)
b3 := all[len(bss[0]):]
var n1 int
for i := range b.px {
b.px[i].R = byte(int(b3[n1]) * 255 / maxval)
b.px[i].G = byte(int(b3[n1+1]) * 255 / maxval)
b.px[i].B = byte(int(b3[n1+2]) * 255 / maxval)
n1 += 3
}
return
}
const (
// single whitespace character
ws = "[ \n\r\t\v\f]"
// isolated comment
cmt = "#[^\n\r]*"
// comment sub expression
cmts = "(" + ws + "*" + cmt + "[\n\r])"
// number with leading comments
num = "(" + cmts + "+" + ws + "*|" + ws + "+)([0-9]+)"
)
var rxHeader = regexp.MustCompile("^P6" + num + num + num +
"(" + cmts + "*" + ")" + ws)
var rxComment = regexp.MustCompile(cmt)
// ReadFile writes binary P6 format PPM from the specified filename.
func ReadPpmFile(fn string) (b *Bitmap, err error) {
var f *os.File
if f, err = os.Open(fn); err != nil {
return
}
if b, err = ReadPpmFrom(f); err != nil {
return
}
return b, f.Close()
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Racket | Racket |
#lang racket
(define A (char->integer #\A))
(define Z (char->integer #\Z))
(define a (char->integer #\a))
(define z (char->integer #\z))
(define (rotate c n)
(define cnum (char->integer c))
(define (shift base) (integer->char (+ base (modulo (+ n (- cnum base)) 26))))
(cond [(<= A cnum Z) (shift A)]
[(<= a cnum z) (shift a)]
[else c]))
(define (caesar s n)
(list->string (for/list ([c (in-string s)]) (rotate c n))))
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))
|
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #Common_Lisp | Common Lisp |
(defpackage :rosetta.bitwise-i/o
(:use :common-lisp)
(:export :bitwise-i/o-demo))
(in-package :rosetta.bitwise-i/o)
(defun byte->bit-vector (byte byte-bits)
"Convert one BYTE into a bit-vector of BYTE-BITS length."
(let ((vector (make-array byte-bits :element-type 'bit))
(bit-value 1))
(declare (optimize (speed 3)))
(dotimes (bit-index byte-bits vector)
(setf (aref vector bit-index)
(if (plusp (logand byte (the (unsigned-byte 8) bit-value)))
1 0))
(setq bit-value (ash bit-value 1)))))
(defun bytes->bit-vector (byte-vector byte-bits)
"Convert a BYTE-VECTOR into a bit-vector, with each byte taking BYTE-BITS.
For optimization's sake, I limit the size of the vector to (FLOOR
MOST-POSITIVE-FIXNUM BYTE-BITS), which is somewhat ridiculously long,
but allows the compiler to trust that indices will fit in a FIXNUM."
(reduce (lambda (a b) (concatenate 'bit-vector a b))
(map 'list (lambda (byte) (byte->bit-vector byte byte-bits)) byte-vector)))
(defun ascii-char-p (char)
"True if CHAR is an ASCII character"
(< (char-code char) #x80))
(defun assert-ascii-string (string)
"`ASSERT' that STRING is an ASCII string."
(assert (every #'ascii-char-p string)
(string)
"STRING must contain only ASCII (7-bit) characters;~%“~a”
…contains non-ASCII character~p~:*: ~{~% • ~c ~:*— ~@c ~}"
string (coerce (remove-duplicates (remove-if #'ascii-char-p string)
:test #'char=)
'list)))
(defun ascii-string->bit-vector (string)
"Convert a STRING consisting only of characters in the ASCII \(7-bit)
range into a bit-vector of 7 bits per character.
This assumes \(as is now, in 2017, I believe universally the case) that
the local character code system \(as for `CHAR-CODE' and `CODE-CHAR') is
Unicode, or at least, a superset of ASCII \(eg: ISO-8859-*)
"
(check-type string simple-string)
(assert-ascii-string string)
(bytes->bit-vector (map 'vector #'char-code string) 7))
(defun pad-bit-vector-to-8 (vector)
"Ensure that VECTOR is a multiple of 8 bits in length."
(adjust-array vector (* 8 (ceiling (length vector) 8))))
(defun bit-vector->byte (vector)
"Convert VECTOR into a single byte."
(declare (optimize (speed 3)))
(check-type vector bit-vector)
(assert (<= (length vector) 8))
(reduce (lambda (x y)
(logior (the (unsigned-byte 8)
(ash (the (unsigned-byte 8) x) 1))
(the bit y)))
(reverse vector) :initial-value 0))
(defun bit-vector->bytes (vector byte-size &key (truncatep nil))
"Convert a bit vector VECTOR into a vector of bytes of BYTE-SIZE bits each.
If TRUNCATEP, then discard any trailing bits."
(let* ((out-length (funcall (if truncatep 'floor 'ceiling)
(length vector)
byte-size))
(output (make-array out-length
:element-type (list 'unsigned-byte byte-size))))
(loop for byte from 0 below out-length
for start-bit = 0 then end-bit
for end-bit = byte-size then (min (+ byte-size end-bit)
(length vector))
do (setf (aref output byte)
(bit-vector->byte (subseq vector start-bit end-bit))))
output))
(defun ascii-pack-to-8-bit (string)
"Pack an ASCII STRING into 8-bit bytes (7→8 bit packing)"
(bit-vector->bytes (ascii-string->bit-vector string)
8))
(defun unpack-ascii-from-8-bits (byte-vector)
"Convert an 8-bit BYTE-VECTOR into an array of (unpacked) 7-bit bytes."
(map 'string #'code-char
(bit-vector->bytes
(pad-bit-vector-to-8 (bytes->bit-vector byte-vector 8))
7
:truncatep t)))
(defun write-7->8-bit-string-to-file (string pathname)
"Given a string of 7-bit character STRING, create a new file at PATHNAME
with the contents of that string packed into 8-bit bytes."
(format *trace-output* "~&Writing string to ~a in packed 7→8 bits…~%“~a”"
pathname string)
(assert-ascii-string string)
(with-open-file (output pathname
:direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8))
(write-sequence (ascii-pack-to-8-bit string) output)
(finish-output output)
(let ((expected-length (ceiling (* (length string) 7) 8)))
(assert (= (file-length output) expected-length) ()
"The file written was ~:d byte~:p in length, ~
but the string supplied should have written ~:d byte~:p."
(file-length output) expected-length))))
(defun read-file-into-byte-array (pathname)
"Read a binary file into a byte array"
(with-open-file (input pathname
:direction :input
:if-does-not-exist :error
:element-type '(unsigned-byte 8))
(let ((buffer (make-array (file-length input)
:element-type '(unsigned-byte 8))))
(read-sequence buffer input)
buffer)))
(defun read-8->7-bit-string-from-file (pathname)
"Read 8-bit packed data from PATHNAME and return it as
a 7-bit string."
(unpack-ascii-from-8-bits (read-file-into-byte-array pathname)))
(defun bitwise-i/o-demo (&key (string "Hello, World.")
(pathname #p"/tmp/demo.bin"))
"Writes STRING to PATHNAME after 7→8 bit packing, then reads it back
to validate."
(write-7->8-bit-string-to-file string pathname)
(let ((read-back (read-8->7-bit-string-from-file pathname)))
(assert (equal string read-back) ()
"Reading back string got:~%“~a”~%…expected:~%“~a”" read-back string)
(format *trace-output* "~&String read back matches:~%“~a”" read-back))
(finish-output *trace-output*))
|
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #E | E |
-module(ppm).
-export([ppm/1, write/2]).
-define(WHITESPACE, <<10>>).
-define(SPACE, <<32>>).
% data structure introduced in task Bitmap (module ros_bitmap.erl)
-record(bitmap, {
pixels = nil,
shape = {0, 0}
}).
% create ppm image from bitmap record
ppm(Bitmap) ->
{Width, Height} = Bitmap#bitmap.shape,
Pixels = ppm_pixels(Bitmap),
Maxval = 255, % original ppm format maximum
list_to_binary([
header(), width_and_height(Width, Height), maxval(Maxval), Pixels]).
% write bitmap as ppm file
write(Bitmap, Filename) ->
Ppm = ppm(Bitmap),
{ok, File} = file:open(Filename, [binary, write]),
file:write(File, Ppm),
file:close(File).
%%%%%%%%%%%% four parts of ppm file %%%%%%%%%%%%%%%%%%%%%%
header() ->
[<<"P6">>, ?WHITESPACE].
width_and_height(Width, Height) ->
[encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE].
maxval(Maxval) ->
[encode_decimal(Maxval), ?WHITESPACE].
ppm_pixels(Bitmap) ->
% 24 bit color depth
array:to_list(Bitmap#bitmap.pixels).
%%%%%%%%%%%% Internals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
encode_decimal(Number) ->
integer_to_list(Number).
|
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #Haskell | Haskell | 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" |
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file | Bitmap/Read a PPM file | Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
| #J | J | require 'files'
readppm=: monad define
dat=. fread y NB. read from file
msk=. 1 ,~ (*. 3 >: +/\) (LF&=@}: *. '#'&~:@}.) dat NB. mark field ends
't wbyh maxval dat'=. msk <;._2 dat NB. parse
'wbyh maxval'=. 2 1([ {. [: _99&". (LF,' ')&charsub)&.> wbyh;maxval NB. convert to numeric
if. (_99 0 +./@e. wbyh,maxval) +. 'P6' -.@-: 2{.t do. _1 return. end.
(a. i. dat) makeRGB |.wbyh NB. convert to basic bitmap format
) |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #11l | 11l | FALSE DC X'00'
TRUE DC X'FF' |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Raku | Raku | my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
}
sub decrypt ( $key where 1..25, $cyphertext ) {
$cyphertext.trans( @alpha.rotate($key) Z=> @alpha );
}
my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $en = encrypt( 13, $original );
my $de = decrypt( 13, $en );
.say for $original, $en, $de;
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 ); |
http://rosettacode.org/wiki/Bitwise_IO | Bitwise IO | The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
quantized by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0000 (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a rough (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see LZW compression) use fixed or variable words
nine (or more) bits long.
Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
Errors handling is not mandatory
| #D | D | import std.stdio: File;
import core.stdc.stdio: FILE, fputc, fgetc;
import std.string: representation;
/***********
Bitwise I/O, the file must be in binary mode, and its FILE*
must be kept open during the usage of BitwiseFile.
*/
struct BitwiseFile {
FILE* fp;
uint accu;
int bits;
this(File f)
in {
assert(f.isOpen);
//assert(f.isBinary);
} body {
this.fp = f.getFP();
}
void write(const(ubyte)[] buf, size_t nBits, size_t shift)
nothrow {
auto accu = this.accu;
auto bits = this.bits;
auto bufPtr = buf.ptr;
bufPtr += shift / 8;
shift %= 8;
while (nBits || bits >= 8) {
while (bits >= 8) {
bits -= 8;
fputc(accu >> bits, this.fp);
accu &= (1 << bits) - 1;
}
while (bits < 8 && nBits) {
accu = (accu << 1) |
(((128 >> shift) & *bufPtr) >> (7 - shift));
nBits--;
bits++;
shift++;
if (shift == 8) {
shift = 0;
bufPtr++;
}
}
}
this.accu = accu;
this.bits = bits;
}
size_t read(ubyte[] buf, size_t nBits, size_t shift) nothrow {
auto accu = this.accu;
auto bits = this.bits;
auto bufPtr = buf.ptr;
int i = 0;
bufPtr += shift / 8;
shift %= 8;
while (nBits) {
while (bits && nBits) {
immutable mask = 128u >> shift;
if (accu & (1 << (bits - 1)))
*bufPtr |= mask;
else
*bufPtr &= ~mask;
nBits--;
bits--;
shift++;
if (shift >= 8) {
shift = 0;
bufPtr++;
}
}
if (!nBits)
break;
accu = (accu << 8) | fgetc(this.fp);
bits += 8;
}
this.accu = accu;
this.bits = bits;
return i;
}
void detach() nothrow {
if (this.bits) {
this.accu <<= 8 - this.bits;
fputc(this.accu, this.fp);
}
this.fp = null;
this.accu = 0;
this.bits = 0;
}
nothrow ~this() {
detach;
}
}
void main() { // Demo code.
import core.stdc.stdio: fopen, fclose;
import std.string: assumeUTF;
import std.stdio: writeln;
immutable data = "abcdefghijk".representation;
enum n = data.length;
// For each ubyte in data, write 7 bits skipping 1.
auto fout = File("bitwise_io_test.bin", "wb");
auto bf1 = BitwiseFile(fout);
foreach (immutable i; 0 .. n)
bf1.write(data[i .. $], 7, 1);
bf1.detach();
fout.close();
// Read 7 bits and expand to each ubyte of result skipping 1 bit.
ubyte[n + 1] result = '\0';
auto fin = File("bitwise_io_test.bin", "rb");
auto bf2 = BitwiseFile(fin);
foreach (immutable i; 0 .. n)
bf2.read(result[i .. $], 7, 1);
bf2.detach();
fin.close();
// Should be the same chars as 'data'.
result.assumeUTF.writeln;
} |
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file | Bitmap/Write a PPM file | Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)
| #Erlang | Erlang |
-module(ppm).
-export([ppm/1, write/2]).
-define(WHITESPACE, <<10>>).
-define(SPACE, <<32>>).
% data structure introduced in task Bitmap (module ros_bitmap.erl)
-record(bitmap, {
pixels = nil,
shape = {0, 0}
}).
% create ppm image from bitmap record
ppm(Bitmap) ->
{Width, Height} = Bitmap#bitmap.shape,
Pixels = ppm_pixels(Bitmap),
Maxval = 255, % original ppm format maximum
list_to_binary([
header(), width_and_height(Width, Height), maxval(Maxval), Pixels]).
% write bitmap as ppm file
write(Bitmap, Filename) ->
Ppm = ppm(Bitmap),
{ok, File} = file:open(Filename, [binary, write]),
file:write(File, Ppm),
file:close(File).
%%%%%%%%%%%% four parts of ppm file %%%%%%%%%%%%%%%%%%%%%%
header() ->
[<<"P6">>, ?WHITESPACE].
width_and_height(Width, Height) ->
[encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE].
maxval(Maxval) ->
[encode_decimal(Maxval), ?WHITESPACE].
ppm_pixels(Bitmap) ->
% 24 bit color depth
array:to_list(Bitmap#bitmap.pixels).
%%%%%%%%%%%% Internals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
encode_decimal(Number) ->
integer_to_list(Number).
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.