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/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #D | D | import bitmap: Image, RGB;
void circle(Color)(Image!Color img, in int x0, in int y0,
in int radius, in Color color)
pure nothrow @nogc @safe {
int f = 1 - radius;
int ddfX = 1;
int ddfY = -2 * radius;
int x = 0;
int y = radius;
img[x0, y0 + radius] = color;
img[x0, y0 - radius] = color;
img[x0 + radius, y0] = color;
img[x0 - radius, y0] = color;
while (x < y) {
if (f >= 0) {
y--;
ddfY += 2;
f += ddfY;
}
x++;
ddfX += 2;
f += ddfX;
img[x0 + x, y0 + y] = color;
img[x0 - x, y0 + y] = color;
img[x0 + x, y0 - y] = color;
img[x0 - x, y0 - y] = color;
img[x0 + y, y0 + x] = color;
img[x0 - y, y0 + x] = color;
img[x0 + y, y0 - x] = color;
img[x0 - y, y0 - x] = color;
}
}
void main() @safe {
auto img = new Image!RGB(25, 25);
img.clear(RGB.white);
circle(img, 12, 12, 12, RGB.black);
img.textualShow;
} |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #11l | 11l | T Colour
Byte r, g, b
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
F (r, g, b)
.r = r
.g = g
.b = 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 chardisplay()
V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’))
txt = txt.map(row -> ‘|’row‘|’)
txt.insert(0, ‘+’(‘-’ * .width)‘+’)
txt.append(‘+’(‘-’ * .width)‘+’)
print(reversed(txt).join("\n"))
F set(x, y, colour = black)
.map[y][x] = colour
F get(x, y)
R .map[y][x]
F line(x0, y0, x1, y1)
‘Bresenham's line algorithm’
V dx = abs(x1 - x0)
V dy = abs(y1 - y0)
V (x, y) = (x0, y0)
V sx = I x0 > x1 {-1} E 1
V sy = I y0 > y1 {-1} E 1
I dx > dy
V err = dx / 2.0
L x != x1
.set(x, y)
err -= dy
I err < 0
y += sy
err += dx
x += sx
E
V err = dy / 2.0
L y != y1
.set(x, y)
err -= dx
I err < 0
x += sx
err += dy
y += sy
.set(x, y)
F cubicbezier(x0, y0, x1, y1, x2, y2, x3, y3, n = 20)
[(Int, Int)] pts
L(i) 0 .. n
V t = Float(i) / n
V a = (1. - t) ^ 3
V b = 3. * t * (1. - t) ^ 2
V c = 3.0 * t ^ 2 * (1.0 - t)
V d = t ^ 3
V x = Int(a * x0 + b * x1 + c * x2 + d * x3)
V y = Int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append((x, y))
L(i) 0 .< n
.line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1])
V bitmap = Bitmap(17, 17)
bitmap.cubicbezier(16, 1, 1, 4, 3, 16, 15, 11)
bitmap.chardisplay() |
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
| #Wren | Wren | import "io" for File
class BitFilter {
construct new(name) {
_name = name
_accu = 0
_bits = 0
}
openWriter() {
_bw = File.create(_name)
}
openReader() {
_br = File.open(_name)
_offset = 0
}
write(buf, start, nBits, shift) {
var index = start + (shift/8).floor
shift = shift % 8
while (nBits != 0 || _bits >= 8) {
while (_bits >= 8) {
_bits = _bits - 8
_bw.writeBytes(String.fromByte((_accu >> _bits) & 255))
}
while (_bits < 8 && nBits != 0) {
var b = buf[index]
_accu = (_accu << 1) | (((128 >> shift) & b) >> (7 - shift))
nBits = nBits - 1
_bits = _bits + 1
shift = shift + 1
if (shift == 8) {
shift = 0
index = index + 1
}
}
}
}
read(buf, start, nBits, shift) {
var index = start + (shift/8).floor
shift = shift % 8
while (nBits != 0) {
while (_bits != 0 && nBits != 0) {
var mask = 128 >> shift
if ((_accu & (1 << (_bits - 1))) != 0) {
buf[index] = (buf[index] | mask) & 255
} else {
buf[index] = (buf[index] & ~mask) & 255
}
nBits = nBits - 1
_bits = _bits - 1
shift = shift + 1
if (shift >= 8) {
shift = 0
index = index + 1
}
}
if (nBits == 0) break
var byte = _br.readBytes(1, _offset).bytes[0]
_accu = (_accu << 8) | byte
_bits = _bits + 8
_offset = _offset + 1
}
}
closeWriter() {
if (_bits != 0) {
_accu = _accu << (8 - _bits)
_bw.writeBytes(String.fromByte(_accu & 255))
}
_bw.close()
_accu = 0
_bits = 0
}
closeReader() {
_br.close()
_accu = 0
_bits = 0
_offset = 0
}
}
var s = "abcdefghijk".bytes.toList
var f = "test.bin"
var bf = BitFilter.new(f)
/* for each byte in s, write 7 bits skipping 1 */
bf.openWriter()
for (i in 0...s.count) bf.write(s, i, 7, 1)
bf.closeWriter()
/* read 7 bits and expand to each byte of s2 skipping 1 bit */
bf.openReader()
var s2 = List.filled(s.count, 0)
for (i in 0...s2.count) bf.read(s2, i, 7, 1)
bf.closeReader()
System.print(s2.map { |b| String.fromByte(b) }.join()) |
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.)
| #REXX | REXX | /*REXX program writes a PPM formatted image file, also known as a P6 (binary) file. */
green = 00ff00 /*define a pixel with the color green. */
parse arg oFN width height color . /*obtain optional arguments from the CL*/
if oFN=='' | oFN=="," then oFN='IMAGE' /*Not specified? Then use the default.*/
if width=='' | width=="," then width= 20 /* " " " " " " */
if height=='' | height=="," then height= 20 /* " " " " " " */
if color=='' | color=="," then color= green /* " " " " " " */
oFID= oFN'.PPM' /*define oFID by adding an extension.*/
@. = x2c(color) /*set all pixels of image a hex color. */
$ = '9'x /*define the separator (in the header).*/
# = 255 /* " " max value for all colors. */
call charout oFID, , 1 /*set the position of the file's output*/
call charout oFID,'P6'width || $ || height || $ || # || $ /*write file header info. */
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k /*write the PPM file, 1 pixel at a time*/
end /*k*/ /* ↑ a pixel contains three bytes, */
end /*j*/ /* └────which defines the pixel's color*/
call charout oFID, _ /*write the image's raster to the file.*/
call charout oFID /*close the output file just to be safe*/
/*stick a fork in it, we're all 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.)
| #Ruby | Ruby | class RGBColour
def values
[@red, @green, @blue]
end
end
class Pixmap
def save(filename)
File.open(filename, 'w') do |f|
f.puts "P6", "#{@width} #{@height}", "255"
f.binmode
@height.times do |y|
@width.times do |x|
f.print @data[x][y].values.pack('C3')
end
end
end
end
alias_method :write, :save
end |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Ada | Ada | procedure Flood_Fill
( Picture : in out Image;
From : Point;
Fill : Pixel;
Replace : Pixel;
Distance : Luminance := 20
) is
function Diff (A, B : Luminance) return Luminance is
pragma Inline (Diff);
begin
if A > B then
return A - B;
else
return B - A;
end if;
end Diff;
function "-" (A, B : Pixel) return Luminance is
pragma Inline ("-");
begin
return Luminance'Max (Luminance'Max (Diff (A.R, B.R), Diff (A.G, B.G)), Diff (A.B, B.B));
end "-";
procedure Column (From : Point);
procedure Row (From : Point);
Visited : array (Picture'Range (1), Picture'Range (2)) of Boolean :=
(others => (others => False));
procedure Column (From : Point) is
X1 : Positive := From.X;
X2 : Positive := From.X;
begin
Visited (From.X, From.Y) := True;
for X in reverse Picture'First (1)..From.X - 1 loop
exit when Visited (X, From.Y);
declare
Color : Pixel renames Picture (X, From.Y);
begin
Visited (X, From.Y) := True;
exit when Color - Replace > Distance;
Color := Fill;
X1 := X;
end;
end loop;
for X in From.X + 1..Picture'Last (1) loop
exit when Visited (X, From.Y);
declare
Color : Pixel renames Picture (X, From.Y);
begin
Visited (X, From.Y) := True;
exit when Color - Replace > Distance;
Color := Fill;
X2 := X;
end;
end loop;
for X in X1..From.X - 1 loop
Row ((X, From.Y));
end loop;
for X in From.X + 1..X2 loop
Row ((X, From.Y));
end loop;
end Column;
procedure Row (From : Point) is
Y1 : Positive := From.Y;
Y2 : Positive := From.Y;
begin
Visited (From.X, From.Y) := True;
for Y in reverse Picture'First (2)..From.Y - 1 loop
exit when Visited (From.X, Y);
declare
Color : Pixel renames Picture (From.X, Y);
begin
Visited (From.X, Y) := True;
exit when Color - Replace > Distance;
Color := Fill;
Y1 := Y;
end;
end loop;
for Y in From.Y + 1..Picture'Last (2) loop
exit when Visited (From.X, Y);
declare
Color : Pixel renames Picture (From.X, Y);
begin
Visited (From.X, Y) := True;
exit when Color - Replace > Distance;
Color := Fill;
Y2 := Y;
end;
end loop;
for Y in Y1..From.Y - 1 loop
Column ((From.X, Y));
end loop;
for Y in From.Y + 1..Y2 loop
Column ((From.X, Y));
end loop;
end Row;
Color : Pixel renames Picture (From.X, From.Y);
begin
if Color - Replace <= Distance then
Visited (From.X, From.Y) := True;
Color := Fill;
Column (From);
end if;
end Flood_Fill; |
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
| #Crystal | Crystal | if false
puts "false"
elsif nil
puts "nil"
elsif Pointer(Nil).new 0
puts "null pointer"
elsif true && "any other value"
puts "finally true!"
end |
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
| #D | D | #t // <boolean> true
#f // <boolean> false |
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
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
PRINT "text orginal ",text
abc="ABCDEFGHIJKLMNOPQRSTUVWXYZ",key=3,caesarskey=key+1
secretbeg=EXTRACT (abc,#caesarskey,0)
secretend=EXTRACT (abc,0,#caesarskey)
secretabc=CONCAT (secretbeg,secretend)
abc=STRINGS (abc,":</:"),secretabc=STRINGS (secretabc,":</:")
abc=SPLIT (abc), secretabc=SPLIT (secretabc)
abc2secret=JOIN(abc," ",secretabc),secret2abc=JOIN(secretabc," ",abc)
BUILD X_TABLE abc2secret=*
DATA {abc2secret}
BUILD X_TABLE secret2abc=*
DATA {secret2abc}
ENCODED = EXCHANGE (text,abc2secret)
PRINT "text encoded ",encoded
DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #BASIC256 | BASIC256 | arraybase 1
dim names$ = {"North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west", "North"}
dim grados = {0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38}
for i = grados[?,] to grados[?]
j = int((grados[i] + 5.625) / 11.25)
if j > 31 then j -= 32
print rjust(string(j),2); " "; ljust(string(names$[j+1]),20); grados[i]
next i |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ImageLevels[img] |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Nim | Nim | import bitmap
import grayscale_image
type Histogram = array[Luminance, Natural]
#---------------------------------------------------------------------------------------------------
func histogram*(img: GrayImage): Histogram =
## Build and return gray scale image histogram.
for lum in img.pixels:
inc result[lum]
#---------------------------------------------------------------------------------------------------
func median*(hist: Histogram): Luminance =
# Return the median luminance of a histogram.
var
inf = byte(0)
sup = Luminance.high
infCount, supCount = 0
while inf != sup:
if infCount < supCount:
inc infCount, hist[inf]
inc inf
else:
inc supCount, hist[sup]
dec sup
result = inf
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import ppm_read, ppm_write
# Read an image.
let image = readPPM("house.ppm")
# Build its histogram and find the median luminance.
let grayImage = image.toGrayImage
let hist = grayImage.histogram()
let m = hist.median()
echo "Median luminance: ", m
# Convert to black and white.
for pt in image.indices:
image[pt.x, pt.y] = if grayImage[pt.x, pt.y] < m: Black else: White
# Save image as a PPM file.
image.writePPM("house_bw.ppm") |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #OCaml | OCaml | type histogram = int array
let get_histogram ~img:gray_channel =
let width = Bigarray.Array2.dim1 gray_channel
and height = Bigarray.Array2.dim2 gray_channel in
let t = Array.make 256 0 in
for x = 0 to pred width do
for y = 0 to pred height do
let v = gray_get_pixel_unsafe gray_channel x y in
t.(v) <- t.(v) + 1;
done;
done;
(t: histogram)
;; |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #ActionScript | ActionScript | function bitwise(a:int, b:int):void
{
trace("And: ", a & b);
trace("Or: ", a | b);
trace("Xor: ", a ^ b);
trace("Not: ", ~a);
trace("Left Shift: ", a << b);
trace("Right Shift(Arithmetic): ", a >> b);
trace("Right Shift(Logical): ", a >>> b);
} |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Julia | Julia | // Version 1.2.40
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import kotlin.math.abs
import java.io.File
import javax.imageio.ImageIO
class Point(var x: Int, var y: Int)
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) {
val dx = abs(x1 - x0)
val dy = abs(y1 - y0)
val sx = if (x0 < x1) 1 else -1
val sy = if (y0 < y1) 1 else -1
var xx = x0
var yy = y0
var e1 = (if (dx > dy) dx else -dy) / 2
var e2: Int
while (true) {
setPixel(xx, yy, c)
if (xx == x1 && yy == y1) break
e2 = e1
if (e2 > -dx) { e1 -= dy; xx += sx }
if (e2 < dy) { e1 += dx; yy += sy }
}
}
fun quadraticBezier(p1: Point, p2: Point, p3: Point, clr: Color, n: Int) {
val pts = List(n + 1) { Point(0, 0) }
for (i in 0..n) {
val t = i.toDouble() / n
val u = 1.0 - t
val a = u * u
val b = 2.0 * t * u
val c = t * t
pts[i].x = (a * p1.x + b * p2.x + c * p3.x).toInt()
pts[i].y = (a * p1.y + b * p2.y + c * p3.y).toInt()
setPixel(pts[i].x, pts[i].y, clr)
}
for (i in 0 until n) {
val j = i + 1
drawLine(pts[i].x, pts[i].y, pts[j].x, pts[j].y, clr)
}
}
}
fun main(args: Array<String>) {
val width = 320
val height = 320
val bbs = BasicBitmapStorage(width, height)
with (bbs) {
fill(Color.cyan)
val p1 = Point(10, 100)
val p2 = Point(250, 270)
val p3 = Point(150, 20)
quadraticBezier(p1, p2, p3, Color.black, 20)
val qbFile = File("quadratic_bezier.jpg")
ImageIO.write(image, "jpg", qbFile)
}
} |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #ERRE | ERRE | PROGRAM BCircle
!$INCLUDE="PC.LIB"
PROCEDURE BCircle(cx%,cy%,r%)
local f%,x%,y%,ddx%,ddy%
f%=1-r% y%=r% ddy%=-2*r%
PSET(cx%,cy%+r%,1)
PSET(cx%,cy%-r%,1)
PSET(cx%+r%,cy%,1)
PSET(cx%-r%,cy%,1)
WHILE x%<y% DO
IF f%>=0 THEN
y%=y%-1
ddy%=ddy%+2
f%=f%+ddy%
END IF
x%=x%+1
ddx%=ddx%+2
f%=f%+ddx%+1
PSET(cx%+x%,cy%+y%,1)
PSET(cx%-x%,cy%+y%,1)
PSET(cx%+x%,cy%-y%,1)
PSET(cx%-x%,cy%-y%,1)
PSET(cx%+y%,cy%+x%,1)
PSET(cx%-y%,cy%+x%,1)
PSET(cx%+y%,cy%-x%,1)
PSET(cx%-y%,cy%-x%,1)
END WHILE
END PROCEDURE
BEGIN
SCREEN(1)
! Draw circles
BCircle(100,100,40)
BCircle(100,100,80)
END PROGRAM
|
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #FBSL | FBSL | #DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_CLOSE 16
FBSLSETTEXT(ME, "Bresenham Circle") ' Set form caption
FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color
FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments
RESIZE(ME, 0, 0, 220, 220)
CENTER(ME)
SHOW(ME)
DIM Breadth AS INTEGER, Height AS INTEGER
FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height)
BEGIN EVENTS ' Main message loop
SELECT CASE CBMSG
CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw
CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up
END SELECT
END EVENTS
SUB MidpointCircle()
BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order
BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black
SUB BresenhamCircle(cx, cy, radius, colour)
DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius
PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour)
PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour)
WHILE x < y
IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :)
INCR(x)(dx, 2)(f, dx + 1)
PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour)
PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour)
PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour)
PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour)
WEND
END SUB
END SUB |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #Action.21 | Action! | INCLUDE "H6:RGBLINE.ACT" ;from task Bresenham's line algorithm
INCLUDE "H6:REALMATH.ACT"
RGB black,yellow,violet,blue
TYPE IntPoint=[INT x,y]
PROC CubicBezier(RgbImage POINTER img
IntPoint POINTER p1,p2,p3,p4 RGB POINTER col)
INT i,n=[20],prevX,prevY,nextX,nextY
REAL one,two,three,ri,rn,rt,ra,rb,rc,rd,tmp1,tmp2,tmp3
REAL x1,y1,x2,y2,x3,y3,x4,y4
IntToReal(p1.x,x1) IntToReal(p1.y,y1)
IntToReal(p2.x,x2) IntToReal(p2.y,y2)
IntToReal(p3.x,x3) IntToReal(p3.y,y3)
IntToReal(p4.x,x4) IntToReal(p4.y,y4)
IntToReal(1,one) IntToReal(2,two)
IntToReal(3,three) IntToReal(n,rn)
FOR i=0 TO n
DO
prevX=nextX prevY=nextY
IntToReal(i,ri)
RealDiv(ri,rn,rt) ;t=i/n
RealSub(one,rt,tmp1) ;tmp1=1-t
RealMult(tmp1,tmp1,tmp2) ;tmp2=(1-t)^2
RealMult(tmp2,tmp1,ra) ;a=(1-t)^3
RealMult(three,rt,tmp2) ;tmp2=3*t
RealMult(tmp1,tmp1,tmp3) ;tmp3=(1-t)^2
RealMult(tmp2,tmp3,rb) ;b=3*t*(1-t)^2
RealMult(three,rt,tmp2) ;tmp2=3*t
RealMult(rt,tmp1,tmp3) ;tmp3=t*(1-t)
RealMult(tmp2,tmp3,rc) ;c=3*t^2*(1-t)
RealMult(rt,rt,tmp2) ;tmp2=t^2
RealMult(tmp2,rt,rd) ;d=t^3
RealMult(ra,x1,tmp1) ;tmp1=a*x1
RealMult(rb,x2,tmp2) ;tmp2=b*x2
RealAdd(tmp1,tmp2,tmp3) ;tmp3=a*x1+b*x2
RealMult(rc,x3,tmp1) ;tmp1=c*x3
RealAdd(tmp3,tmp1,tmp2) ;tmp2=a*x1+b*x2+c*x3
RealMult(rd,x4,tmp1) ;tmp1=d*x4
RealAdd(tmp2,tmp1,tmp3) ;tmp3=a*x1+b*x2+c*x3+d*x4
nextX=Round(tmp3)
RealMult(ra,y1,tmp1) ;tmp1=a*y1
RealMult(rb,y2,tmp2) ;tmp2=b*y2
RealAdd(tmp1,tmp2,tmp3) ;tmp3=a*y1+b*y2
RealMult(rc,y3,tmp1) ;tmp1=c*y3
RealAdd(tmp3,tmp1,tmp2) ;tmp2=a*y1+b*y2+c*y3
RealMult(rd,y4,tmp1) ;tmp1=d*y4
RealAdd(tmp2,tmp1,tmp3) ;tmp3=a*y1+b*y2+c*y3+d*y4
nextY=Round(tmp3)
IF i>0 THEN
RgbLine(img,prevX,prevY,nextX,nextY,col)
FI
OD
RETURN
PROC DrawImage(RgbImage POINTER img BYTE x,y)
RGB POINTER ptr
BYTE i,j
ptr=img.data
FOR j=0 TO img.h-1
DO
FOR i=0 TO img.w-1
DO
IF RgbEqual(ptr,yellow) THEN
Color=1
ELSEIF RgbEqual(ptr,violet) THEN
Color=2
ELSEIF RgbEqual(ptr,blue) THEN
Color=3
ELSE
Color=0
FI
Plot(x+i,y+j)
ptr==+RGBSIZE
OD
OD
RETURN
PROC Main()
RgbImage img
BYTE CH=$02FC,width=[70],height=[40]
BYTE ARRAY ptr(8400)
IntPoint p1,p2,p3,p4
Graphics(7+16)
SetColor(0,13,12) ;yellow
SetColor(1,4,8) ;violet
SetColor(2,8,6) ;blue
SetColor(4,0,0) ;black
RgbBlack(black)
RgbYellow(yellow)
RgbViolet(violet)
RgbBlue(blue)
InitRgbImage(img,width,height,ptr)
FillRgbImage(img,black)
p1.x=0 p1.y=3
p2.x=10 p2.y=39
p3.x=69 p3.y=31
p4.x=40 p4.y=8
RgbLine(img,p1.x,p1.y,p2.x,p2.y,blue)
RgbLine(img,p2.x,p2.y,p3.x,p3.y,blue)
RgbLine(img,p3.x,p3.y,p4.x,p4.y,blue)
CubicBezier(img,p1,p2,p3,p4,yellow)
SetRgbPixel(img,p1.x,p1.y,violet)
SetRgbPixel(img,p2.x,p2.y,violet)
SetRgbPixel(img,p3.x,p3.y,violet)
SetRgbPixel(img,p4.x,p4.y,violet)
DrawImage(img,(160-width)/2,(96-height)/2)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #Ada | Ada | procedure Cubic_Bezier
( Picture : in out Image;
P1, P2, P3, P4 : Point;
Color : Pixel;
N : Positive := 20
) is
Points : array (0..N) of Point;
begin
for I in Points'Range loop
declare
T : constant Float := Float (I) / Float (N);
A : constant Float := (1.0 - T)**3;
B : constant Float := 3.0 * T * (1.0 - T)**2;
C : constant Float := 3.0 * T**2 * (1.0 - T);
D : constant Float := T**3;
begin
Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X) + D * Float (P4.X));
Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y) + D * Float (P4.Y));
end;
end loop;
for I in Points'First..Points'Last - 1 loop
Line (Picture, Points (I), Points (I + 1), Color);
end loop;
end Cubic_Bezier; |
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
| #Z80_Assembly | Z80 Assembly | StoreBinaryString:
;INPUT:
; HL = SOURCE ADDRESS
; DE = OUTPUT STRING RAM
; BC = HOW MANY BYTES OF SOURCE DATA TO CONVERT
ld a,(hl)
push bc
ld b,a ;backup a for later
ld c,%10000000 ;a "revolving bit mask" is used to compare
; each bit of A, in sequence.
loop:
ld a,b ;restore A
and c
ld a,'0' ;get ascii 0 into A. This does not affect the flags!
jr z,skip ;this jump is based on the result of B AND C
inc a ;convert ascii 0 into ascii 1, only if B AND C was nonzero.
skip:
LD (DE),A ;store in output string
inc de ;next byte of output string
rrc c ;shift the bit mask down to the next bit of A
jr nc,loop ;once a 1 is shifted into the carry, we're finished. Otherwise, check next bit.
pop bc
inc hl
dec bc
ld a,b
or c
jp nz,StoreBinaryString
ret |
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.)
| #Rust | Rust | use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM { height: height, width: width, data: buffer }
}
fn buffer_size(&self) -> u32 {
3 * self.height * self.width
}
fn get_offset(&self, x: u32, y: u32) -> Option<usize> {
let offset = (y * self.width * 3) + (x * 3);
if offset < self.buffer_size() {
Some(offset as usize)
} else {
None
}
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<RGB> {
match self.get_offset(x, y) {
Some(offset) => {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB {r: r, g: g, b: b})
},
None => None
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = color.b;
true
},
None => false
}
}
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = File::create(&path)?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
file.write(header.as_bytes())?;
file.write(&self.data)?;
Ok(())
}
} |
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.)
| #Scala | Scala | object Pixmap {
def save(bm:RgbBitmap, filename:String)={
val out=new DataOutputStream(new FileOutputStream(filename))
out.writeBytes("P6\u000a%d %d\u000a%d\u000a".format(bm.width, bm.height, 255))
for(y <- 0 until bm.height; x <- 0 until bm.width; c=bm.getPixel(x, y)){
out.writeByte(c.getRed)
out.writeByte(c.getGreen)
out.writeByte(c.getBlue)
}
}
} |
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #C | C | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #AutoHotkey | AutoHotkey | SetBatchLines, -1
CoordMode, Mouse
CoordMode, Pixel
CapsLock::
KeyWait, CapsLock
MouseGetPos, X, Y
PixelGetColor, color, X, Y
FloodFill(x, y, color, 0x000000, 1, "CapsLock")
MsgBox Done!
Return
FloodFill(x, y, target, replacement, mode=1, key="")
{
If GetKeyState(key, "P")
Return
PixelGetColor, color, x, y
If (color <> target || color = replacement || target = replacement)
Return
VarSetCapacity(Rect, 16, 0)
NumPut(x, Rect, 0)
NumPut(y, Rect, 4)
NumPut(x+1, Rect, 8)
NumPut(y+1, Rect, 12)
hDC := DllCall("GetDC", UInt, 0)
hBrush := DllCall("CreateSolidBrush", UInt, replacement)
DllCall("FillRect", UInt, hDC, Str, Rect, UInt, hBrush)
DllCall("ReleaseDC", UInt, 0, UInt, hDC)
DllCall("DeleteObject", UInt, hBrush)
FloodFill(x+1, y, target, replacement, mode, key)
FloodFill(x-1, y, target, replacement, mode, key)
FloodFill(x, y+1, target, replacement, mode, key)
FloodFill(x, y-1, target, replacement, mode, key)
If (mode = 2 || mode = 4)
FloodFill(x, y, target, replacement, mode, key)
If (Mode = 3 || mode = 4)
{
FloodFill(x+1, y+1, target, replacement, key)
FloodFill(x-1, y+1, target, replacement, key)
FloodFill(x+1, y-1, target, replacement, key)
FloodFill(x-1, y-1, target, replacement, key)
}
} |
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
| #Dc | Dc | #t // <boolean> true
#f // <boolean> false |
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
| #Delphi | Delphi | #t // <boolean> true
#f // <boolean> false |
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
| #TXR | TXR | @(next :args)
@(cases)
@{key /[0-9]+/}
@text
@(or)
@ (throw error "specify <key-num> <text>")
@(end)
@(do
(defvar k (int-str key 10)))
@(bind enc-dec
@(collect-each ((i (range 0 25)))
(let* ((p (tostringp (+ #\a i)))
(e (tostringp (+ #\a (mod (+ i k) 26))))
(P (upcase-str p))
(E (upcase-str e)))
^(((,p ,e) (,P ,E))
((,e ,p) (,E ,P))))))
@(deffilter enc . @(mappend (fun first) enc-dec))
@(deffilter dec . @(mappend (fun second) enc-dec))
@(output)
encoded: @{text :filter enc}
decoded: @{text :filter dec}
@(end) |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #BBC_BASIC | BBC BASIC | DIM bearing(32)
bearing() = 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, \
\ 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, \
\ 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, \
\ 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38
FOR i% = 0 TO 32
box% = FNcompassbox(bearing(i%), compass$)
PRINT ; bearing(i%), ; box%, compass$
NEXT
END
DEF FNcompassbox(bearing, RETURN box$)
LOCAL pt%
pt% = INT(bearing / 360 * 32 + 0.5) MOD 32
box$ = FNpt(pt%)
LEFT$(box$,1) = CHR$(ASC(LEFT$(box$,1))-32)
= pt% + 1
DEF FNpt(pt%)
LOCAL pt$() : DIM pt$(3)
IF pt% AND 1 THEN = FNpt((pt% + 1) AND 28) + " by " + \
\ FNpt(((2 - (pt% AND 2)) * 4) + pt% AND 24)
IF pt% AND 2 THEN = FNpt((pt% + 2) AND 24) + "-" + FNpt((pt% OR 4) AND 28)
IF pt% AND 4 THEN = FNpt((pt% + 8) AND 16) + FNpt((pt% OR 8) AND 24)
pt$() = "north", "east", "south", "west"
= pt$(pt% DIV 8)
|
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Octave | Octave | function h = imagehistogram(imago)
if ( isgray(imago) )
for j = 0:255
h(j+1) = numel(imago( imago == j ));
endfor
else
error("histogram on gray img only");
endif
endfunction
% test
im = jpgread("Lenna100.jpg");
img = rgb2gray(im);
h = imagehistogram(img);
% let's try to show the histogram
bar(h);
pause;
% in order to obtain the requested filtering, we
% can use median directly on the img, and then
% use that value, this way:
m = median(reshape(img, 1, numel(img)));
disp(m);
ibw = img;
ibw( img > m ) = 255;
ibw( img <= m ) = 0;
jpgwrite("lennamed_.jpg", ibw, 100);
% which disagree (128) with the m computed with histog_med (130).
% If we compute it this way:
% m = sort(reshape(img, 1, numel(img)))(ceil(numel(img)/2));
% we obtain 130... but builtin median works as expected, since
% N (number of pixel of Lenna) is even, not odd.
% but let's use our histogram h instead
function m = histog_med(histog)
from = 0; to = 255;
left = histog(from + 1); right = histog(to+1);
while ( from != to )
if ( left < right )
from++; left += histog(from+1);
else
to--; right += histog(to+1);
endif
endwhile
m = from;
endfunction
m = histog_med(h);
disp(m);
ibw( img > m ) = 255;
ibw( img <= m ) = 0;
jpgwrite("lennamed.jpg", ibw, 100); |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Ada | Ada | with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
procedure Bitwise is
subtype Byte is Unsigned_8;
package Byte_IO is new Ada.Text_Io.Modular_IO (Byte);
A : constant Byte := 2#00011110#;
B : constant Byte := 2#11110100#;
X : constant Byte := 128;
N : constant Natural := 1;
begin
Put ("A and B = "); Byte_IO.Put (Item => A and B, Base => 2); New_Line;
Put ("A or B = "); Byte_IO.Put (Item => A or B, Base => 2); New_Line;
Put ("A xor B = "); Byte_IO.Put (Item => A xor B, Base => 2); New_Line;
Put ("not A = "); Byte_IO.Put (Item => not A, Base => 2); New_Line;
New_Line (2);
Put_Line (Unsigned_8'Image (Shift_Left (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right_Arithmetic (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Left (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise; |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Kotlin | Kotlin | // Version 1.2.40
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import kotlin.math.abs
import java.io.File
import javax.imageio.ImageIO
class Point(var x: Int, var y: Int)
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) {
val dx = abs(x1 - x0)
val dy = abs(y1 - y0)
val sx = if (x0 < x1) 1 else -1
val sy = if (y0 < y1) 1 else -1
var xx = x0
var yy = y0
var e1 = (if (dx > dy) dx else -dy) / 2
var e2: Int
while (true) {
setPixel(xx, yy, c)
if (xx == x1 && yy == y1) break
e2 = e1
if (e2 > -dx) { e1 -= dy; xx += sx }
if (e2 < dy) { e1 += dx; yy += sy }
}
}
fun quadraticBezier(p1: Point, p2: Point, p3: Point, clr: Color, n: Int) {
val pts = List(n + 1) { Point(0, 0) }
for (i in 0..n) {
val t = i.toDouble() / n
val u = 1.0 - t
val a = u * u
val b = 2.0 * t * u
val c = t * t
pts[i].x = (a * p1.x + b * p2.x + c * p3.x).toInt()
pts[i].y = (a * p1.y + b * p2.y + c * p3.y).toInt()
setPixel(pts[i].x, pts[i].y, clr)
}
for (i in 0 until n) {
val j = i + 1
drawLine(pts[i].x, pts[i].y, pts[j].x, pts[j].y, clr)
}
}
}
fun main(args: Array<String>) {
val width = 320
val height = 320
val bbs = BasicBitmapStorage(width, height)
with (bbs) {
fill(Color.cyan)
val p1 = Point(10, 100)
val p2 = Point(250, 270)
val p3 = Point(150, 20)
quadraticBezier(p1, p2, p3, Color.black, 20)
val qbFile = File("quadratic_bezier.jpg")
ImageIO.write(image, "jpg", qbFile)
}
} |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #Forth | Forth | : circle { x y r color bmp -- }
1 r - 0 r 2* negate 0 r { f ddx ddy dx dy }
color x y r + bmp b!
color x y r - bmp b!
color x r + y bmp b!
color x r - y bmp b!
begin dx dy < while
f 0< 0= if
dy 1- to dy
ddy 2 + dup to ddy
f + to f
then
dx 1+ to dx
ddx 2 + dup to ddx
f 1+ + to f
color x dx + y dy + bmp b!
color x dx - y dy + bmp b!
color x dx + y dy - bmp b!
color x dx - y dy - bmp b!
color x dy + y dx + bmp b!
color x dy - y dx + bmp b!
color x dy + y dx - bmp b!
color x dy - y dx - bmp b!
repeat ;
12 12 bitmap value test
0 test bfill
6 6 5 blue test circle
test bshow cr |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #Fortran | Fortran | interface draw_circle
module procedure draw_circle_sc, draw_circle_rgb
end interface
private :: plot, draw_circle_toch |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
cubic bezier OF class image :=
( REF IMAGE picture,
POINT p1, p2, p3, p4,
PIXEL color,
UNION(INT, VOID) in n
)VOID:
BEGIN
INT n = (in n|(INT n):n|20); # default 20 #
[0:n]POINT points;
FOR i FROM LWB points TO UPB points DO
REAL t = i / n,
a = (1 - t)**3,
b = 3 * t * (1 - t)**2,
c = 3 * t**2 * (1 - t),
d = t**3;
x OF points [i] := ENTIER (0.5 + a * x OF p1 + b * x OF p2 + c * x OF p3 + d * x OF p4);
y OF points [i] := ENTIER (0.5 + a * y OF p1 + b * y OF p2 + c * y OF p3 + d * y OF p4)
OD;
FOR i FROM LWB points TO UPB points - 1 DO
(line OF class image)(picture, points (i), points (i + 1), color)
OD
END # cubic bezier #;
SKIP |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #BBC_BASIC | BBC BASIC | Width% = 200
Height% = 200
REM Set window size:
VDU 23,22,Width%;Height%;8,16,16,128
REM Draw cubic Bézier curve:
PROCbeziercubic(160,150, 10,120, 30,0, 150,50, 20, 0,0,0)
END
DEF PROCbeziercubic(x1,y1,x2,y2,x3,y3,x4,y4,n%,r%,g%,b%)
LOCAL i%, t, t1, a, b, c, d, p{()}
DIM p{(n%) x%,y%}
FOR i% = 0 TO n%
t = i% / n%
t1 = 1 - t
a = t1^3
b = 3 * t * t1^2
c = 3 * t^2 * t1
d = t^3
p{(i%)}.x% = INT(a * x1 + b * x2 + c * x3 + d * x4 + 0.5)
p{(i%)}.y% = INT(a * y1 + b * y2 + c * y3 + d * y4 + 0.5)
NEXT
FOR i% = 0 TO n%-1
PROCbresenham(p{(i%)}.x%,p{(i%)}.y%,p{(i%+1)}.x%,p{(i%+1)}.y%, \
\ r%,g%,b%)
NEXT
ENDPROC
DEF PROCbresenham(x1%,y1%,x2%,y2%,r%,g%,b%)
LOCAL dx%, dy%, sx%, sy%, e
dx% = ABS(x2% - x1%) : sx% = SGN(x2% - x1%)
dy% = ABS(y2% - y1%) : sy% = SGN(y2% - y1%)
IF dx% < dy% e = dx% / 2 ELSE e = dy% / 2
REPEAT
PROCsetpixel(x1%,y1%,r%,g%,b%)
IF x1% = x2% IF y1% = y2% EXIT REPEAT
IF dx% > dy% THEN
x1% += sx% : e -= dy% : IF e < 0 e += dx% : y1% += sy%
ELSE
y1% += sy% : e -= dx% : IF e < 0 e += dy% : x1% += sx%
ENDIF
UNTIL FALSE
ENDPROC
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/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
| #zkl | zkl | // stream of numBits sized ints to bytes, numBits<8
fcn toBytes(n,[(numBits,acc,bitsSoFar)]state){
acc=acc.shiftLeft(numBits) + n; bitsSoFar+=numBits;
reg r;
if(bitsSoFar>=8){
bitsSoFar-=8;
r=acc.shiftRight(bitsSoFar);
acc=acc.bitAnd((-1).shiftLeft(bitsSoFar).bitNot());
}
else r=Void.Skip; // need more bits to make a byte
state.clear(numBits,acc,bitsSoFar);
r
} |
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.)
| #Scheme | Scheme | (define (write-ppm image file)
(define (write-image image)
(define (write-row row)
(define (write-colour colour)
(if (not (null? colour))
(begin (write-char (integer->char (car colour)))
(write-colour (cdr colour)))))
(if (not (null? row))
(begin (write-colour (car row)) (write-row (cdr row)))))
(if (not (null? image))
(begin (write-row (car image)) (write-image (cdr image)))))
(with-output-to-file file
(lambda ()
(begin (display "P6")
(newline)
(display (length (car image)))
(display " ")
(display (length image))
(newline)
(display 255)
(newline)
(write-image image))))) |
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #Common_Lisp | Common Lisp |
;;;; This is a revised version, inspired by a throwaway script originally
;;;; published at http://deedbot.org/bundle-381528.txt by the same Adlai.
;;; package definition
(cl:defpackage :bitcoin-address-encoder
(:use :cl . #.(ql:quickload :ironclad))
(:shadowing-import-from :ironclad #:null)
(:import-from :ironclad #:simple-octet-vector))
(cl:in-package :bitcoin-address-encoder)
;;; secp256k1, as shown concisely in https://en.bitcoin.it/wiki/Secp256k1
;;; and officially defined by the SECG at http://www.secg.org/sec2-v2.pdf
(macrolet ((define-constants (&rest constants)
`(progn ,@(loop for (name value) on constants by #'cddr
collect `(defconstant ,name ,value)))))
(define-constants
;; these constants are only necessary for computing public keys
xg #x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
yg #x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
ng #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
;; this constant is necessary both for computation and validation
p #.`(- ,@(mapcar (lambda (n) (ash 1 n)) '(256 32 9 8 7 6 4 0)))
))
;;; operations within the field of positive integers modulo the prime p
(macrolet ((define-operations (&rest pairs)
`(progn ,@(loop for (op name) on pairs by #'cddr collect
`(defun ,name (x y) (mod (,op x y) p))))))
(define-operations + add - sub * mul))
;;; modular exponentiation by squaring, still in the same field
;;; THIS IS A VARIABLE-TIME ALGORITHM, BLIND REUSE IS INSECURE!
(defun pow (x n &optional (x^n 1)) ; (declare (notinline pow))
(do ((x x (mul x x)) (n n (ash n -1))) ((zerop n) x^n)
(when (oddp n) (setf x^n (mul x^n x)))))
;;; extended euclidean algorithm, still in the same field
;;; THIS IS A VARIABLE-TIME ALGORITHM, BLIND REUSE IS INSECURE!
(defun eea (a b &optional (x 0) (prevx 1) (y 1) (prevy 0))
(if (zerop b) (values prevx prevy)
(multiple-value-bind (q r) (floor a b)
(eea b r (sub prevx (mul q x)) x (sub prevy (mul q y)) y))))
;;; multiplicative inverse in the field of integers modulo the prime p
(defun inv (x) (nth-value 1 (eea p (mod x p))))
;;; operation, in the group of rational points over elliptic curve "SECP256K1"
;;; THIS IS A VARIABLE-TIME ALGORITHM, BLIND REUSE IS INSECURE!
(defun addp (xp yp xq yq) ; https://hyperelliptic.org/EFD/g1p/auto-shortw.html
(if (and xp yp xq yq) ; base case: avoid The Pothole At The End Of The Algebra
(macrolet ((ua (s r) `(let* ((s ,s) (x (sub (mul s s) ,r)))
(values x (sub 0 (add yp (mul s (sub x xp))))))))
(if (/= xp xq) (ua (mul (sub yp yq) (inv (- xp xq))) (add xp xq)) ; p+q
(if (zerop (add yp yq)) (values nil nil) ; p = -q, so p+q = infinity
(ua (mul (inv (* 2 yp)) (mul 3 (pow xp 2))) (mul 2 xp))))) ; 2*p
(if (and xp yp) (values xp yp) (values xq yq)))) ; pick the [in]finite one
;;; Scalar multiplication (by doubling)
;;; THIS IS A VARIABLE-TIME ALGORITHM, BLIND REUSE IS INSECURE!
(defun smulp (k xp yp)
(if (zerop k) (values nil nil)
(multiple-value-bind (xq yq) (addp xp yp xp yp)
(multiple-value-bind (xr yr) (smulp (ash k -1) xq yq)
(if (evenp k) (values xr yr) (addp xp yp xr yr))))))
;;; Tests if a point is on the curve
;;; THIS IS A VARIABLE-TIME ALGORITHM, BLIND REUSE IS INSECURE!
(defun e (x y) (= (mul y y) (add (pow x #o3) #o7)))
;;; "A horseshoe brings good luck even to those of little faith." - S. Nakamoto
(macrolet ((check-sanity (&rest checks)
`(progn ,@(loop for (test text) on checks by #'cddr
collect `(assert ,test () ,text)))))
(check-sanity (= 977 (sub (pow 2 256) (pow 2 32))) "mathematics has broken"
(e xg yg) "the generator isn't a rational point on the curve"
(not (smulp ng xg yg)) "the generator's order is incorrect"))
;;; dyslexia-friendly encoding, placed in public domain by Satoshi Nakamoto
(defun base58enc (bytes)
(loop with code = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
for x = (octets-to-integer bytes) then (floor x #10R58) until (zerop x)
collect (char code (mod x #10R58)) into out finally
(return (coerce (nreverse (append out (loop for b across bytes
while (zerop b) collect #\1)))
'string))))
;;; encodes arbitrary coordinates into a Pay-To-Pubkey-Hash address
(defun pubkey-to-p2pkh (x y)
;; ... ok, the previous comment was a lie; the following line verifies that
;; the coordinates correspond to a rational point on the curve, and gives a
;; few chances to correct typos in either of the coordinates interactively.
(assert (e x y) (x y) "The point (~D, ~D) is off the curve secp256k1." x y)
(labels ((digest (hashes bytes)
(reduce 'digest-sequence hashes :from-end t :initial-value bytes))
(sovcat (&rest things)
(apply 'concatenate 'simple-octet-vector things))
(checksum (octets)
(sovcat octets (subseq (digest '(sha256 sha256) octets) 0 4))))
(let ((point (sovcat '(4) (integer-to-octets x) (integer-to-octets y))))
(base58enc (checksum (sovcat '(0) (digest '(ripemd-160 sha256) point)))))))
|
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #BBC_BASIC | BBC BASIC | MODE 8
GCOL 15
CIRCLE FILL 640, 512, 500
GCOL 0
CIRCLE FILL 500, 600, 200
GCOL 3
PROCflood(600, 200, 15)
GCOL 4
PROCflood(600, 700, 0)
END
DEF PROCflood(X%, Y%, C%)
LOCAL L%, R%
IF POINT(X%,Y%) <> C% ENDPROC
L% = X%
R% = X%
WHILE POINT(L%-2,Y%) = C% : L% -= 2 : ENDWHILE
WHILE POINT(R%+2,Y%) = C% : R% += 2 : ENDWHILE
LINE L%,Y%,R%,Y%
FOR X% = L% TO R% STEP 2
PROCflood(X%, Y%+2, C%)
PROCflood(X%, Y%-2, C%)
NEXT
ENDPROC |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #C | C | /*
* RosettaCode: Bitmap/Flood fill, language C, dialects C89, C99, C11.
*
* This is an implementation of the recursive algorithm. For the sake of
* simplicity, instead of reading files as JPEG, PNG, etc., the program
* read and write Portable Bit Map (PBM) files in plain text format.
* Portable Bit Map files can also be read and written with GNU GIMP.
*
* The program is just an example, so the image size is limited to 2048x2048,
* the image can only be black and white, there is no run-time validation.
*
* Data is read from a standard input stream, the results are written to the
* standard output file.
*
* In order for this program to work properly it is necessary to allocate
* enough memory for the program stack. For example, in Microsoft Visual Studio,
* the option /stack:134217728 declares a 128MB stack instead of the default
* size of 1MB.
*/
#define _CRT_SECURE_NO_WARNINGS /* Unlock printf etc. in MSVC */
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 2048
#define BYTE unsigned char
static int width, height;
static BYTE bitmap[MAXSIZE][MAXSIZE];
static BYTE oldColor;
static BYTE newColor;
void floodFill(int i, int j)
{
if ( 0 <= i && i < height
&& 0 <= j && j < width
&& bitmap[i][j] == oldColor )
{
bitmap[i][j] = newColor;
floodFill(i-1,j);
floodFill(i+1,j);
floodFill(i,j-1);
floodFill(i,j+1);
}
}
/* *****************************************************************************
* Input/output routines.
*/
void skipLine(FILE* file)
{
while(!ferror(file) && !feof(file) && fgetc(file) != '\n')
;
}
void skipCommentLines(FILE* file)
{
int c;
int comment = '#';
while ((c = fgetc(file)) == comment)
skipLine(file);
ungetc(c,file);
}
readPortableBitMap(FILE* file)
{
int i,j;
skipLine(file);
skipCommentLines(file); fscanf(file,"%d",&width);
skipCommentLines(file); fscanf(file,"%d",&height);
skipCommentLines(file);
if ( width <= MAXSIZE && height <= MAXSIZE )
for ( i = 0; i < height; i++ )
for ( j = 0; j < width; j++ )
fscanf(file,"%1d",&(bitmap[i][j]));
else exit(EXIT_FAILURE);
}
void writePortableBitMap(FILE* file)
{
int i,j;
fprintf(file,"P1\n");
fprintf(file,"%d %d\n", width, height);
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < width; j++ )
fprintf(file,"%1d", bitmap[i][j]);
fprintf(file,"\n");
}
}
/* *****************************************************************************
* The main entry point.
*/
int main(void)
{
oldColor = 1;
newColor = oldColor ? 0 : 1;
readPortableBitMap(stdin);
floodFill(height/2,width/2);
writePortableBitMap(stdout);
return EXIT_SUCCESS;
} |
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
| #DWScript | DWScript | #t // <boolean> true
#f // <boolean> false |
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
| #Dyalect | Dyalect | #t // <boolean> true
#f // <boolean> false |
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
| #Dylan | Dylan | #t // <boolean> true
#f // <boolean> false |
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
| #TypeScript | TypeScript | function replace(input: string, key: number) : string {
return input.replace(/([a-z])/g,
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
).replace(/([A-Z])/g,
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 65) % 26 + 65));
}
// test
var str = 'The five boxing wizards jump quickly';
var encoded = replace(str, 3);
var decoded = replace(encoded, -3);
console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded); |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #Befunge | Befunge | >>::"}"9**\4+3%79*9*5-*79*9*5--+:5>>>06p:55+%68*+v
^_@#!`*84:+1<v*9"}"*+55,,,".",,,$$_^#!:-1g60/+55\<
>_06g:v>55+,^>/5+55+/48*::::,,,,%:1+.9,:06p48*\-0v
|p60-1<|<!p80:<N|Ev"northwest"0"North by west"0p8<
>:#,_>>>_08g1-^W|S>"-htroN"0"htron yb tsewhtroN"0v
#v"est-northwest"0"Northwest by west"0"Northwest"<
N>"W"0"htron yb tseW"0"tseW"0"htuos yb tseW"0"ts"v
#v0"Southwest"0"Southwest by west"0"West-southwe"<
S>"htuos yb tsewhtuoS"0"tsewhtuos-htuoS"0"tsew y"v
#v"h-southeast"0"South by east"0"South"0"South b"<
E>"tuoS"0"htuos yb tsaehtuoS"0"tsaehtuoS"0"tsae "v
#v"East by south"0"East-southeast"0"Southeast by"<
W>0"tsaE"0"htron yb tsaE"0"tsaehtron-tsaE"0"tsae"v
#v"rtheast by north"0"Northeast"0"Northeast by "<<
^>"oN"0"tsaehtron-htroN"0"tsae yb htroN"0"htroN"01 |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Phix | Phix | -- demo\rosetta\Bitmap_Histogram.exw (runnable version)
include ppm.e -- black, white, read_ppm(), write_ppm() (covers above requirements)
function to_bw(sequence image)
sequence hist = repeat(0,256)
for x=1 to length(image) do
for y=1 to length(image[x]) do
integer pixel = image[x][y] -- red,green,blue
sequence r_g_b = sq_and_bits(pixel,{#FF0000,#FF00,#FF})
integer {r,g,b} = sq_floor_div(r_g_b,{#010000,#0100,#01}),
lum = floor(0.2126*r + 0.7152*g + 0.0722*b)
image[x][y] = lum
hist[lum+1] += 1
end for
end for
integer lo = 1, hi = 256,
ltot = hist[lo],
rtot = hist[hi]
while lo!=hi do
if ltot<rtot then
lo += 1
ltot += hist[lo]
else
hi -= 1
rtot += hist[hi]
end if
end while
integer lum = lo
for i=1 to length(image) do
for j=1 to length(image[i]) do
image[i][j] = iff(image[i][j]<lum?black:white)
end for
end for
return image
end function
sequence img = read_ppm("Lena.ppm")
img = to_bw(img)
write_ppm("LenaBW.ppm",img) |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #PHP | PHP |
define('src_name', 'input.jpg'); // source image
define('dest_name', 'output.jpg'); // destination image
$img = imagecreatefromjpeg(src_name); // read image
if(empty($img)){
echo 'Image could not be loaded!';
exit;
}
$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);
$width = imagesx($img);
$height = imagesy($img);
$array_lum = array(); // for storage of luminosity of each pixel
$sum_lum = 0; // total sum of luminosity
$average_lum = 0; // average luminosity of whole image
for($x = 0; $x < $width; $x++){
for($y = 0; $y < $height; $y++){
// read pixel value
$color = imagecolorat($img, $x, $y);
$r = ($color >> 16) & 0xFF;
$g = ($color >> 8) & 0xFF;
$b = $color & 0xFF;
// save pixel luminosity in temporary array
$array_lum[$x][$y] = ($r + $g + $b);
// add pixel luminosity to sum
$sum_lum += $array_lum[$x][$y];
}
}
// calculate average luminosity
$average_lum = $sum_lum / ($width * $height);
for($x = 0; $x < $width; $x++){
for($y = 0; $y < $height; $y++){
// pixel is brighter than average -> set white
// else -> set black
if($array_lum[$x][$y] > $average_lum){
imagesetpixel($img, $x, $y, $white);
}
else{
imagesetpixel($img, $x, $y, $black);
}
}
}
// save black and white image to dest_name
imagejpeg($img, dest_name);
if(!file_exists(dest_name)){
echo 'Image not saved! Check permission!';
}
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Aikido | Aikido | function bitwise(a, b){
println("a AND b: " + (a & b))
println("a OR b: "+ (a | b))
println("a XOR b: "+ (a ^ b))
println("NOT a: " + ~a)
println("a << b: " + (a << b)) // left shift
println("a >> b: " + (a >> b)) // arithmetic right shift
println("a >>> b: " + (a >>> b)) // logical right shift
} |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Lua | Lua | Bitmap.quadraticbezier = function(self, x1, y1, x2, y2, x3, y3, nseg)
nseg = nseg or 10
local prevx, prevy, currx, curry
for i = 0, nseg do
local t = i / nseg
local a, b, c = (1-t)^2, 2*t*(1-t), t^2
prevx, prevy = currx, curry
currx = math.floor(a * x1 + b * x2 + c * x3 + 0.5)
curry = math.floor(a * y1 + b * y2 + c * y3 + 0.5)
if i > 0 then
self:line(prevx, prevy, currx, curry)
end
end
end
local bitmap = Bitmap(61,21)
bitmap:clear()
bitmap:quadraticbezier( 1,1, 30,37, 59,1 )
bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'}) |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | pts = {{0, 0}, {1, -1}, {2, 1}};
Graphics[{BSplineCurve[pts], Green, Line[pts], Red, Point[pts]}] |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #FreeBASIC | FreeBASIC | ' version 15-10-2016
' compile with: fbc -s gui
' Variant with Integer-Based Arithmetic from Wikipedia page:
' Midpoint circle algorithm
Sub circle_(x0 As Integer, y0 As Integer , radius As Integer, Col As Integer)
Dim As Integer x = radius
Dim As Integer y
' Decision criterion divided by 2 evaluated at x=r, y=0
Dim As Integer decisionOver2 = 1 - x
While(x >= y)
PSet(x0 + x, y0 + y), col
PSet(x0 - x, y0 + y), col
PSet(x0 + x, y0 - y), col
PSet(x0 - x, y0 - y), col
PSet(x0 + y, y0 + x), col
PSet(x0 - y, y0 + x), col
PSet(x0 + y, y0 - x), col
PSet(x0 - y, y0 - x), col
y = y +1
If decisionOver2 <= 0 Then
decisionOver2 += y * 2 +1 ' Change in decision criterion for y -> y +1
Else
x = x -1
decisionOver2 += (y - x) * 2 +1 ' Change for y -> y +1, x -> x -1
End If
Wend
End Sub
' ------=< MAIN >=------
ScreenRes 600, 600, 32
Dim As Integer w, h, depth
Randomize Timer
ScreenInfo w, h
For i As Integer = 1 To 10
circle_(Rnd * w, Rnd * h , Rnd * 200 , Int(Rnd *&hFFFFFF))
Next
'save screen to BMP file
BSave "Name.BMP", 0
' empty keyboard buffer
While Inkey <> "" : Wend
WindowTitle "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #Go | Go | package raster
// Circle plots a circle with center x, y and radius r.
// Limiting behavior:
// r < 0 plots no pixels.
// r = 0 plots a single pixel at x, y.
// r = 1 plots four pixels in a diamond shape around the center pixel at x, y.
func (b *Bitmap) Circle(x, y, r int, p Pixel) {
if r < 0 {
return
}
// Bresenham algorithm
x1, y1, err := -r, 0, 2-2*r
for {
b.SetPx(x-x1, y+y1, p)
b.SetPx(x-y1, y-x1, p)
b.SetPx(x+x1, y-y1, p)
b.SetPx(x+y1, y+x1, p)
r = err
if r > x1 {
x1++
err += x1*2 + 1
}
if r <= y1 {
y1++
err += y1*2 + 1
}
if x1 >= 0 {
break
}
}
}
func (b *Bitmap) CircleRgb(x, y, r int, c Rgb) {
b.Circle(x, y, r, c.Pixel())
} |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #C | C | void cubic_bezier(
image img,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2,
unsigned int x3, unsigned int y3,
unsigned int x4, unsigned int y4,
color_component r,
color_component g,
color_component b ); |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #D | D | import grayscale_image, bitmap_bresenhams_line_algorithm;
struct Pt { int x, y; } // Signed.
void cubicBezier(size_t nSegments=20, Color)
(Image!Color im,
in Pt p1, in Pt p2, in Pt p3, in Pt p4,
in Color color)
pure nothrow @nogc if (nSegments > 0) {
Pt[nSegments + 1] points = void;
foreach (immutable i, ref p; points) {
immutable double t = i / double(nSegments),
a = (1.0 - t) ^^ 3,
b = 3.0 * t * (1.0 - t) ^^ 2,
c = 3.0 * t ^^ 2 * (1.0 - t),
d = t ^^ 3;
alias T = typeof(Pt.x);
p = Pt(cast(T)(a * p1.x + b * p2.x + c * p3.x + d * p4.x),
cast(T)(a * p1.y + b * p2.y + c * p3.y + d * p4.y));
}
foreach (immutable i, immutable p; points[0 .. $ - 1])
im.drawLine(p.x, p.y, points[i + 1].x, points[i + 1].y, color);
}
void main() {
auto im = new Image!Gray(17, 17);
im.clear(Gray.white);
im.cubicBezier(Pt(16, 1), Pt(1, 4), Pt(3, 16), Pt(15, 11),
Gray.black);
im.textualShow();
} |
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.)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "color.s7i";
const proc: writePPM (in string: fileName, in PRIMITIVE_WINDOW: aWindow) is func
local
var file: ppmFile is STD_NULL;
var integer: x is 0;
var integer: y is 0;
var color: pixColor is black;
begin
ppmFile := open(fileName, "w");
if ppmFile <> STD_NULL then
writeln(ppmFile, "P6");
writeln(ppmFile, width(aWindow) <& " " <& height(aWindow));
writeln(ppmFile, "255");
for y range 0 to pred(height(aWindow)) do
for x range 0 to pred(width(aWindow)) do
pixColor := getPixelColor(aWindow, x, y);
write(ppmFile, str(chr(pixColor.redLight)) <& chr(pixColor.greenLight) <& chr(pixColor.blueLight));
end for;
end for;
close(ppmFile);
end if;
end func; |
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.)
| #Sidef | Sidef | subset Int < Number {|n| n.is_int }
subset UInt < Int {|n| n >= 0 }
subset UInt8 < Int {|n| n ~~ ^256 }
struct Pixel {
R < UInt8,
G < UInt8,
B < UInt8
}
class Bitmap(width < UInt, height < UInt) {
has data = []
method fill(Pixel p) {
data = (width*height -> of { Pixel(p.R, p.G, p.B) })
}
method setpixel(i < UInt, j < UInt, Pixel p) {
subset WidthLimit < UInt { |n| n ~~ ^width }
subset HeightLimit < UInt { |n| n ~~ ^height }
func (w < WidthLimit, h < HeightLimit) {
data[w*height + h] = p
}(i, j)
}
method p6 {
<<-EOT + data.map {|p| [p.R, p.G, p.B].pack('C3') }.join
P6
#{width} #{height}
255
EOT
}
}
var b = Bitmap(width: 125, height: 125)
for i,j in (^b.height ~X ^b.width) {
b.setpixel(i, j, Pixel(2*i, 2*j, 255 - 2*i))
}
%f"palette.ppm".write(b.p6, :raw) |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #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 chardisplay()
V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’))
txt = txt.map(row -> ‘|’row‘|’)
txt.insert(0, ‘+’(‘-’ * .width)‘+’)
txt.append(‘+’(‘-’ * .width)‘+’)
print(reversed(txt).join("\n"))
F set(x, y, colour = black)
.map[y][x] = colour
F get(x, y)
R .map[y][x]
F line(x0, y0, x1, y1)
‘Bresenham's line algorithm’
V dx = abs(x1 - x0)
V dy = abs(y1 - y0)
V (x, y) = (x0, y0)
V sx = I x0 > x1 {-1} E 1
V sy = I y0 > y1 {-1} E 1
I dx > dy
V err = dx / 2.0
L x != x1
.set(x, y)
err -= dy
I err < 0
y += sy
err += dx
x += sx
E
V err = dy / 2.0
L y != y1
.set(x, y)
err -= dx
I err < 0
x += sx
err += dy
y += sy
.set(x, y)
V bitmap = Bitmap(17, 17)
L(x0, y0, x1, y1) ((1, 8, 8, 16), (8, 16, 16, 8), (16, 8, 8, 1), (8, 1, 1, 8))
bitmap.line(x0, y0, x1, y1)
bitmap.chardisplay() |
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #D | D | import std.stdio, std.algorithm, std.digest.ripemd, sha_256_2;
// A Bitcoin public point.
struct PPoint { ubyte[32] x, y; }
private enum bitcoinVersion = 0;
private enum RIPEMD160_digest_len = typeof("".ripemd160Of).length;
private alias sha = SHA256.digest;
alias Address = ubyte[1 + 4 + RIPEMD160_digest_len];
/// Returns a base 58 encoded bitcoin address corresponding to the receiver.
char[] toBase58(ref Address a) pure nothrow @safe {
static immutable symbols = "123456789" ~
"ABCDEFGHJKLMNPQRSTUVWXYZ" ~
"abcdefghijkmnopqrstuvwxyz";
static assert(symbols.length == 58);
auto result = new typeof(return)(34);
foreach_reverse (ref ri; result) {
uint c = 0;
foreach (ref ai; a) {
immutable d = (c % symbols.length) * 256 + ai;
ai = d / symbols.length;
c = d;
}
ri = symbols[c % symbols.length];
}
size_t i = 1;
for (; i < result.length && result[i] == '1'; i++) {}
return result[i - 1 .. $];
}
char[] bitcoinEncode(in ref PPoint p) pure nothrow {
ubyte[typeof(PPoint.x).length + typeof(PPoint.y).length + 1] s;
s[0] = 4;
s[1 .. 1 + p.x.length] = p.x[];
s[1 + p.x.length .. $] = p.y[];
Address rmd;
rmd[0] = bitcoinVersion;
rmd[1 .. RIPEMD160_digest_len + 1] = s.sha.ripemd160Of;
rmd[$-4 .. $] = rmd[0 .. RIPEMD160_digest_len + 1].sha.sha[0 .. 4];
return rmd.toBase58;
}
void main() {
PPoint p = {
cast(typeof(PPoint.x))
x"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
cast(typeof(PPoint.y))
x"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"};
p.bitcoinEncode.writeln;
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
namespace FloodFill
{
class Program
{
private static bool ColorMatch(Color a, Color b)
{
return (a.ToArgb() & 0xffffff) == (b.ToArgb() & 0xffffff);
}
static void FloodFill(Bitmap bmp, Point pt, Color targetColor, Color replacementColor)
{
Queue<Point> q = new Queue<Point>();
q.Enqueue(pt);
while (q.Count > 0)
{
Point n = q.Dequeue();
if (!ColorMatch(bmp.GetPixel(n.X, n.Y),targetColor))
continue;
Point w = n, e = new Point(n.X + 1, n.Y);
while ((w.X >= 0) && ColorMatch(bmp.GetPixel(w.X, w.Y),targetColor))
{
bmp.SetPixel(w.X, w.Y, replacementColor);
if ((w.Y > 0) && ColorMatch(bmp.GetPixel(w.X, w.Y - 1),targetColor))
q.Enqueue(new Point(w.X, w.Y - 1));
if ((w.Y < bmp.Height - 1) && ColorMatch(bmp.GetPixel(w.X, w.Y + 1),targetColor))
q.Enqueue(new Point(w.X, w.Y + 1));
w.X--;
}
while ((e.X <= bmp.Width - 1) && ColorMatch(bmp.GetPixel(e.X, e.Y),targetColor))
{
bmp.SetPixel(e.X, e.Y, replacementColor);
if ((e.Y > 0) && ColorMatch(bmp.GetPixel(e.X, e.Y - 1), targetColor))
q.Enqueue(new Point(e.X, e.Y - 1));
if ((e.Y < bmp.Height - 1) && ColorMatch(bmp.GetPixel(e.X, e.Y + 1), targetColor))
q.Enqueue(new Point(e.X, e.Y + 1));
e.X++;
}
}
}
static void Main(string[] args)
{
Bitmap bmp = new Bitmap("Unfilledcirc.bmp");
FloodFill(bmp, new Point(200, 200), Color.White, Color.Red);
FloodFill(bmp, new Point(100, 100), Color.Black, Color.Blue);
bmp.Save("Filledcirc.bmp");
}
}
}
|
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | ? if (true) { "a" } else { "b" }
# value: "a"
? if (false) { "a" } else { "b" }
# value: "b"
? if (90) { "a" } else { "b" }
# problem: the int 90 doesn't coerce to a boolean |
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
| #E | E | ? if (true) { "a" } else { "b" }
# value: "a"
? if (false) { "a" } else { "b" }
# value: "b"
? if (90) { "a" } else { "b" }
# problem: the int 90 doesn't coerce to a boolean |
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
| #UNIX_Shell | UNIX Shell | caesar() {
local OPTIND
local encrypt n=0
while getopts :edn: option; do
case $option in
e) encrypt=true ;;
d) encrypt=false ;;
n) n=$OPTARG ;;
:) echo "error: missing argument for -$OPTARG" >&2
return 1 ;;
?) echo "error: unknown option -$OPTARG" >&2
return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ -z $encrypt ]]; then
echo "error: specify one of -e or -d" >&2
return 1
fi
local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
local lower=abcdefghijklmnopqrstuvwxyz
if $encrypt; then
tr "$upper$lower" "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" <<< "$1"
else
tr "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" "$upper$lower" <<< "$1"
fi
}
tr() {
local -A charmap
local i trans line char
for ((i=0; i<${#1}; i++)); do
charmap[${1:i:1}]=${2:i:1}
done
while IFS= read -r line; do
trans=""
for ((i=0; i<${#line}; i++)); do
char=${line:i:1}
if [[ -n ${charmap[$char]} ]]; then
trans+=${charmap[$char]}
else
trans+=$char
fi
done
echo "$trans"
done
}
txt="The five boxing wizards jump quickly."
enc=$(caesar -e -n 5 "$txt")
dec=$(caesar -d -n 5 "$enc")
echo "original: $txt"
echo "encrypted: $enc"
echo "decrypted: $dec" |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #C | C | #include <stdio.h>
int main()
{
int i, j;
double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,
84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88,
168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12,
253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5,
354.37, 354.38 };
const char * names = "North "
"North by east "
"North-northeast "
"Northeast by north "
"Northeast "
"Northeast by east "
"East-northeast "
"East by north "
"East "
"East by south "
"East-southeast "
"Southeast by east "
"Southeast "
"Southeast by south "
"South-southeast "
"South by east "
"South "
"South by west "
"South-southwest "
"Southwest by south "
"Southwest "
"Southwest by west "
"West-southwest "
"West by south "
"West "
"West by north "
"West-northwest "
"Northwest by west "
"Northwest "
"Northwest by north "
"North-northwest "
"North by west "
"North ";
for (i = 0; i < 33; i++) {
j = .5 + degrees[i] * 32 / 360;
printf("%2d %.22s %6.2f\n", (j % 32) + 1, names + (j % 32) * 22,
degrees[i]);
}
return 0;
} |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #PicoLisp | PicoLisp | (de histogram (Pgm)
(let H (need 256 0)
(for L Pgm
(for G L
(inc (nth H (inc G))) ) )
H ) ) |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #PureBasic | PureBasic | Procedure getHistogram(image, Array histogram(1))
Protected w = ImageWidth(image) - 1
Protected h = ImageHeight(image) - 1
Dim histogram(255) ;output
StartDrawing(ImageOutput(image))
For x = 0 To w
For y = 0 To h
lum = Red(Point(x, y)) ;the Green or Blue color components could be used also
histogram(lum) + 1
Next
Next
StopDrawing()
EndProcedure
Procedure median(Array histogram(1))
Protected low, high = 255, left, right
While low <> high
If left < right
low + 1
left + histogram(low)
Else
high - 1
right + histogram(high)
EndIf
Wend
ProcedureReturn low
EndProcedure
Procedure blackAndWhite(image, median)
Protected w = ImageWidth(image) - 1
Protected h = ImageHeight(image) - 1
CallDebugger
StartDrawing(ImageOutput(image))
For x = 0 To w
For y = 0 To h
If Red(Point(x, y)) < median ;the Green or Blue color components could be used also
Plot(x, y, $000000) ;black
Else
Plot(x, y, $FFFFFF) ;white
EndIf
Next
Next
StopDrawing()
EndProcedure
Define sourceFile.s, outputFile.s, image = 3, m
Dim histogram(255)
sourceFile = OpenFileRequester("Select source image file", "*.ppm", "PPM image (*.ppm)|PPM", 0)
If sourceFile And LCase(GetExtensionPart(sourceFile)) = "ppm"
LoadImagePPM(image, sourceFile)
ImageGrayout(image)
getHistogram(image,histogram())
m = median(histogram())
blackAndWhite(image, m)
outputFile = Left(sourceFile, Len(sourceFile) - Len(GetExtensionPart(sourceFile))) + "_bw." + GetExtensionPart(sourceFile)
SaveImageAsPPM(image, outputFile, 1)
EndIf |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #ALGOL_68 | ALGOL 68 | main:(
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here #
OP SLC = (BITS b, INT rotate) BITS: b SHL rotate OR b SHR ( bits width - rotate );
OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR b SHL ( bits width - rotate );
# SRC and SRL are non-standard, but versions are built in to ALGOL 68R's standard prelude #
PRIO XOR = 2;
OP XOR = (BITS p, q) BITS: p AND NOT q OR NOT p AND q;
# XOR is non-standard, but a version is built in to ALGOL 68G's standard prelude #
# ALGOL 68 has 5 different ways of representing a BINary BITS - Bases: 2, 4, 8, 16 and flip/flop #
FORMAT b5 = $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d," "gl$;
OP BBBBB = (BITS b)[]BITS: (b,b,b,b,b);
PROC bitwise = (BITS a, BITS b, INT shift)VOID:
(
printf((
$" bits shorths: "gxgl$, bits shorths, "1 plus the number of extra SHORT BITS types",
$" bits lengths: "gxgl$, bits lengths, "1 plus the number of extra LONG BITS types",
$" max bits: "gl$, max bits,
$" long max bits: "gl$, long max bits,
$" long long max bits: "gl$, long long max bits,
$" bits width: "gxgl$, bits width, "The number of CHAR required to display BITS",
$" long bits width: "gxgl$, long bits width, "The number of CHAR required to display LONG BITS",
$" long long bits width: "gxgl$, long long bits width, "The number of CHAR required to display LONG LONG BITS",
$" bytes shorths: "gxgl$, bytes shorths, "1 plus the number of extra SHORT BYTES types",
$" bytes lengths: "gxgl$, bits lengths, "1 plus the number of extra LONG BYTES types",
$" bytes width: "gxgl$, bytes width, "The number of CHAR required to display BYTES",
$" long bytes width: "gxgl$, long bytes width, "The number of CHAR required to display LONG BYTES"
));
printf(($" a: "f(b5)$, BBBBB a));
printf(($" b: "f(b5)$, BBBBB b));
printf(($" a AND b: "f(b5)$, BBBBB(a AND b)));
printf(($" a OR b: "f(b5)$, BBBBB(a OR b)));
printf(($" a XOR b: "f(b5)$, BBBBB(a XOR b)));
printf(($" NOT b: "f(b5)$, BBBBB NOT a));
printf(($" a SHL "d": "f(b5)$, shift, BBBBB(a SHL shift)));
printf(($" a SHR "d": "f(b5)$, shift, BBBBB(a SHR shift)));
printf(($" a SLC "d": "f(b5)$, shift, BBBBB(a SLC shift)));
printf(($" a SRC "d": "f(b5)$, shift, BBBBB(a SRC shift)))
COMMENT with original ALGOL 68 character set;
printf(($" a AND b: "f(b5)$, BBBBB(a ∧ b)));
printf(($" a OR b: "f(b5)$, BBBBB(a ∨ b)));
printf(($" NOT b: "f(b5)$, BBBBB ¬ a));
printf(($" a SHL "d": "f(b5)$, shift, BBBBB(a ↑ shift)));
printf(($" a SHR "d": "f(b5)$, shift, BBBBB(a ↓ shift)));
Also:
printf(($" a AND b: "f(b5)$, BBBBB(a /\ b)));
printf(($" a OR b: "f(b5)$, BBBBB(a \/ b)));
COMMENT
);
bitwise(BIN 255, BIN 170, 5)
# or using alternate representations for 255 and 170 in BITS #
CO
bitwise(2r11111111,2r10101010,5);
bitwise(4r3333,4r2222,5);
bitwise(8r377,8r252,5);
bitwise(16rff,16raa,5)
END CO
) |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #MATLAB | MATLAB |
function bezierQuad(obj,pixel_0,pixel_1,pixel_2,color,varargin)
if( isempty(varargin) )
resolution = 20;
else
resolution = varargin{1};
end
%Calculate time axis
time = (0:1/resolution:1)';
timeMinus = 1-time;
%The formula for the curve is expanded for clarity, the lack of
%loops is because its calculation has been vectorized
curve = (timeMinus.^2)*pixel_0; %First term of polynomial
curve = curve + (2.*time.*timeMinus)*pixel_1; %second term of polynomial
curve = curve + (time.^2)*pixel_2; %third term of polynomial
curve = round(curve); %round each of the points to the nearest integer
%connect each of the points in the curve with a line using the
%Bresenham Line algorithm
for i = (1:length(curve)-1)
obj.bresenhamLine(curve(i,:),curve(i+1,:),color);
end
assignin('caller',inputname(1),obj); %saves the changes to the object
end
|
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Nim | Nim | import bitmap
import bresenham
import lenientops
proc drawQuadraticBezier*(
image: Image; pt1, pt2, pt3: Point; color: Color; nseg: Positive = 20) =
var points = newSeq[Point](nseg + 1)
for i in 0..nseg:
let t = i / nseg
let a = (1 - t) * (1 - t)
let b = 2 * t * (1 - t)
let c = t * t
points[i] = (x: (a * pt1.x + b * pt2.x + c * pt3.x).toInt,
y: (a * pt1.y + b * pt2.y + c * pt3.y).toInt)
for i in 1..points.high:
image.drawLine(points[i - 1], points[i], color)
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
var img = newImage(16, 12)
img.fill(White)
img.drawQuadraticBezier((1, 7), (7, 12), (14, 1), Black)
img.print |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #OCaml | OCaml | let quad_bezier ~img ~color
~p1:(_x1, _y1)
~p2:(_x2, _y2)
~p3:(_x3, _y3) =
let (x1, y1, x2, y2, x3, y3) =
(float _x1, float _y1, float _x2, float _y2, float _x3, float _y3)
in
let bz t =
let a = (1.0 -. t) ** 2.0
and b = 2.0 *. t *. (1.0 -. t)
and c = t ** 2.0
in
let x = a *. x1 +. b *. x2 +. c *. x3
and y = a *. y1 +. b *. y2 +. c *. y3
in
(int_of_float x, int_of_float y)
in
let rec loop _t acc =
if _t > 20 then acc else
begin
let t = (float _t) /. 20.0 in
let x, y = bz t in
loop (succ _t) ((x,y)::acc)
end
in
let pts = loop 0 [] in
(*
(* draw only points *)
List.iter (fun (x, y) -> put_pixel img color x y) pts;
*)
(* draw segments *)
let line = draw_line ~img ~color in
let by_pair li f =
ignore (List.fold_left (fun prev x -> f prev x; x) (List.hd li) (List.tl li))
in
by_pair pts (fun p0 p1 -> line ~p0 ~p1);
;; |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #Haskell | Haskell | module Circle where
import Data.List
type Point = (Int, Int)
-- Takes the center of the circle and radius, and returns the circle points
generateCirclePoints :: Point -> Int -> [Point]
generateCirclePoints (x0, y0) radius
-- Four initial points, plus the generated points
= (x0, y0 + radius) : (x0, y0 - radius) : (x0 + radius, y0) : (x0 - radius, y0) : points
where
-- Creates the (x, y) octet offsets, then maps them to absolute points in all octets.
points = concatMap generatePoints $ unfoldr step initialValues
generatePoints (x, y)
= [(xop x0 x', yop y0 y') | (x', y') <- [(x, y), (y, x)], xop <- [(+), (-)], yop <- [(+), (-)]]
-- The initial values for the loop
initialValues = (1 - radius, 1, (-2) * radius, 0, radius)
-- One step of the loop. The loop itself stops at Nothing.
step (f, ddf_x, ddf_y, x, y) | x >= y = Nothing
| otherwise = Just ((x', y'), (f', ddf_x', ddf_y', x', y'))
where
(f', ddf_y', y') | f >= 0 = (f + ddf_y' + ddf_x', ddf_y + 2, y - 1)
| otherwise = (f + ddf_x, ddf_y, y)
ddf_x' = ddf_x + 2
x' = x + 1
|
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #F.23 | F# |
/// Uses Vector<float> from Microsoft.FSharp.Math (in F# PowerPack)
module CubicBezier
/// Create bezier curve from p1 to p4, using the control points p2, p3
/// Returns the requested number of segments
let cubic_bezier (p1:vector) (p2:vector) (p3:vector) (p4:vector) segments =
[0 .. segments - 1]
|> List.map(fun i ->
let t = float i / float segments
let a = (1. - t) ** 3.
let b = 3. * t * ((1. - t) ** 2.)
let c = 3. * (t ** 2.) * (1. - t)
let d = t ** 3.
let x = a * p1.[0] + b * p2.[0] + c * p3.[0] + d * p4.[0]
let y = a * p1.[1] + b * p2.[1] + c * p3.[1] + d * p4.[1]
vector [x; y])
|
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #Factor | Factor | USING: arrays kernel locals math math.functions
rosettacode.raster.storage sequences ;
IN: rosettacode.raster.line
! this gives a function
:: (cubic-bezier) ( P0 P1 P2 P3 -- bezier )
[ :> x
1 x - 3 ^ P0 n*v
1 x - sq 3 * x * P1 n*v
1 x - 3 * x sq * P2 n*v
x 3 ^ P3 n*v
v+ v+ v+ ] ; inline
! gives an interval of x from 0 to 1 to map the bezier function
: t-interval ( x -- interval )
[ iota ] keep 1 - [ / ] curry map ;
! turns a list of points into the list of lines between them
: points-to-lines ( seq -- seq )
dup rest [ 2array ] 2map ;
: draw-lines ( {R,G,B} points image -- )
[ [ first2 ] dip draw-line ] curry with each ;
:: bezier-lines ( {R,G,B} P0 P1 P2 P3 image -- )
! 100 is an arbitrary value.. could be given as a parameter..
100 t-interval P0 P1 P2 P3 (cubic-bezier) map
points-to-lines
{R,G,B} swap image draw-lines ; |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #FBSL | FBSL | #DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_CLOSE 16
FBSLSETTEXT(ME, "Bezier Cubic")
FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color
DRAWWIDTH(5) ' Adjust point size
FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments
RESIZE(ME, 0, 0, 235, 235)
CENTER(ME)
SHOW(ME)
DIM Height AS INTEGER
FBSL.GETCLIENTRECT(ME, 0, 0, 0, Height)
BEGIN EVENTS
SELECT CASE CBMSG
CASE WM_LBUTTONDOWN: BezierCube(160, 150, 10, 120, 30, 0, 150, 50, 20) ' Draw
CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up
END SELECT
END EVENTS
SUB BezierCube(x1, y1, x2, y2, x3, y3, x4, y4, n)
TYPE POINTAPI
x AS INTEGER
y AS INTEGER
END TYPE
DIM t, t1, a, b, c, d, p[n] AS POINTAPI
FOR DIM i = 0 TO n
t = i / n: t1 = 1 - t
a = t1 ^ 3
b = 3 * t * t1 ^ 2
c = 3 * t ^ 2 * t1
d = t ^ 3
p[i].x = a * x1 + b * x2 + c * x3 + d * x4 + 0.5
p[i].y = Height - (a * y1 + b * y2 + c * y3 + d * y4 + 0.5)
NEXT
FOR i = 0 TO n - 1
Bresenham(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y)
NEXT
SUB Bresenham(x0, y0, x1, y1)
DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1)
DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1)
DIM tmp, er = IIF(dx > dy, dx, -dy) / 2
WHILE NOT (x0 = x1 ANDALSO y0 = y1)
PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order
tmp = er
IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF
IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF
WEND
END SUB
END SUB |
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.)
| #Stata | Stata | mata
void writeppm(name, r, g, b) {
n = rows(r)
p = cols(r)
f = fopen(name, "w")
fput(f, "P3")
fput(f, strofreal(p) + " " + strofreal(n) + " 255")
for (i = 1; i <= n; i++) {
for (j = 1; j <= p; j++) {
fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j]))
}
}
fclose(f)
}
r = J(1, 6, (0::5) * 51)
g = J(6, 1, (0..5) * 51)
b = J(6, 6, 255)
writeppm("image.ppm", r, g, b)
end |
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.)
| #Tcl | Tcl | package require Tk
proc output_ppm {image filename} {
$image write $filename -format ppm
}
set img [newImage 150 150]
fill $img red
setPixel $img green 40 40
output_ppm $img filename.ppm
# check the file format:
set fh [open filename.ppm]
puts [gets $fh] ;# ==> P6
puts [gets $fh] ;# ==> 150 150
puts [gets $fh] ;# ==> 255
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;# ==> 255 \n 0 \n 0 \n
close $fh |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #360_Assembly | 360 Assembly | * Bitmap/Bresenham's line algorithm - 13/05/2019
BRESENH CSECT
USING BRESENH,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,DATAXY @dataxy
LA R8,1 p=1
DO WHILE=(C,R8,LE,=A(POINTS)) do p=1 to points
L R6,0(R10) x=dataxy((p-1)*2+1)
L R7,4(R10) y=dataxy((p-1)*2+2)
IF C,R8,EQ,=F'1' THEN if p=1 then
ST R6,MINX minx=x
ST R6,MAXX maxx=x
ST R7,MINY miny=y
ST R7,MAXY maxy=y
ENDIF , endif
IF C,R6,LT,MINX THEN if x<minx then
ST R6,MINX minx=x
ENDIF , endif
IF C,R6,GT,MAXX THEN if x>maxx then
ST R6,MAXX maxx=x
ENDIF , endif
IF C,R7,LT,MINY THEN if y<miny then
ST R7,MINY miny=y
ENDIF , endif
IF C,R7,GT,MAXY THEN if y>maxy then
ST R7,MAXY maxy=y
ENDIF , endif
LA R10,8(R10) @dataxy+=8
LA R8,1(R8) p++
ENDDO , enddo p
L R1,MINX minx
S R1,=A(BORDER*2) -border*2
ST R1,MINX minx=minx-border*2
L R1,MAXX maxx
A R1,=A(BORDER*2) +border*2
ST R1,MAXX maxx=maxx+border*2
L R1,MINY miny
S R1,=A(BORDER) -border
ST R1,MINY miny=miny-border
L R1,MAXY maxy
A R1,=A(BORDER) +border
ST R1,MAXY maxy=maxy+border
L R1,MINX minx
LCR R1,R1 -
A R1,=F'1' +1
ST R1,OX ox=-minx+1
L R1,MINY miny
LCR R1,R1 -
A R1,=F'1' +1
ST R1,OY oy=-miny+1
LA R1,HMAPX hbound(map,1)
S R1,OX wx=hbound(map,1)-ox
IF C,R1,LT,MAXX THEN if maxx>wx then
ST R1,MAXX maxx=wx
ENDIF , endif
LA R1,HMAPY hbound(map,2)
S R1,OY wy=hbound(map,2)-oy
IF C,R1,LT,MAXY THEN if maxy>wy then
ST R1,MAXY maxy=wy
ENDIF , endif
L R6,MINX x=minx
DO WHILE=(C,R6,LE,MAXX) do x=minx to maxx
L R1,OY oy
BCTR R1,0 1
MH R1,=AL2(HMAPX) dim(x)
AR R1,R6 x
A R1,OX ox
LA R1,MAP-1(R1) map(0+oy,x+ox)
MVC 0(1,R1),=C'-' map(0+oy,x+ox)='-'
A R6,=F'1' x++
ENDDO , enddo x
L R7,MINY y=miny
DO WHILE=(C,R7,LE,MAXY) do y=miny to maxy
LR R1,R7 y
A R1,OY +oy
BCTR R1,0 -1
MH R1,=AL2(HMAPX) *dim(x)
A R1,OX +ox
LA R1,MAP-1(R1) @map(y+oy,0+ox)
MVC 0(1,R1),=C'|' map(y+oy,0+ox)='|'
A R7,=F'1' y++
ENDDO , enddo y
L R1,OY +oy
BCTR R1,0 -1
MH R1,=AL2(HMAPX) *dim(x)
A R1,OX +ox
LA R1,MAP-1(R1) @map(0+oy,0+ox)
MVC 0(1,R1),=C'+' map(0+oy,0+ox)='+'
LA R10,POINTS points
BCTR R10,0 pn=points-1
LA R9,DATAXY @dataxy
LA R8,1 p=1
DO WHILE=(CR,R8,LE,R10) do p=1 to points-1
L R6,0(R9) x=dataxy((p-1)*2+1)
L R7,4(R9) y=dataxy((p-1)*2+2)
L R4,8(R9) xf=dataxy(p*2+1)
L R5,12(R9) yf=dataxy(p*2+2)
LR R2,R4 xf
SR R2,R6 -x
LPR R2,R2 abs()
ST R2,DX dx=abs(xf-x)
LR R2,R5 xf
SR R2,R7 -y
LPR R2,R2 abs()
ST R2,DY dy=abs(yf-y)
IF CR,R6,LT,R4 THEN if x<xf then
MVC SX,=F'1' sx=+1
ELSE , else
MVC SX,=F'-1' sx=-1
ENDIF , endif
IF CR,R7,LT,R5 THEN if y<yf then
MVC SY,=F'1' sy=+1
ELSE , else
MVC SY,=F'-1' sy=-1
ENDIF , endif
L R2,DX dx
S R2,DY -dy
ST R2,ERR err=dx-dy
LOOP EQU * loop forever
LR R1,R7 y
A R1,OY +oy
BCTR R1,0 -1
MH R1,=AL2(HMAPX) *dim(x)
AR R1,R6 +x
A R1,OX +ox
LA R1,MAP-1(R1) @map(y+oy,x+ox)
MVC 0(1,R1),=C'X' map(y+oy,x+ox)='X'
CR R6,R4 if x=xf
BNE STAYDO ~
CR R7,R5 if y=yf
BE EXITLOOP if x=xf and y=yf then leave loop
STAYDO L R0,ERR err
A R0,ERR err+err
ST R0,ERR2 err2=err+err
L R0,DY dy
LCR R0,R0 -dy
IF C,R0,LT,ERR2 THEN if err2>-dy then
A R0,ERR -dy+err
ST R0,ERR err=err-dy
A R6,SX x=x+sx
ENDIF , endif
L R0,DX dx
IF C,R0,GT,ERR2 THEN if err2<dx then
L R0,ERR err
A R0,DX +dx
ST R0,ERR err=err+dx
A R7,SY y=y+sy
ENDIF , endif
B LOOP endloop
EXITLOOP LA R9,8(R9) @dataxy+=2
LA R8,1(R8) p++
ENDDO , enddo p
LA R9,MAP+(HMAPX*HMAPY)-HMAPX @map
L R7,MAXY y=maxy
DO WHILE=(C,R7,GE,MINY) do y=maxy to miny by -1
MVC PG(HMAPX),0(R9) output map(x,*)
XPRNT PG,L'PG print buffer
S R9,=A(HMAPX) @pg
S R7,=F'1' y--
ENDDO , enddo y
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
BORDER EQU 2 border size
POINTS EQU (MAP-DATAXY)/L'DATAXY/2
HMAPX EQU 24 dim(map,1)
HMAPY EQU 20 dim(map,2)
DATAXY DC F'1',F'8',F'8',F'16',F'16',F'8',F'8',F'1',F'1',F'8'
MAP DC (HMAPX*HMAPY)CL1'.' map(hmapx,hmapy)
OX DS F
OY DS F
MINX DS F
MAXX DS F
MINY DS F
MAXY DS F
DX DS F
DY DS F
SX DS F
SY DS F
ERR DS F
ERR2 DS F
PG DC CL80' ' buffer
REGEQU
END BRESENH |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #Ada | Ada | with Ada.Exceptions, Interfaces;
with Ada.Streams;
use Ada.Exceptions, Interfaces;
use Ada.Streams;
package Bitcoin is
subtype BT_Raw_Addr is Stream_Element_Array(1..25);
subtype BT_Checksum is Stream_Element_Array(1..4);
subtype BT_Addr is String(1..34);
subtype Sha256String is String(1..64);
Invalid_Address_Error : Exception;
function Double_Sha256(S : Stream_Element_Array) return BT_Checksum;
function Is_Valid(A : BT_Raw_Addr) return Boolean;
procedure Base58_Decode(S : BT_Addr; A : out BT_Raw_Addr) ;
private
Base58 : constant String := "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function Hex_Val (C, C2 : Character) return Stream_Element;
end Bitcoin;
with GNAT.SHA256, Ada.Strings.Fixed;
use GNAT.SHA256, Ada.Strings.Fixed;
package body Bitcoin is
function Hex_Val (C, C2 : Character) return Stream_Element is
subtype Nibble is Integer range 0..15;
HEX : array (0..255) of Nibble := (
48=>0, 49=>1, 50=>2, 51=>3, 52=>4, 53=>5, 54=>6, 55=>7, 56=>8, 57=>9
, 65=>10, 66=>11, 67=>12, 68 =>13, 69 =>14, 70 =>15
, 97=>10, 98=>11, 99=>12, 100=>13, 101=>14, 102=>15
, Others=>0
);
begin
return Stream_Element(HEX(Character'Pos(C)) * 16 + HEX(Character'Pos(C2)));
end Hex_Val;
function Double_Sha256(S : Stream_Element_Array) return BT_Checksum is
Ctx : Context := Initial_Context;
D : Message_Digest;
S2 : Stream_Element_Array(1..32);
Ctx2 : Context := Initial_Context;
C : BT_Checksum;
begin
Update(Ctx, S);
D := Digest(Ctx);
for I in S2'Range loop
S2(I) := Hex_Val(D(Integer(I)*2-1), D(Integer(I)*2));
end loop;
Update(Ctx2, S2);
D := Digest(Ctx2);
for I in C'Range loop
C(I) := Hex_Val(D(Integer(I)*2-1), D(Integer(I)*2));
end loop;
return C;
end Double_Sha256;
--------------------------------------------------------------------------------
-- Summary of Base58: --
-- We decode S into a 200 bit unsigned integer. --
-- We could use a BigNum library, but choose to go without. --
--------------------------------------------------------------------------------
procedure Base58_Decode(S : BT_Addr; A : out BT_Raw_Addr) is
begin
A := (Others => 0);
for I in S'Range loop
declare
P : Natural := Index(Base58, String(S(I..I)));
C : Natural;
begin
if P = 0 then
raise Invalid_Address_Error;
end if;
C := P - 1;
for J in reverse A'Range loop
C := C + Natural(A(J)) * 58;
A(J) := Stream_Element(Unsigned_32(C) and 255); -- 0x00FF
C := Natural(Shift_Right(Unsigned_32(C),8) and 255); -- 0xFF00
end loop;
if C /= 0 then
raise Invalid_Address_Error;
end if;
end;
end loop;
end Base58_Decode;
function Is_Valid(A : BT_Raw_Addr) return Boolean is
begin
return A(1) = 0 and A(22..25) = Double_Sha256(A(1..21));
end Is_Valid;
end Bitcoin;
with Ada.Text_IO, Bitcoin;
use Ada.Text_IO, Bitcoin;
procedure Bitcoin_Addr_Validate is
begin
declare
BTs : array (positive range <>) of BT_Addr := (
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- VALID
, "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9" -- VALID
, "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X" -- checksum changed, original data.
, "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- data changed, original checksum.
, "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- invalid chars
);
begin
for I in Bts'Range loop
declare
A : BT_Raw_Addr;
Valid : Boolean;
begin
Put(BTs(I) & " validity: ");
Base58_Decode(BTs(I), A);
Valid := Is_Valid(A);
Put_Line(Boolean'Image(Valid));
exception
when E : Invalid_Address_Error =>
Put_Line ("*** Error: Invalid BT address.");
end;
end loop;
end;
end Bitcoin_Addr_Validate;
|
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #Delphi | Delphi |
program Public_point_to_address;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Winapi.Windows,
DCPsha256,
DCPripemd160;
const
bitcoinVersion = 0;
type
TByteArray = array of Byte;
TA25 = TByteArray;
TPPoint = record
x, y: TByteArray;
constructor SetHex(xi, yi: ansistring);
end;
TA25Helper = record helper for TA25
public
constructor Create(p: TPPoint);
function DoubleSHA256(): TByteArray;
procedure UpdateChecksum();
procedure SetPoint(p: TPPoint);
function ToBase58: Ansistring;
end;
function HashSHA256(const Input: TByteArray): TByteArray;
var
Hasher: TDCP_sha256;
begin
Hasher := TDCP_sha256.Create(nil);
try
Hasher.Init;
Hasher.Update(Input[0], Length(Input));
SetLength(Result, Hasher.HashSize div 8);
Hasher.final(Result[0]);
finally
Hasher.Free;
end;
end;
function HashRipemd160(const Input: TByteArray): TByteArray;
var
Hasher: TDCP_ripemd160;
begin
Hasher := TDCP_ripemd160.Create(nil);
try
Hasher.Init;
Hasher.Update(Input[0], Length(Input));
SetLength(Result, Hasher.HashSize div 8);
Hasher.final(Result[0]);
finally
Hasher.Free;
end;
end;
{ TPPoint }
constructor TPPoint.SetHex(xi, yi: ansistring);
function StrToHexArray(value: Ansistring): TByteArray;
var
b: ansistring;
h, i: integer;
begin
SetLength(Result, 32);
for i := 0 to 31 do
begin
b := '$' + copy(value, i * 2 + 1, 2);
if not TryStrToInt(b, h) then
raise Exception.CreateFmt('Error in TPPoint.SetHex.StrToHexArray: Invalid hex string in position %d of "x"',
[i * 2]);
Result[i] := h;
end;
end;
begin
if (Length(xi) <> 64) or (Length(yi) <> 64) then
raise Exception.Create('Error in TPPoint.SetHex: Invalid hex string length');
x := StrToHexArray(xi);
y := StrToHexArray(yi);
end;
{ TA25Helper }
constructor TA25Helper.Create(p: TPPoint);
begin
SetLength(self, 25);
SetPoint(p);
end;
function TA25Helper.DoubleSHA256: TByteArray;
begin
Result := HashSHA256(HashSHA256(copy(self, 0, 21)));
end;
procedure TA25Helper.SetPoint(p: TPPoint);
var
c, s: TByteArray;
begin
c := concat([4], p.x, p.y);
s := HashSHA256(c);
self := concat([self[0]], HashRipemd160(s));
SetLength(self, 25);
UpdateChecksum;
end;
function TA25Helper.ToBase58: Ansistring;
var
c, i, n: Integer;
const
Size = 34;
Alphabet: Ansistring = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
begin
SetLength(Result, Size);
for n := Size - 1 downto 0 do
begin
c := 0;
for i := 0 to 24 do
begin
c := c * 256 + Self[i];
Self[i] := byte(c div 58);
c := c mod 58;
end;
Result[n + 1] := Alphabet[c + 1];
end;
i := 2;
while (i < Size) and (result[i] = '1') do
inc(i);
Result := copy(Result, i - 1, Size);
end;
procedure TA25Helper.UpdateChecksum;
begin
CopyMemory(@self[21], @self.DoubleSHA256[0], 4);
end;
var
p: TPPoint;
a: TA25;
const
x: Ansistring = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352';
y: Ansistring = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6';
begin
p.SetHex(x, y);
a := TA25.Create(p);
writeln(a.ToBase58);
readln;
end. |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #C.2B.2B | C++ | #ifndef PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_
#include <opencv2/opencv.hpp>
#include <string.h>
#include <queue>
using namespace cv;
using namespace std;
class FloodFillAlgorithm {
public:
FloodFillAlgorithm(Mat* image) :
image(image) {
}
virtual ~FloodFillAlgorithm();
void flood(Point startPoint, Scalar tgtColor, Scalar loDiff);
void flood(Point startPoint, Mat* tgtMat);
protected:
Mat* image;
private:
bool insideImage(Point p);
};
#endif /* PROCESSING_FLOODFILLALGORITHM_H_ */
|
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #D | D | import std.array, bitmap;
void floodFill(Color)(Image!Color img, in uint x, in uint y,
in Color color)
/*pure*/ nothrow in {
assert (y < img.ny && x < img.nx);
} body {
immutable target = img[x, y];
static struct Pos { uint x, y; }
auto stack = [Pos(x, y)];
while (!stack.empty) {
immutable p = stack.back;
stack.popBack;
if (p.y < img.ny && p.x < img.nx && img[p.x, p.y] == target) {
img[p.x, p.y] = color;
stack.assumeSafeAppend;
stack ~= [Pos(p.x, p.y + 1), Pos(p.x, p.y - 1),
Pos(p.x + 1, p.y), Pos(p.x - 1, p.y)];
}
}
}
void main() {
Image!RGB img;
loadPPM6(img, "unfilled_circ.ppm");
img.floodFill(200, 200, RGB(127, 0, 0));
img.savePPM6("unfilled_circ_flooded.ppm");
} |
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
| #EchoLisp | EchoLisp |
(not #t) → #f
(not #f) → #t
(not null) → #f
(not 0) → #f
|
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
| #EGL | EGL |
myBool boolean = 0;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 1;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 2;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = false;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = true;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myInt int = 0;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 1;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 2;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = false;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = true;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
|
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
| #Ursa | Ursa | decl string mode
while (not (or (= mode "encode") (= mode "decode")))
out "encode/decode: " console
set mode (lower (in string console))
end while
decl string message
out "message: " console
set message (upper (in string console))
decl int key
out "key: " console
set key (in int console)
if (or (> key 26) (< key 0))
out endl "invalid key" endl console
stop
end if
if (= mode "decode")
set key (int (- 26 key))
end if
for (decl int i) (< i (size message)) (inc i)
if (and (> (ord message<i>) 64) (< (ord message<i>) 91))
out (chr (int (+ (mod (int (+ (- (ord message<i>) 65) key)) 26) 65))) console
end if
end for
out endl console |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #C.23 | C# |
using System;
using System.Collections.Generic;
namespace BoxTheCompass
{
class Compass
{
string[] cp = new string[] {"North", "North by east", "North-northeast", "Northeast by north", "Northeast","Northeast by east",
"East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast",
"Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south",
"Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest",
"Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west", "North"};
public void compassHeading(float a)
{
int h = Convert.ToInt32(Math.Floor(a / 11.25f + .5f)) % 32;
Console.WriteLine( "{0,2}: {1,-22} : {2,6:N}",h + 1, cp[h], a );
}
};
class Program
{
static void Main(string[] args)
{
Compass c = new Compass();
float[] degs = new float[] {0.0f, 16.87f, 16.88f, 33.75f, 50.62f, 50.63f, 67.5f, 84.37f, 84.38f, 101.25f,
118.12f, 118.13f, 135.0f, 151.87f, 151.88f, 168.75f, 185.62f, 185.63f, 202.5f, 219.37f, 219.38f, 236.25f,
253.12f, 253.13f, 270.0f, 286.87f, 286.88f, 303.75f, 320.62f, 320.63f, 337.5f, 354.37f, 354.38f};
foreach (float d in degs)
c.compassHeading(d);
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
|
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Python | Python | from PIL import Image
# Open the image
image = Image.open("lena.jpg")
# Get the width and height of the image
width, height = image.size
# Calculate the amount of pixels
amount = width * height
# Total amount of greyscale
total = 0
# B/W image
bw_image = Image.new('L', (width, height), 0)
# Bitmap image
bm_image = Image.new('1', (width, height), 0)
for h in range(0, height):
for w in range(0, width):
r, g, b = image.getpixel((w, h))
greyscale = int((r + g + b) / 3)
total += greyscale
bw_image.putpixel((w, h), gray_scale)
# The average greyscale
avg = total / amount
black = 0
white = 1
for h in range(0, height):
for w in range(0, width):
v = bw_image.getpixel((w, h))
if v >= avg:
bm_image.putpixel((w, h), white)
else:
bm_image.putpixel((w, h), black)
bw_image.show()
bm_image.show() |
http://rosettacode.org/wiki/Bitmap/Histogram | Bitmap/Histogram | Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.
Test task
Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:
Convert image to grayscale;
Compute the histogram
Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
Replace each pixel of luminance lesser than the median to black, and others to white.
Use read/write ppm file, and grayscale image solutions.
| #Racket | Racket | #lang racket
(require racket/draw math/statistics racket/require
(filtered-in
(lambda (name) (regexp-replace #rx"unsafe-" name ""))
racket/unsafe/ops))
;; CIE formula as discussed in "Greyscale image" task
(define (L r g b)
;; In fact there is no need, statistically for L to be divided by 10000
(fx+ (fx* r 2126) (fx+ (fx* g 7152) (fx* b 722))))
(define (prepare-bytes bm depth load-content?)
(define w (send bm get-width))
(define h (send bm get-height))
(define rv (make-bytes (* w h depth)))
(define just-alpha? #f)
(define pre-multiply? #t); let racket cope with alpha-ness
(when load-content? (send bm get-argb-pixels 0 0 w h rv just-alpha? pre-multiply?))
rv)
(define (bitmap-histogram bm)
(unless (send bm is-color?) (error 'bitmap->histogram "bitmap must be colour"))
(define pxls (prepare-bytes bm 4 #t))
(define l# (make-hash))
(for ((r (in-bytes pxls 1 #f 4)) (g (in-bytes pxls 2 #f 4)) (b (in-bytes pxls 3 #f 4)))
(hash-update! l# (L r g b) add1 0))
(define xs (hash-keys l#)) ; the colour values
(define ws (hash-values l#)) ; the "weights" i.e. counts for median
(values xs ws))
(define (bitmap-quantile q bm (hist-xs #f) (hist-ws #f))
(define-values (xs ws) (if (and hist-xs hist-ws)
(values hist-xs hist-ws)
(bitmap-histogram bm)))
(quantile q < xs ws))
;; we don't return a 1-depth bitmap, so we can do more interesting things with colour
(define (bitmap->monochrome q bm (hist-xs #f) (hist-ws #f))
(define Q (bitmap-quantile q bm hist-xs hist-ws))
(define pxls (prepare-bytes bm 4 #t))
(for ((r (in-bytes pxls 1 #f 4))
(g (in-bytes pxls 2 #f 4))
(b (in-bytes pxls 3 #f 4))
(i (sequence-map (curry fx* 4) (in-naturals))))
(define l (L r g b))
(define rgb+ (cond [(fx< l Q) 0] [else 255]))
(bytes-set! pxls (fx+ i 1) rgb+)
(bytes-set! pxls (fx+ i 2) rgb+)
(bytes-set! pxls (fx+ i 3) rgb+))
(define w (send bm get-width))
(define h (send bm get-height))
(define rv (make-bitmap w h #f))
(send rv set-argb-pixels 0 0 w h pxls)
rv)
(module+ main
(define bm (read-bitmap "271px-John_Constable_002.jpg"))
(define-values (xs ws) (bitmap-histogram bm))
(void
(send (bitmap->monochrome 1/4 bm) save-file "histogram-racket-0.25.png" 'png)
(send (bitmap->monochrome 1/2 bm) save-file "histogram-racket-0.50.png" 'png) ; median
(send (bitmap->monochrome 3/4 bm xs ws) save-file "histogram-racket-0.75.png" 'png))) |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #ALGOL_W | ALGOL W | % performs bitwise and, or, not, left-shift and right shift on the integers n1 and n2 %
% Algol W does not have xor, arithmetic right shift, left rotate or right rotate %
procedure bitOperations ( integer value n1, n2 ) ;
begin
bits b1, b2;
% the Algol W bitwse operations operate on bits values, so we first convert the %
% integers to bits values using the builtin bitstring procedure %
% the results are converted back to integers using the builtin number procedure %
% all Algol W bits and integers are 32 bits quantities %
b1 := bitstring( n1 );
b2 := bitstring( n2 );
% perform the operaations and display the results as integers %
write( n1, " and ", n2, " = ", number( b1 and b2 ) );
write( n1, " or ", n2, " = ", number( b1 or b2 ) );
write( " "
, " not ", n1, " = ", number( not b1 ) );
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" );
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ; |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #Phix | Phix | -- demo\rosetta\Bitmap_BezierQuadratic.exw
include ppm.e -- black, green, red, white, new_image(), write_ppm(), bresLine() -- (covers above requirements)
function quadratic_bezier(sequence img, atom x1, y1, x2, y2, x3, y3, integer colour, segments)
sequence pts = repeat(0,segments*2)
for i=0 to segments*2-1 by 2 do
atom t = i/segments,
t1 = 1-t,
a = power(t1,2),
b = 2*t*t1,
c = power(t,2)
pts[i+1] = floor(a*x1+b*x2+c*x3)
pts[i+2] = floor(a*y1+b*y2+c*y3)
end for
for i=1 to segments*2-2 by 2 do
img = bresLine(img, pts[i], pts[i+1], pts[i+2], pts[i+3], colour)
end for
return img
end function
sequence img = new_image(200,200,black)
img = quadratic_bezier(img, 0,100, 100,200, 200,0, white, 40)
img = bresLine(img,0,100,100,200,green)
img = bresLine(img,100,200,200,0,green)
img[1][100] = red
img[100][200] = red
img[200][1] = red
write_ppm("BezierQ.ppm",img) |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #PicoLisp | PicoLisp | (scl 6)
(de quadBezier (Img N X1 Y1 X2 Y2 X3 Y3)
(let (R (* N N) X X1 Y Y1 DX 0 DY 0)
(for I N
(let (J (- N I) A (*/ 1.0 J J R) B (*/ 2.0 I J R) C (*/ 1.0 I I R))
(brez Img X Y
(setq DX (- (+ (*/ A X1 1.0) (*/ B X2 1.0) (*/ C X3 1.0)) X))
(setq DY (- (+ (*/ A Y1 1.0) (*/ B Y2 1.0) (*/ C Y3 1.0)) Y)) )
(inc 'X DX)
(inc 'Y DY) ) ) ) ) |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic | Bitmap/Bézier curves/Quadratic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve
(definition on Wikipedia).
| #PureBasic | PureBasic | Procedure quad_bezier(img, p1x, p1y, p2x, p2y, p3x, p3y, Color, n_seg)
Protected i
Protected.f T, t1, a, b, c, d
Dim pts.POINT(n_seg)
For i = 0 To n_seg
T = i / n_seg
t1 = 1.0 - T
a = Pow(t1, 2)
b = 2.0 * T * t1
c = Pow(T, 2)
pts(i)\x = a * p1x + b * p2x + c * p3x
pts(i)\y = a * p1y + b * p2y + c * p3y
Next
StartDrawing(ImageOutput(img))
FrontColor(Color)
For i = 0 To n_seg - 1
BresenhamLine(pts(i)\x, pts(i)\y, pts(i + 1)\x, pts(i + 1)\y)
Next
StopDrawing()
EndProcedure
Define w, h, img
w = 200: h = 200: img = 1
CreateImage(img, w, h) ;img is internal id of the image
OpenWindow(0, 0, 0, w, h,"Bezier curve, quadratic", #PB_Window_SystemMenu)
quad_bezier(1, 80,20, 130,80, 20,150, RGB(255, 255, 255), 20)
ImageGadget(0, 0, 0, w, h, ImageID(1))
Define event
Repeat
event = WaitWindowEvent()
Until event = #PB_Event_CloseWindow
|
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #J | J | NB.*getBresenhamCircle v Returns points for a circle given center and radius
NB. y is: y0 x0 radius
getBresenhamCircle=: monad define
'y0 x0 radius'=. y
x=. 0
y=. radius
f=. -. radius
pts=. 0 2$0
while. x <: y do.
pts=. pts , y , x
if. f >: 0 do.
y=. <:y
f=. f + _2 * y
end.
x=. >:x
f =. f + >: 2 * x
end.
offsets=. (,|."1) (1 _1 {~ #: i.4) *"1"1 _ pts
~.,/ (y0,x0) +"1 offsets
)
NB.*drawCircles v Draws circle(s) (x) on image (y)
NB. x is: 2-item list of boxed (y0 x0 radius) ; (color)
drawCircles=: (1&{:: ;~ [: ; [: <@getBresenhamCircle"1 (0&{::))@[ setPixels ] |
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm | Bitmap/Midpoint circle algorithm | Task
Using the data storage type defined on this page for raster images,
write an implementation of the midpoint circle algorithm (also known as Bresenham's circle algorithm).
(definition on Wikipedia).
| #Java | Java |
import java.awt.Color;
public class MidPointCircle {
private BasicBitmapStorage image;
public MidPointCircle(final int imageWidth, final int imageHeight) {
this.image = new BasicBitmapStorage(imageWidth, imageHeight);
}
private void drawCircle(final int centerX, final int centerY, final int radius) {
int d = (5 - r * 4)/4;
int x = 0;
int y = radius;
Color circleColor = Color.white;
do {
image.setPixel(centerX + x, centerY + y, circleColor);
image.setPixel(centerX + x, centerY - y, circleColor);
image.setPixel(centerX - x, centerY + y, circleColor);
image.setPixel(centerX - x, centerY - y, circleColor);
image.setPixel(centerX + y, centerY + x, circleColor);
image.setPixel(centerX + y, centerY - x, circleColor);
image.setPixel(centerX - y, centerY + x, circleColor);
image.setPixel(centerX - y, centerY - x, circleColor);
if (d < 0) {
d += 2 * x + 1;
} else {
d += 2 * (x - y) + 1;
y--;
}
x++;
} while (x <= y);
}
}
|
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #Fortran | Fortran | subroutine cubic_bezier(img, p1, p2, p3, p4, color)
type(rgbimage), intent(inout) :: img
type(point), intent(in) :: p1, p2, p3, p4
type(rgb), intent(in) :: color
integer :: i, j
real :: pts(0:N_SEG,0:1), t, a, b, c, d, x, y
do i = 0, N_SEG
t = real(i) / real(N_SEG)
a = (1.0 - t)**3.0
b = 3.0 * t * (1.0 - t)**2
c = 3.0 * (1.0 - t) * t**2
d = t**3.0
x = a * p1%x + b * p2%x + c * p3%x + d * p4%x
y = a * p1%y + b * p2%y + c * p3%y + d * p4%y
pts(i,0) = x
pts(i,1) = y
end do
do i = 0, N_SEG-1
j = i + 1
call draw_line(img, point(pts(i,0), pts(i,1)), &
point(pts(j,0), pts(j,1)), color)
end do
end subroutine cubic_bezier |
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.)
| #UNIX_Shell | UNIX Shell | function write {
_.to_s > "$1"
} |
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.)
| #Vedit_macro_language | Vedit macro language | /////////////////////////////////////////////////////////////////////
//
// Save image as PPM file.
// @10 = filename. Buffer #10 contains the Pixel data.
//
:SAVE_PPM:
Buf_Switch(#10)
BOF
IT("P6") IN
Num_Ins(#11, LEFT) // width of image
Num_Ins(#12, LEFT) // height of image
Num_Ins(255, LEFT+NOCR) // maxval
IC(10)
File_Save_As(@10, OK)
Return
|
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #Action.21 | Action! | INCLUDE "H6:RGBLINE.ACT" ;from task Bresenham's line algorithm
RGB black,yellow,violet,blue
PROC DrawImage(RgbImage POINTER img BYTE x,y)
RGB POINTER ptr
BYTE i,j
ptr=img.data
FOR j=0 TO img.h-1
DO
FOR i=0 TO img.w-1
DO
IF RgbEqual(ptr,yellow) THEN
Color=1
ELSEIF RgbEqual(ptr,violet) THEN
Color=2
ELSEIF RgbEqual(ptr,blue) THEN
Color=3
ELSE
Color=0
FI
Plot(x+i,y+j)
ptr==+RGBSIZE
OD
OD
RETURN
PROC Main()
RgbImage img
BYTE CH=$02FC,width=[81],height=[51],st=[5]
BYTE ARRAY ptr(12393)
BYTE c,i,n
INT x,y,nx,ny
RGB POINTER col
Graphics(7+16)
SetColor(0,13,12) ;yellow
SetColor(1,4,8) ;violet
SetColor(2,8,6) ;blue
SetColor(4,0,0) ;black
RgbBlack(black)
RgbYellow(yellow)
RgbViolet(violet)
RgbBlue(blue)
InitRgbImage(img,width,height,ptr)
FillRgbImage(img,black)
nx=width/st ny=height/st
FOR n=0 TO 2*nx+2*ny-1
DO
IF n MOD 3=0 THEN col=yellow
ELSEIF n MOD 3=1 THEN col=violet
ELSE col=blue FI
IF n<nx THEN
x=n*st y=0
ELSEIF n<nx+ny THEN
x=width-1 y=(n-nx)*st
ELSEIF n<2*nx+ny THEN
x=width-1-(n-nx-ny)*st y=height-1
ELSE
x=0 y=height-1-(n-2*nx-ny)*st
FI
RgbLine(img,width/2,height/2,x,y,col)
OD
DrawImage(img,(160-width)/2,(96-height)/2)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #C | C | #include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
const char *coin_err;
#define bail(s) { coin_err = s; return 0; }
int unbase58(const char *s, unsigned char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
int i, j, c;
const char *p;
memset(out, 0, 25);
for (i = 0; s[i]; i++) {
if (!(p = strchr(tmpl, s[i])))
bail("bad char");
c = p - tmpl;
for (j = 25; j--; ) {
c += 58 * out[j];
out[j] = c % 256;
c /= 256;
}
if (c) bail("address too long");
}
return 1;
}
int valid(const char *s) {
unsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH];
coin_err = "";
if (!unbase58(s, dec)) return 0;
SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);
if (memcmp(dec + 21, d2, 4))
bail("bad digest");
return 1;
}
int main (void) {
const char *s[] = {
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I",
0 };
int i;
for (i = 0; s[i]; i++) {
int status = valid(s[i]);
printf("%s: %s\n", s[i], status ? "Ok" : coin_err);
}
return 0;
} |
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #Factor | Factor | USING: checksums checksums.ripemd checksums.sha io.binary kernel
math sequences ;
IN: rosetta-code.bitcoin.point-address
CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
: btc-checksum ( bytes -- checksum-bytes )
2 [ sha-256 checksum-bytes ] times 4 head ;
: bigint>base58 ( n -- str )
33 [ 58 /mod ALPHABET nth ] "" replicate-as reverse nip ;
: >base58 ( bytes -- str )
be> bigint>base58 ;
: point>address ( X Y -- address )
[ 32 >be ] bi@ append
0x4 prefix
sha-256 checksum-bytes
ripemd-160 checksum-bytes
dup 0 prefix btc-checksum
append 0 prefix >base58 ;
|
http://rosettacode.org/wiki/Bitcoin/public_point_to_address | Bitcoin/public point to address | Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
compute the SHA-256 of this string ;
compute the RIPEMD-160 of this SHA-256 digest ;
compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;
Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
Extra credit: add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| #Go | Go | package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/ripemd160"
)
// Point is a type for a bitcoin public point.
type Point struct {
x, y [32]byte
}
// SetHex takes two hexidecimal strings and decodes them into the receiver.
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
// A25 type in common with Bitcoin/address validation task.
type A25 [25]byte
// doubleSHA256 method in common with Bitcoin/address validation task.
func (a *A25) doubleSHA256() []byte {
h := sha256.New()
h.Write(a[:21])
d := h.Sum([]byte{})
h = sha256.New()
h.Write(d)
return h.Sum(d[:0])
}
// UpdateChecksum computes the address checksum on the first 21 bytes and
// stores the result in the last 4 bytes.
func (a *A25) UpdateChecksum() {
copy(a[21:], a.doubleSHA256())
}
// SetPoint takes a public point and generates the corresponding address
// into the receiver, complete with valid checksum.
func (a *A25) SetPoint(p *Point) {
c := [65]byte{4}
copy(c[1:], p.x[:])
copy(c[33:], p.y[:])
h := sha256.New()
h.Write(c[:])
s := h.Sum([]byte{})
h = ripemd160.New()
h.Write(s)
h.Sum(a[1:1])
a.UpdateChecksum()
}
// Tmpl in common with Bitcoin/address validation task.
var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
// A58 returns a base58 encoded bitcoin address corresponding to the receiver.
// Code adapted from the C solution to this task.
func (a *A25) A58() []byte {
var out [34]byte
for n := 33; n >= 0; n-- {
c := 0
for i := 0; i < 25; i++ {
c = c*256 + int(a[i])
a[i] = byte(c / 58)
c %= 58
}
out[n] = tmpl[c]
}
i := 1
for i < 34 && out[i] == '1' {
i++
}
return out[i-1:]
}
func main() {
// parse hex into point object
var p Point
err := p.SetHex(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
if err != nil {
fmt.Println(err)
return
}
// generate address object from point
var a A25
a.SetPoint(&p)
// show base58 representation
fmt.Println(string(a.A58()))
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Delphi | Delphi | def floodFill(image, x, y, newColor) {
def matchColor := image[x, y]
def w := image.width()
def h := image.height()
/** For any given pixel x,y, this algorithm first fills a contiguous
horizontal line segment of pixels containing that pixel, then
recursively scans the two adjacent rows over the same horizontal
interval. Let this be invocation 0, and the immediate recursive
invocations be 1, 2, 3, ..., # be pixels of the wrong color, and
* be where each scan starts; the fill ordering is as follows:
--------------##########-------
-...1111111111*11####*33333...-
###########000*000000000000...-
-...2222222222*22222##*4444...-
--------------------##---------
Each invocation returns the x coordinate of the rightmost pixel it filled,
or x0 if none were.
Since it is recursive, this algorithm is unsuitable for large images
with small stacks.
*/
def fillScan(var x0, y) {
if (y >= 0 && y < h && x0 >= 0 && x0 < w) {
image[x0, y] := newColor
var x1 := x0
# Fill rightward
while (x1 < w - 1 && image.test(x1 + 1, y, matchColor)) {
x1 += 1
image[x1, y] := newColor # This could be replaced with a horizontal-line drawing operation
}
# Fill leftward
while (x0 > 0 && image.test(x0 - 1, y, matchColor)) {
x0 -= 1
image[x0, y] := newColor
}
if (x0 > x1) { return x0 } # Filled at most center
# x0..x1 is now a run of newly-filled pixels.
# println(`Filled $y $x0..$x1`)
# println(image)
# Scan the lines above and below
for ynext in [y - 1, y + 1] {
if (ynext >= 0 && ynext < h) {
var x := x0
while (x <= x1) {
if (image.test(x, ynext, matchColor)) {
x := fillScan(x, ynext)
}
x += 1
}
}
}
return x1
} else {
return x0
}
}
fillScan(x, y)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.