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/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
| #Elena | Elena |
iex(1)> true === :true
true
iex(2)> false === :false
true
iex(3)> true === 1
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
| #Elixir | Elixir |
iex(1)> true === :true
true
iex(2)> false === :false
true
iex(3)> true === 1
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
| #Ursala | Ursala | #import std
#import nat
enc "n" = * -:~&@T ^p(rep"n" ~&zyC,~&)~~K30K31X letters # encryption function
dec "n" = * -:~&@T ^p(~&,rep"n" ~&zyC)~~K30K31X letters # decryption function
plaintext = 'the five boxing wizards jump quickly THE FIVE BOXING WIZARDS JUMP QUICKLY'
#show+ # exhaustive test
test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25 |
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.2B.2B | C++ | #include <string>
#include <boost/array.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <math.h>
using std::string;
using namespace boost::assign;
int get_Index(float angle)
{
return static_cast<int>(floor(angle / 11.25 +0.5 )) % 32 + 1;
}
string get_Abbr_From_Index(int i)
{
static boost::array<std::string, 32> points(list_of
("N")("NbE")("NNE")("NEbN")("NE")("NEbE")("ENE")("EbN")
("E")("EbS")("ESE")("SEbE")("SE")("SEbS")("SSE")("SbE")
("S")("SbW")("SSW")("SWbS")("SW")("SWbW")("WSW")("WbS")
("W")("WbN")("WNW")("NWbW")("NW")("NWbN")("NNW")("NbW"));
return points[i-1];
}
string Build_Name_From_Abbreviation(string a)
{
string retval;
for (int i = 0; i < a.size(); ++i){
if ((1 == i) && (a[i] != 'b') && (a.size() == 3)) retval += "-";
switch (a[i]){
case 'N' : retval += "north"; break;
case 'S' : retval += "south"; break;
case 'E' : retval += "east"; break;
case 'W' : retval += "west"; break;
case 'b' : retval += " by "; break;
}
}
retval[0] = toupper(retval[0]);
return retval;
}
int main()
{
boost::array<float,33> headings(list_of
(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));
int i;
boost::format f("%1$4d %2$-20s %3$_7.2f");
BOOST_FOREACH(float a, headings)
{
i = get_Index(a);
std::cout << f % i % Build_Name_From_Abbreviation(get_Abbr_From_Index(i)) % a << std::endl;
}
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.
| #Raku | Raku | class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @.data;
}
role PBM {
has @.BM;
method P4 returns Blob {
"P4\n{self.width} {self.height}\n".encode('ascii')
~ Blob.new: self.BM
}
}
sub getline ( $fh ) {
my $line = '#'; # skip comments when reading image file
$line = $fh.get while $line.substr(0,1) eq '#';
$line;
}
sub load-ppm ( $ppm ) {
my $fh = $ppm.IO.open( :enc('ISO-8859-1') );
my $type = $fh.&getline;
my ($width, $height) = $fh.&getline.split: ' ';
my $depth = $fh.&getline;
Bitmap.new( width => $width.Int, height => $height.Int,
data => ( $fh.slurp.ords.rotor(3).map:
{ Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } )
)
}
sub grayscale ( Bitmap $bmp ) {
map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data;
}
sub histogram ( Bitmap $bmp ) {
my @gray = grayscale($bmp);
my $threshold = @gray.sum / @gray;
for @gray.rotor($bmp.width) {
my @row = $_.list;
@row.push(0) while @row % 8;
$bmp.BM.append: @row.rotor(8).map: { :2(($_ X< $threshold)».Numeric.join) }
}
}
my $filename = './Lenna.ppm';
my Bitmap $b = load-ppm( $filename ) but PBM;
histogram($b);
'./Lenna-bw.pbm'.IO.open(:bin, :w).write: $b.P4; |
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.
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- BIT OPERATIONS FOR APPLESCRIPT (VIA JAVASCRIPT FOR AUTOMATION)
-- bitAND :: Int -> Int -> Int
on bitAND(x, y)
jsOp2("&", x, y)
end bitAND
-- bitOR :: Int -> Int -> Int
on bitOR(x, y)
jsOp2("|", x, y)
end bitOR
-- bitXOr :: Int -> Int -> Int
on bitXOR(x, y)
jsOp2("^", x, y)
end bitXOR
-- bitNOT :: Int -> Int
on bitNOT(x)
jsOp1("~", x)
end bitNOT
-- (<<) :: Int -> Int -> Int
on |<<|(x, y)
if 31 < y then
0
else
jsOp2("<<", x, y)
end if
end |<<|
-- Logical right shift
-- (>>>) :: Int -> Int -> Int
on |>>>|(x, y)
jsOp2(">>>", x, y)
end |>>>|
-- Arithmetic right shift
-- (>>) :: Int -> Int -> Int
on |>>|(x, y)
jsOp2(">>", x, y)
end |>>|
-- TEST ----------------------------------------------------------
on run
-- Using an ObjC interface to Javascript for Automation
set strClip to bitWise(255, 170)
set the clipboard to strClip
strClip
end run
-- bitWise :: Int -> Int -> String
on bitWise(a, b)
set labels to {"a AND b", "a OR b", "a XOR b", "NOT a", ¬
"a << b", "a >>> b", "a >> b"}
set xs to {bitAND(a, b), bitOR(a, b), bitXOR(a, b), bitNOT(a), ¬
|<<|(a, b), |>>>|(a, b), |>>|(a, b)}
script asBin
property arrow : " -> "
on |λ|(x, y)
justifyRight(8, space, x) & arrow & ¬
justifyRight(14, space, y as text) & arrow & showBinary(y)
end |λ|
end script
unlines({"32 bit signed integers (in two's complement binary encoding)", "", ¬
unlines(zipWith(asBin, ¬
{"a = " & a as text, "b = " & b as text}, {a, b})), "", ¬
unlines(zipWith(asBin, labels, xs))})
end bitWise
-- CONVERSIONS AND DISPLAY
-- bitsFromInt :: Int -> Either String [Bool]
on bitsFromIntLR(x)
script go
on |λ|(n, d, bools)
set xs to {0 ≠ d} & bools
if n > 0 then
|λ|(n div 2, n mod 2, xs)
else
xs
end if
end |λ|
end script
set a to abs(x)
if (2.147483647E+9) < a then
|Left|("Integer overflow – maximum is (2 ^ 31) - 1")
else
set bs to go's |λ|(a div 2, a mod 2, {})
if 0 > x then
|Right|(replicate(32 - (length of bs), true) & ¬
binSucc(map(my |not|, bs)))
else
set bs to go's |λ|(a div 2, a mod 2, {})
|Right|(replicate(32 - (length of bs), false) & bs)
end if
end if
end bitsFromIntLR
-- Successor function (+1) for unsigned binary integer
-- binSucc :: [Bool] -> [Bool]
on binSucc(bs)
script succ
on |λ|(a, x)
if a then
if x then
Tuple(a, false)
else
Tuple(x, true)
end if
else
Tuple(a, x)
end if
end |λ|
end script
set tpl to mapAccumR(succ, true, bs)
if |1| of tpl then
{true} & |2| of tpl
else
|2| of tpl
end if
end binSucc
-- showBinary :: Int -> String
on showBinary(x)
script showBin
on |λ|(xs)
script bChar
on |λ|(b)
if b then
"1"
else
"0"
end if
end |λ|
end script
map(bChar, xs)
end |λ|
end script
bindLR(my bitsFromIntLR(x), showBin)
end showBinary
-- JXA ------------------------------------------------------------------
--jsOp2 :: String -> a -> b -> c
on jsOp2(strOp, a, b)
bindLR(evalJSLR(unwords({a as text, strOp, b as text})), my |id|) as integer
end jsOp2
--jsOp2 :: String -> a -> b
on jsOp1(strOp, a)
bindLR(evalJSLR(unwords({strOp, a as text})), my |id|) as integer
end jsOp1
-- evalJSLR :: String -> Either String a
on evalJSLR(strJS)
try -- NB if gJSC is global it must be released
-- (e.g. set to null) at end of script
gJSC's evaluateScript
on error
set gJSC to current application's JSContext's new()
log ("new JSC")
end try
set v to unwrap((gJSC's evaluateScript:(strJS))'s toObject())
if v is missing value then
|Left|("JS evaluation error")
else
|Right|(v)
end if
end evalJSLR
-- GENERIC FUNCTIONS --------------------------------------------------
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Right| of m then
mReturn(mf)'s |λ|(|Right| of m)
else
m
end if
end bindLR
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- id :: a -> a
on |id|(x)
x
end |id|
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- 'The mapAccumR function behaves like a combination of map and foldr;
-- it applies a function to each element of a list, passing an accumulating
-- parameter from |Right| to |Left|, and returning a final value of this
-- accumulator together with the new list.' (see Hoogle)
-- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumR(f, acc, xs)
script
on |λ|(x, a, i)
tell mReturn(f) to set pair to |λ|(|1| of a, x, i)
Tuple(|1| of pair, (|2| of pair) & |2| of a)
end |λ|
end script
foldr(result, Tuple(acc, []), xs)
end mapAccumR
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- not :: Bool -> Bool
on |not|(p)
not p
end |not|
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to {my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
-- unwrap :: NSObject -> a
on unwrap(objCValue)
if objCValue is missing value then
missing value
else
set ca to current application
item 1 of ((ca's NSArray's arrayWithObject:objCValue) as list)
end if
end unwrap
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith |
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).
| #Python | Python |
#lang racket
(require racket/draw)
(define (draw-line dc p q)
(match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))
(define (draw-lines dc ps)
(void
(for/fold ([p0 (first ps)]) ([p (rest ps)])
(draw-line dc p0 p)
p)))
(define (int t p q)
(define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1)))
(map (int1 t) p q))
(define (bezier-points p0 p1 p2)
(for/list ([t (in-range 0.0 1.0 (/ 1.0 20))])
(int t (int t p0 p1) (int t p1 p2))))
(define bm (make-object bitmap% 17 17))
(define dc (new bitmap-dc% [bitmap bm]))
(send dc set-smoothing 'unsmoothed)
(send dc set-pen "red" 1 'solid)
(draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16)))
bm
|
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).
| #R | R |
#lang racket
(require racket/draw)
(define (draw-line dc p q)
(match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))
(define (draw-lines dc ps)
(void
(for/fold ([p0 (first ps)]) ([p (rest ps)])
(draw-line dc p0 p)
p)))
(define (int t p q)
(define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1)))
(map (int1 t) p q))
(define (bezier-points p0 p1 p2)
(for/list ([t (in-range 0.0 1.0 (/ 1.0 20))])
(int t (int t p0 p1) (int t p1 p2))))
(define bm (make-object bitmap% 17 17))
(define dc (new bitmap-dc% [bitmap bm]))
(send dc set-smoothing 'unsmoothed)
(send dc set-pen "red" 1 'solid)
(draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16)))
bm
|
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).
| #Racket | Racket |
#lang racket
(require racket/draw)
(define (draw-line dc p q)
(match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))
(define (draw-lines dc ps)
(void
(for/fold ([p0 (first ps)]) ([p (rest ps)])
(draw-line dc p0 p)
p)))
(define (int t p q)
(define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1)))
(map (int1 t) p q))
(define (bezier-points p0 p1 p2)
(for/list ([t (in-range 0.0 1.0 (/ 1.0 20))])
(int t (int t p0 p1) (int t p1 p2))))
(define bm (make-object bitmap% 17 17))
(define dc (new bitmap-dc% [bitmap bm]))
(send dc set-smoothing 'unsmoothed)
(send dc set-pen "red" 1 'solid)
(draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16)))
bm
|
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).
| #Raku | Raku | class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i + $j * $!width] }
method set-pixel ($i, $j, Pixel $p) {
return if $j >= $!height;
self.pixel($i, $j) = $p.clone;
}
method get-pixel ($i, $j) returns Pixel {
self.pixel($i, $j);
}
method line(($x0 is copy, $y0 is copy), ($x1 is copy, $y1 is copy), $pix) {
my $steep = abs($y1 - $y0) > abs($x1 - $x0);
if $steep {
($x0, $y0) = ($y0, $x0);
($x1, $y1) = ($y1, $x1);
}
if $x0 > $x1 {
($x0, $x1) = ($x1, $x0);
($y0, $y1) = ($y1, $y0);
}
my $Δx = $x1 - $x0;
my $Δy = abs($y1 - $y0);
my $error = 0;
my $Δerror = $Δy / $Δx;
my $y-step = $y0 < $y1 ?? 1 !! -1;
my $y = $y0;
for $x0 .. $x1 -> $x {
if $steep {
self.set-pixel($y, $x, $pix);
} else {
self.set-pixel($x, $y, $pix);
}
$error += $Δerror;
if $error >= 0.5 {
$y += $y-step;
$error -= 1.0;
}
}
}
method dot (($px, $py), $pix, $radius = 2) {
for $px - $radius .. $px + $radius -> $x {
for $py - $radius .. $py + $radius -> $y {
self.set-pixel($x, $y, $pix) if ( $px - $x + ($py - $y) * i ).abs <= $radius;
}
}
}
method quadratic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), $pix, $segments = 30 ) {
my @line-segments = map -> $t {
my \a = (1-$t)²;
my \b = $t * (1-$t) * 2;
my \c = $t²;
(a*$x1 + b*$x2 + c*$x3).round(1),(a*$y1 + b*$y2 + c*$y3).round(1)
}, (0, 1/$segments, 2/$segments ... 1);
for @line-segments.rotor(2=>-1) -> ($p1, $p2) { self.line( $p1, $p2, $pix) };
}
method data { @!data }
}
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
sub color( $r, $g, $b) { Pixel.new(R => $r, G => $g, B => $b) }
my Bitmap $b = Bitmap.new( width => 600, height => 400) but PPM;
$b.fill( color(2,2,2) );
my @points = (65,25), (85,380), (570,15);
my %seen;
my $c = 0;
for @points.permutations -> @this {
%seen{@this.reverse.join.Str}++;
next if %seen{@this.join.Str};
$b.quadratic( |@this, color(255-$c,127,$c+=80) );
}
@points.map: { $b.dot( $_, color(255,0,0), 3 )}
$*OUT.write: $b.P6; |
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).
| #Julia | Julia | function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T
x = radius - 1
y = 0
δx = δy = 1
er = δx - (radius << 1)
s = x + y
while x ≥ y
for opx in (+, -), opy in (+, -), el in (x, y)
@inbounds img[opx(x0, el) + 1, opy(y0, s - el) + 1] = col
end
if er ≤ 0
y += 1
er += δy
δy += 2
end
if er > 0
x -= 1
δx += 2
er += (-radius << 1) + δx
end
s = x + y
end
return img
end
# Test
using Images
img = fill(Gray(255.0), 25, 25);
drawcircle!(img, Gray(0.0), 12, 12, 12) |
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).
| #Lua | Lua | function Bitmap:circle(x, y, r, c)
local dx, dy, err = r, 0, 1-r
while dx >= dy do
self:set(x+dx, y+dy, c)
self:set(x-dx, y+dy, c)
self:set(x+dx, y-dy, c)
self:set(x-dx, y-dy, c)
self:set(x+dy, y+dx, c)
self:set(x-dy, y+dx, c)
self:set(x+dy, y-dx, c)
self:set(x-dy, y-dx, c)
dy = dy + 1
if err < 0 then
err = err + 2 * dy + 1
else
dx, err = dx-1, err + 2 * (dy - dx) + 1
end
end
end |
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).
| #FreeBASIC | FreeBASIC | ' version 01-11-2016
' compile with: fbc -s console
' translation from Bitmap/Bresenham's line algorithm C entry
Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, _
Col As UInteger = &HFFFFFF)
Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0)
Dim As Integer sx = IIf(x0 < x1, 1, -1)
Dim As Integer sy = IIf(y0 < y1, 1, -1)
Dim As Integer er = IIf(dx > dy, dx, -dy) \ 2, e2
Do
PSet(x0, y0), col
If (x0 = x1) And (y0 = y1) Then Exit Do
e2 = er
If e2 > -dx Then Er -= dy : x0 += sx
If e2 < dy Then Er += dx : y0 += sy
Loop
End Sub
' Bitmap/Bézier curves/Cubic BBC BASIC entry
Sub beziercubic(x1 As Double, y1 As Double, x2 As Double, y2 As Double, _
x3 As Double, y3 As Double, x4 As Double, y4 As Double, _
n As ULong, col As UInteger = &HFFFFFF)
Type point_
x As Integer
y As Integer
End Type
Dim As ULong i
Dim As Double t, t1, a, b, c, d
Dim As point_ p(n)
For i = 0 To n
t = i / n
t1 = 1 - t
a = t1 ^ 3
b = t * t1 * t1 * 3
c = t * t * t1 * 3
d = t ^ 3
p(i).x = Int(a * x1 + b * x2 + c * x3 + d * x4 + .5)
p(i).y = Int(a * y1 + b * y2 + c * y3 + d * y4 + .5)
Next
For i = 0 To n -1
Br_line(p(i).x, p(i).y, p(i +1).x, p(i +1).y, col)
Next
End Sub
' ------=< MAIN >=------
ScreenRes 250,250,32 ' 0,0 in top left corner
beziercubic(160, 150, 10, 120, 30, 0, 150, 50, 20)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #11l | 11l | F biorhythms(birthdate_str, targetdate_str)
‘
Print out biorhythm data for targetdate assuming you were
born on birthdate.
birthdate and targetdata are strings in this format:
YYYY-MM-DD e.g. 1964-12-26
’
print(‘Born: ’birthdate_str‘ Target: ’targetdate_str)
V birthdate = time:strptime(birthdate_str, ‘%Y-%m-%d’)
V targetdate = time:strptime(targetdate_str, ‘%Y-%m-%d’)
V days = (targetdate - birthdate).days()
print(‘Day: ’days)
V cycle_labels = [‘Physical’, ‘Emotional’, ‘Mental’]
V cycle_lengths = [23, 28, 33]
V quadrants = [(‘up and rising’, ‘peak’), (‘up but falling’, ‘transition’), (‘down and falling’, ‘valley’), (‘down but rising’, ‘transition’)]
L(i) 3
V label = cycle_labels[i]
V length = cycle_lengths[i]
V position = days % length
V quadrant = Int(floor((4 * position) / length))
V percentage = Int(round(100 * sin(2 * math:pi * position / length), 0))
V transition_date = (targetdate + TimeDelta(days' floor((quadrant + 1) / 4 * length) - position)).strftime(‘%Y-%m-%d’)
V (trend, next) = quadrants[quadrant]
String description
I percentage > 95
description = ‘peak’
E I percentage < -95
description = ‘valley’
E I abs(percentage) < 5
description = ‘critical transition’
E
description = percentage‘% (’trend‘, next ’next‘ ’transition_date‘)’
print(label‘ day ’position‘: ’description)
biorhythms(‘2043-03-09’, ‘2072-07-11’) |
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.)
| #Visual_Basic_.NET | Visual Basic .NET | Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)
Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height)
Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)
Dim bytes(bufferSize - 1) As Byte
Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)
Dim index As Integer = header.Length
For y As Integer = 0 To rasterBitmap.Height - 1
For x As Integer = 0 To rasterBitmap.Width - 1
Dim color As Rgb = rasterBitmap.GetPixel(x, y)
bytes(index) = color.R
bytes(index + 1) = color.G
bytes(index + 2) = color.B
index += 3
Next
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub |
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.
| #Ada | Ada | procedure Line (Picture : in out Image; Start, Stop : Point; Color : Pixel) is
DX : constant Float := abs Float (Stop.X - Start.X);
DY : constant Float := abs Float (Stop.Y - Start.Y);
Err : Float;
X : Positive := Start.X;
Y : Positive := Start.Y;
Step_X : Integer := 1;
Step_Y : Integer := 1;
begin
if Start.X > Stop.X then
Step_X := -1;
end if;
if Start.Y > Stop.Y then
Step_Y := -1;
end if;
if DX > DY then
Err := DX / 2.0;
while X /= Stop.X loop
Picture (X, Y) := Color;
Err := Err - DY;
if Err < 0.0 then
Y := Y + Step_Y;
Err := Err + DX;
end if;
X := X + Step_X;
end loop;
else
Err := DY / 2.0;
while Y /= Stop.Y loop
Picture (X, Y) := Color;
Err := Err - DX;
if Err < 0.0 then
X := X + Step_X;
Err := Err + DY;
end if;
Y := Y + Step_Y;
end loop;
end if;
Picture (X, Y) := Color; -- Ensure dots to be drawn
end Line; |
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.23 | C# |
using System;
using System.Linq;
using System.Security.Cryptography;
using NUnit.Framework;
namespace BitcoinValidator
{
public class ValidateTest
{
[TestCase]
public void ValidateBitcoinAddressTest()
{
Assert.IsTrue(ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // VALID
Assert.IsTrue(ValidateBitcoinAddress("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9")); // VALID
Assert.Throws<Exception>(() => ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X")); // checksum changed, original data
Assert.Throws<Exception>(() => ValidateBitcoinAddress("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // data changed, original checksum
Assert.Throws<Exception>(() => ValidateBitcoinAddress("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // invalid chars
Assert.Throws<Exception>(() => ValidateBitcoinAddress("BZbvjr")); // checksum is fine, address too short
}
public static bool ValidateBitcoinAddress(string address)
{
if (address.Length < 26 || address.Length > 35) throw new Exception("wrong length");
var decoded = DecodeBase58(address);
var d1 = Hash(decoded.SubArray(0, 21));
var d2 = Hash(d1);
if (!decoded.SubArray(21, 4).SequenceEqual(d2.SubArray(0, 4))) throw new Exception("bad digest");
return true;
}
const string Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const int Size = 25;
private static byte[] DecodeBase58(string input)
{
var output = new byte[Size];
foreach (var t in input)
{
var p = Alphabet.IndexOf(t);
if (p == -1) throw new Exception("invalid character found");
var j = Size;
while (--j > 0)
{
p += 58 * output[j];
output[j] = (byte)(p % 256);
p /= 256;
}
if (p != 0) throw new Exception("address too long");
}
return output;
}
private static byte[] Hash(byte[] bytes)
{
var hasher = new SHA256Managed();
return hasher.ComputeHash(bytes);
}
}
public static class ArrayExtensions
{
public static T[] SubArray<T>(this T[] data, int index, int length)
{
var result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
}
}
|
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
| #Haskell | Haskell | import Numeric (showIntAtBase)
import Data.List (unfoldr)
import Data.Binary (Word8)
import Crypto.Hash.SHA256 as S (hash)
import Crypto.Hash.RIPEMD160 as R (hash)
import Data.ByteString (unpack, pack)
publicPointToAddress :: Integer -> Integer -> String
publicPointToAddress x y =
let toBytes x = reverse $ unfoldr (\b -> if b == 0 then Nothing else Just (fromIntegral $ b `mod` 256, b `div` 256)) x
ripe = 0 : unpack (R.hash $ S.hash $ pack $ 4 : toBytes x ++ toBytes y)
ripe_checksum = take 4 $ unpack $ S.hash $ S.hash $ pack ripe
addressAsList = ripe ++ ripe_checksum
address = foldl (\v b -> v * 256 + fromIntegral b) 0 addressAsList
base58Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
in showIntAtBase 58 (base58Digits !!) address ""
main = print $ publicPointToAddress
0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
|
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
| #Julia | Julia | const digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
function encodebase58(b::Vector{<:Integer})
out = Vector{Char}(34)
for j in endof(out):-1:1
local c::Int = 0
for i in eachindex(b)
c = c * 256 + b[i]
b[i] = c ÷ 58
c %= 58
end
out[j] = digits[c + 1]
end
local i = 1
while i < endof(out) && out[i] == '1'
i += 1
end
return join(out[i:end])
end
const COINVER = 0x00
function pubpoint2address(x::Vector{UInt8}, y::Vector{UInt8})
c = vcat(0x04, x, y)
c = vcat(COINVER, digest("ripemd160", sha256(c)))
d = sha256(sha256(c))
return encodebase58(vcat(c, d[1:4]))
end
pubpoint2address(x::AbstractString, y::AbstractString) =
pubpoint2address(hex2bytes(x), hex2bytes(y)) |
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.
| #E | E | 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)
} |
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
| #Elm | Elm |
--True and False directly represent Boolean values in Elm
--For eg to show yes for true and no for false
if True then "yes" else "no"
--Same expression differently
if False then "no" else "yes"
--This you can run as a program
--Elm allows you to take anything you want for representation
--In the program we take T for true F for false
import Html exposing(text,div,Html)
import Html.Attributes exposing(style)
type Expr = T | F | And Expr Expr | Or Expr Expr | Not Expr
evaluate : Expr->Bool
evaluate expression =
case expression of
T ->
True
F ->
False
And expr1 expr2 ->
evaluate expr1 && evaluate expr2
Or expr1 expr2 ->
evaluate expr1 || evaluate expr2
Not expr ->
not (evaluate expr)
--CHECKING RANDOM LOGICAL EXPRESSIONS
ex1= Not F
ex2= And T F
ex3= And (Not(Or T F)) T
main =
div [] (List.map display [ex1, ex2, ex3])
display expr=
div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ]
--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
| #Emacs_Lisp | Emacs Lisp | 1> 1 < 2.
true
2> 1 < 1.
false
3> 0 == false.
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
| #Vala | Vala | static void println(string str) {
stdout.printf("%s\r\n", str);
}
static unichar encrypt_char(unichar ch, int code) {
if (!ch.isalpha()) return ch;
unichar offset = ch.isupper() ? 'A' : 'a';
return (unichar)((ch + code - offset) % 26 + offset);
}
static string encrypt(string input, int code) {
var builder = new StringBuilder();
unichar c;
for (int i = 0; input.get_next_char(ref i, out c);) {
builder.append_unichar(encrypt_char(c, code));
}
return builder.str;
}
static string decrypt(string input, int code) {
return encrypt(input, 26 - code);
}
const string test_case = "The quick brown fox jumped over the lazy dog";
void main() {
println(test_case);
println(encrypt(test_case, -1));
println(decrypt(encrypt(test_case, -1), -1));
} |
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)..
| #Clojure | Clojure | (ns boxing-the-compass
(:use [clojure.string :only [capitalize]]))
(def headings
(for [i (range 0 (inc 32))]
(let [heading (* i 11.25)]
(case (mod i 3)
1 (+ heading 5.62)
2 (- heading 5.62)
heading))))
(defn angle2compass
[angle]
(let [dirs ["N" "NbE" "N-NE" "NEbN" "NE" "NEbE" "E-NE" "EbN"
"E" "EbS" "E-SE" "SEbE" "SE" "SEbS" "S-SE" "SbE"
"S" "SbW" "S-SW" "SWbS" "SW" "SWbW" "W-SW" "WbS"
"W" "WbN" "W-NW" "NWbW" "NW" "NWbN" "N-NW" "NbW"]
unpack {\N "north" \E "east" \W "west" \S "south" \b " by " \- "-"}
sep (/ 360 (count dirs))
dir (int (/ (mod (+ angle (/ sep 2)) 360) sep))]
(capitalize (apply str (map unpack (dirs dir))))))
(print
(apply str (map-indexed #(format "%2s %-18s %7.2f\n"
(inc (mod %1 32)) (angle2compass %2) %2)
headings))) |
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.
| #Ruby | Ruby | class Pixmap
def histogram
histogram = Hash.new(0)
@height.times do |y|
@width.times do |x|
histogram[self[x,y].luminosity] += 1
end
end
histogram
end
def to_blackandwhite
hist = histogram
# find the median luminosity
median = nil
sum = 0
hist.keys.sort.each do |lum|
sum += hist[lum]
if sum > @height * @width / 2
median = lum
break
end
end
# create the black and white image
bw = self.class.new(@width, @height)
@height.times do |y|
@width.times do |x|
bw[x,y] = self[x,y].luminosity < median ? RGBColour::BLACK : RGBColour::WHITE
end
end
bw
end
def save_as_blackandwhite(filename)
to_blackandwhite.save(filename)
end
end
Pixmap.open('file.ppm').save_as_blackandwhite('file_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.
| #Rust | Rust | extern crate image;
use image::{DynamicImage, GenericImageView, ImageBuffer, Rgba};
/// index of the alpha channel in RGBA
const ALPHA: usize = 3;
/// Computes the luminance of a single pixel
/// Result lies within `u16::MIN..u16::MAX`
const fn luminance(rgba: Rgba<u8>) -> u16 {
let Rgba([r, g, b, _a]) = rgba;
55 * r as u16 + 183 * g as u16 + 19 * b as u16
}
/// computes the median of a given histogram
/// Result lies within `u16::MIN..u16::MAX`
fn get_median(total: usize, histogram: &[usize]) -> u16 {
let mut sum = 0;
for (index, &count) in histogram.iter().enumerate() {
sum += count;
if sum >= total / 2 {
return index as u16;
}
}
u16::MAX
}
/// computes the histogram of a given image
fn compute_histogram(img: &DynamicImage) -> Vec<usize> {
let mut histogram = vec![0; 1 << u16::BITS];
img.pixels()
.map(|(_x, _y, pixel)| luminance(pixel))
.for_each(|luminance| histogram[luminance as usize] += 1);
histogram
}
/// returns a black or white pixel with an alpha value
const fn black_white(is_white: bool, alpha: u8) -> [u8; 4] {
if is_white {
[255, 255, 255, alpha]
} else {
[0, 0, 0, alpha]
}
}
/// create a monochome compy of the given image
/// preserves alpha data
fn convert_to_monochrome(img: &DynamicImage) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
let histogram = compute_histogram(img);
let (width, height) = img.dimensions();
let pixel_count = (width * height) as usize;
let median = get_median(pixel_count, &histogram);
let pixel_buffer = img.pixels()
.flat_map(|(_x, _y, pixel)| black_white(luminance(pixel) > median, pixel[ALPHA]))
.collect();
ImageBuffer::from_vec(width, height, pixel_buffer).unwrap_or_else(|| unreachable!())
}
fn main() {
let img = image::open("lena.jpg").expect("could not load image file");
let img = convert_to_monochrome(&img);
img.save("lena-mono.png").expect("could not save result image");
}
|
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program binarydigit.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/* Initialized data */
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusif Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultLsl: .asciz "Result of left shift : \n"
szMessResultLsr: .asciz "Result of right shift : \n"
szMessResultAsr: .asciz "Result of Arithmetic right shift : \n"
szMessResultRor: .asciz "Result of rotate right : \n"
szMessResultRrx: .asciz "Result of rotate right with extend : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
sMessAffBin: .ascii "Register value : "
sZoneBin: .space 36,' '
.asciz "\n"
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* save des 2 registres */
ldr r0,iAdrszMessResultAnd
bl affichageMess
mov r0,#5
and r0,#15
bl affichage2
ldr r0,iAdrszMessResultOr
bl affichageMess
mov r0,#5
orr r0,#15
bl affichage2
ldr r0,iAdrszMessResultEor
bl affichageMess
mov r0,#5
eor r0,#15
bl affichage2
ldr r0,iAdrszMessResultNot
bl affichageMess
mov r0,#5
mvn r0,r0
bl affichage2
ldr r0,iAdrszMessResultLsl
bl affichageMess
mov r0,#5
lsl r0,#1
bl affichage2
ldr r0,iAdrszMessResultLsr
bl affichageMess
mov r0,#5
lsr r0,#1
bl affichage2
ldr r0,iAdrszMessResultAsr
bl affichageMess
mov r0,#-5
bl affichage2
mov r0,#-5
asr r0,#1
bl affichage2
ldr r0,iAdrszMessResultRor
bl affichageMess
mov r0,#5
ror r0,#1
bl affichage2
ldr r0,iAdrszMessResultRrx
bl affichageMess
mov r0,#5
mov r1,#15
rrx r0,r1
bl affichage2
ldr r0,iAdrszMessResultClear
bl affichageMess
mov r0,#5
bic r0,#0b100 @ clear 3ieme bit
bl affichage2
bic r0,#4 @ clear 3ieme bit ( 4 = 100 binary)
bl affichage2
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszMessResultAnd: .int szMessResultAnd
iAdrszMessResultOr: .int szMessResultOr
iAdrszMessResultEor: .int szMessResultEor
iAdrszMessResultNot: .int szMessResultNot
iAdrszMessResultLsl: .int szMessResultLsl
iAdrszMessResultLsr: .int szMessResultLsr
iAdrszMessResultAsr: .int szMessResultAsr
iAdrszMessResultRor: .int szMessResultRor
iAdrszMessResultRrx: .int szMessResultRrx
iAdrszMessResultClear: .int szMessResultClear
/******************************************************************/
/* register display in binary */
/******************************************************************/
/* r0 contains the register */
affichage2:
push {r0,lr} /* save registers */
push {r1-r5} /* save others registers */
mrs r5,cpsr /* saves state register in r5 */
ldr r1,iAdrsZoneBin
mov r2,#0 @ read bit position counter
mov r3,#0 @ position counter of the written character
1: @ loop
lsls r0,#1 @ left shift with flags
movcc r4,#48 @ flag carry off character '0'
movcs r4,#49 @ flag carry on character '1'
strb r4,[r1,r3] @ character -> display zone
add r2,r2,#1 @ + 1 read bit position counter
add r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#8 @ 8 bits read
addeq r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#16 @ etc
addeq r3,r3,#1
cmp r2,#24
addeq r3,r3,#1
cmp r2,#31 @ 32 bits shifted ?
ble 1b @ no -> loop
ldr r0,iAdrsZoneMessBin @ address of message result
bl affichageMess @ display result
100:
msr cpsr,r5 /*restaur state register */
pop {r1-r5} /* restaur others registers */
pop {r0,lr}
bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system write */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
|
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).
| #Ruby | Ruby | Define cubic(p1,p2,p3,segs) = Prgm
Local i,t,u,prev,pt
0 → pt
For i,1,segs+1
(i-1.0)/segs → t © Decimal to avoid slow exact arithetic
(1-t) → u
pt → prev
u^2*p1 + 2*t*u*p2 + t^2*p3 → pt
If i>1 Then
PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2])
EndIf
EndFor
EndPrgm |
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).
| #Tcl | Tcl | Define cubic(p1,p2,p3,segs) = Prgm
Local i,t,u,prev,pt
0 → pt
For i,1,segs+1
(i-1.0)/segs → t © Decimal to avoid slow exact arithetic
(1-t) → u
pt → prev
u^2*p1 + 2*t*u*p2 + t^2*p3 → pt
If i>1 Then
PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2])
EndIf
EndFor
EndPrgm |
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).
| #TI-89_BASIC | TI-89 BASIC | Define cubic(p1,p2,p3,segs) = Prgm
Local i,t,u,prev,pt
0 → pt
For i,1,segs+1
(i-1.0)/segs → t © Decimal to avoid slow exact arithetic
(1-t) → u
pt → prev
u^2*p1 + 2*t*u*p2 + t^2*p3 → pt
If i>1 Then
PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2])
EndIf
EndFor
EndPrgm |
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).
| #Vedit_macro_language | Vedit macro language | // Daw a Cubic bezier curve
// #20, #30 = Start point
// #21, #31 = Control point 1
// #22, #32 = Control point 2
// #23, #33 = end point
// #40 = depth of recursion
:CUBIC_BEZIER:
if (#40 > 0) {
#24 = (#20+#21)/2; #34 = (#30+#31)/2
#26 = (#22+#23)/2; #36 = (#32+#33)/2
#27 = (#20+#21*2+#22)/4; #37 = (#30+#31*2+#32)/4
#28 = (#21+#22*2+#23)/4; #38 = (#31+#32*2+#33)/4
#29 = (#20+#21*3+#22*3+#23)/8; #39 = (#30+#31*3+#32*3+#33)/8
Num_Push(20,40)
#21 = #24; #31 = #34 // control 1
#22 = #27; #32 = #37 // control 2
#23 = #29; #33 = #39 // end point
#40--
Call("CUBIC_BEZIER") // Draw "left" part
Num_Pop(20,40)
Num_Push(20,40)
#20 = #29; #30 = #39 // start point
#21 = #28; #31 = #38 // control 1
#22 = #26; #32 = #36 // control 2
#40--
Call("CUBIC_BEZIER") // Draw "right" part
Num_Pop(20,40)
} else {
#1=#20; #2=#30; #3=#23; #4=#33
Call("DRAW_LINE")
}
return |
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).
| #Kotlin | Kotlin | // version 1.1.4-3
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.JOptionPane
import javax.swing.JLabel
import javax.swing.ImageIcon
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 drawCircle(bbs: BasicBitmapStorage, centerX: Int, centerY: Int, radius: Int, circleColor: Color) {
var d = (5 - radius * 4) / 4
var x = 0
var y = radius
do {
with(bbs) {
setPixel(centerX + x, centerY + y, circleColor)
setPixel(centerX + x, centerY - y, circleColor)
setPixel(centerX - x, centerY + y, circleColor)
setPixel(centerX - x, centerY - y, circleColor)
setPixel(centerX + y, centerY + x, circleColor)
setPixel(centerX + y, centerY - x, circleColor)
setPixel(centerX - y, centerY + x, circleColor)
setPixel(centerX - y, centerY - x, circleColor)
}
if (d < 0) {
d += 2 * x + 1
}
else {
d += 2 * (x - y) + 1
y--
}
x++
}
while (x <= y)
}
fun main(args: Array<String>) {
val bbs = BasicBitmapStorage(400, 400)
bbs.fill(Color.pink)
drawCircle(bbs, 200, 200, 100, Color.black)
drawCircle(bbs, 200, 200, 50, Color.white)
val label = JLabel(ImageIcon(bbs.image))
val title = "Bresenham's circle algorithm"
JOptionPane.showMessageDialog(null, label, title, JOptionPane.PLAIN_MESSAGE)
} |
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).
| #Go | Go | package raster
const b3Seg = 30
func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {
var px, py [b3Seg + 1]int
fx1, fy1 := float64(x1), float64(y1)
fx2, fy2 := float64(x2), float64(y2)
fx3, fy3 := float64(x3), float64(y3)
fx4, fy4 := float64(x4), float64(y4)
for i := range px {
d := float64(i) / b3Seg
a := 1 - d
b, c := a * a, d * d
a, b, c, d = a*b, 3*b*d, 3*a*c, c*d
px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)
py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)
}
x0, y0 := px[0], py[0]
for i := 1; i <= b3Seg; i++ {
x1, y1 := px[i], py[i]
b.Line(x0, y0, x1, y1, p)
x0, y0 = x1, y1
}
}
func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {
b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())
} |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
} |
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.)
| #Wren | Wren | import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
class Bitmap {
construct new(name, width, height) {
Window.title = name
Window.resize(width, height)
Canvas.resize(width, height)
_bmp = ImageData.create(name, width, height)
// create bitmap
for (y in 0...height) {
for (x in 0...width) {
var c = Color.rgb(x % 256, y % 256, (x * y) % 256)
pset(x, y, c)
}
}
_w = width
_h = height
}
init() {
// write bitmap to a PPM file
var ppm = "P6\n%(_w) %(_h)\n255\n"
for (y in 0..._h) {
for (x in 0..._w) {
var c = pget(x, y)
ppm = ppm + String.fromByte(c.r)
ppm = ppm + String.fromByte(c.g)
ppm = ppm + String.fromByte(c.b)
}
}
FileSystem.save("output.ppm", ppm)
Process.exit(0)
}
pset(x, y, col) { _bmp.pset(x, y, col) }
pget(x, y) { _bmp.pget(x, y) }
update() {}
draw(alpha) {}
}
var Game = Bitmap.new("Bitmap - write to PPM file", 320, 320) |
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.
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID:
BEGIN
REAL dx = ABS (x OF stop - x OF start),
dy = ABS (y OF stop - y OF start);
REAL err;
POINT here := start,
step := (1, 1);
IF x OF start > x OF stop THEN
x OF step := -1
FI;
IF y OF start > y OF stop THEN
y OF step := -1
FI;
IF dx > dy THEN
err := dx / 2;
WHILE x OF here /= x OF stop DO
picture[x OF here, y OF here] := color;
err -:= dy;
IF err < 0 THEN
y OF here +:= y OF step;
err +:= dx
FI;
x OF here +:= x OF step
OD
ELSE
err := dy / 2;
WHILE y OF here /= y OF stop DO
picture[x OF here, y OF here] := color;
err -:= dx;
IF err < 0 THEN
x OF here +:= x OF step;
err +:= dy
FI;
y OF here +:= y OF step
OD
FI;
picture[x OF here, y OF here] := color # ensure dots to be drawn #
END # line #;
SKIP |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #11l | 11l | UInt32 seed = 0
F nonrandom(n)
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) % n
F nonrandom_choice(lst)
R lst[nonrandom(lst.len)]
F basecount(dna)
DefaultDict[Char, Int] d
L(c) dna
d[c]++
R sorted(d.items())
F seq_split(dna, n = 50)
R (0 .< dna.len).step(n).map(i -> @dna[i .< i + @n])
F seq_pp(dna, n = 50)
L(part) seq_split(dna, n)
print(‘#5: #.’.format(L.index * n, part))
print("\n BASECOUNT:")
V tot = 0
L(base, count) basecount(dna)
print(‘ #3: #.’.format(base, count))
tot += count
V (base, count) = (‘TOT’, tot)
print(‘ #3= #.’.format(base, count))
F seq_mutate(String =dna; count = 1, kinds = ‘IDSSSS’, choice = ‘ATCG’)
[(String, Int)] mutation
V k2txt = [‘I’ = ‘Insert’, ‘D’ = ‘Delete’, ‘S’ = ‘Substitute’]
L 0 .< count
V kind = nonrandom_choice(kinds)
V index = nonrandom(dna.len + 1)
I kind == ‘I’
dna = dna[0 .< index]‘’nonrandom_choice(choice)‘’dna[index..]
E I kind == ‘D’ & !dna.empty
dna = dna[0 .< index]‘’dna[index+1..]
E I kind == ‘S’ & !dna.empty
dna = dna[0 .< index]‘’nonrandom_choice(choice)‘’dna[index+1..]
mutation.append((k2txt[kind], index))
R (dna, mutation)
print(‘SEQUENCE:’)
V sequence = ‘TCAATCATTAATCGATTAATACATTCAATTTGAACATCTCCAGGAGAAGGCAGGGTAATCTCGTGTAGCCGTGCTTGGGGCCTCCGATATGGCCGGGGAATTTCAAAGTATAGTGTGCATCCCCTCATAATACATAGATCTATAGGTAAGTATATGGGTTGACGTTGTTAGATGCGATACACGTGCACACTTTATGAATTTTACGTTCCTCTGCCTAGAGTGCCAAGTTTCAATTTGCTACGGTTCCTCA’
seq_pp(sequence)
print("\n\nMUTATIONS:")
V (mseq, m) = seq_mutate(sequence, 10)
L(kind, index) m
print(‘ #10 @#.’.format(kind, index))
print()
seq_pp(mseq) |
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.
| #D | D | import std.stdio, std.algorithm, std.array, std.string, sha_256_2;
struct A25 {
// Type for a 25 ubyte (not base58 encoded) bitcoin address.
ubyte[25] enc;
ubyte bitcoinVersion() const pure nothrow @safe @nogc {
return enc[0];
}
ubyte[4] embeddedChecksum() return const pure nothrow @safe @nogc {
return enc[$ - 4 .. $];
}
/** Computes a double sha256 hash of the first 21 bytes of
the address. Returns the full 32 ubyte sha256 hash. */
ubyte[32] doubleSHA256() const pure nothrow @nogc {
return SHA256.digest(SHA256.digest(enc[0 .. 21]));
}
/** Returns a four ubyte checksum computed from the first 21
bytes of the address. */
ubyte[4] computeChecksum() const pure nothrow @nogc {
return doubleSHA256[0 .. 4];
}
/** Takes a base58 encoded address and decodes it into the
receiver. Errors are returned if the argument is not valid base58
or if the decoded value does not fit in the 25 ubyte address.
The address is not otherwise checked for validity. */
string set58(in ubyte[] s) pure nothrow @safe @nogc {
static immutable digits =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
.representation;
static assert(digits.length == 58);
foreach (immutable char s1; s) {
immutable c = digits.countUntil(s1);
if (c < 0)
return "found a bad char in the Bitcoin address.";
// Currently the D type system can't see c as nonegative.
uint uc = (c < 0) ? 0 : c;
foreach_reverse (ref aj; enc) {
uc += digits.length * aj;
aj = uc % 256;
uc /= 256;
}
if (uc > 0)
return "too long Bitcoin address.";
}
return null;
}
}
/** Validates a base58 encoded bitcoin address. An address is valid
if it can be decoded into a 25 ubyte address, the Version number is 0,
and the checksum validates. Return value ok will be true for valid
addresses. If ok is false, the address is invalid and the error value
may indicate why. */
string isValidA58(in ubyte[] a58) pure nothrow @nogc {
A25 a;
immutable err = a.set58(a58);
if (!err.empty)
return err;
if (a.bitcoinVersion != 0)
return "not Bitcoin version 0.";
return (a.embeddedChecksum == a.computeChecksum) ? null :
"checksums don't match.";
}
void main() {
immutable tests = ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz"];
foreach (immutable test; tests) {
immutable err = test.representation.isValidA58;
writefln(`"%s": %s`, test, err.empty ? "OK." : err);
}
} |
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
| #Wolfram_Language.2FMathematica | Wolfram Language/Mathematica | BlockchainKeyEncode[
PublicKey[
<|
"Type"->"EllipticCurve",
"PublicCurvePoint"-> {
16^^50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352,
16^^2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
}
|>
],
"Address",
BlockchainBase-> "Bitcoin"
] |
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
| #Nim | Nim | import parseutils
import nimcrypto
import bignum
func base58Encode(data: seq[byte]): string =
## Encode data to base58 with at most one starting '1'.
var data = data
const Base = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
result.setlen(34)
# Convert to base 58.
for j in countdown(result.high, 0):
var c = 0
for i, b in data:
c = c * 256 + b.int
data[i] = (c div 58).byte
c = c mod 58
result[j] = Base[c]
# Keep one starting '1' at most.
if result[0] == '1':
for idx in 1..result.high:
if result[idx] != '1':
result = result[(idx - 1)..^1]
break
func hexToByteSeq(s: string): seq[byte] =
## Convert a hexadecimal string to a sequence of bytes.
var pos = 0
while pos < s.len:
var tmp = 0
let parsed = parseHex(s, tmp, pos, 2)
if parsed > 0:
inc pos, parsed
result.add byte tmp
else:
raise newException(ValueError, "Invalid hex string")
func validCoordinates(x, y: string): bool =
## Return true if the coordinates are those of a point in the secp256k1 elliptic curve.
let p = newInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
let x = newInt(x, 16)
let y = newInt(y, 16)
result = y^2 mod p == (x^3 + 7) mod p
func addrEncode(x, y: string): string =
## Encode x and y coordinates to an address.
if not validCoordinates(x, y):
raise newException(ValueError, "Invalid coordinates")
let pubPoint = 4u8 & x.hexToByteSeq & y.hexToByteSeq
if pubPoint.len != 65:
raise newException(ValueError, "Invalid pubpoint string")
var rmd = @(ripemd160.digest(sha256.digest(pubPoint).data).data)
rmd.insert 0u8
rmd.add sha256.digest(sha256.digest(rmd).data).data[0..3]
result = base58Encode(rmd)
when isMainModule:
let address = addrEncode("50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
echo "Coordinates are valid."
echo "Address is: ", address |
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
| #Perl | Perl |
use Crypt::RIPEMD160;
use Digest::SHA qw(sha256);
use Encode::Base58::GMP;
sub public_point_to_address {
my $ec = join '', '04', @_; # EC: concat x and y to one string and prepend '04' magic value
my $octets = pack 'C*', map { hex } unpack('(a2)65', $ec); # transform the hex values string to octets
my $hash = chr(0) . Crypt::RIPEMD160->hash(sha256 $octets); # perform RIPEMD160(SHA256(octets)
my $checksum = substr sha256(sha256 $hash), 0, 4; # build the checksum
my $hex = join '', '0x', # build hex value of hash and checksum
map { sprintf "%02X", $_ }
unpack 'C*', $hash.$checksum;
return '1' . sprintf "%32s", encode_base58($hex, 'bitcoin'); # Do the Base58 encoding, prepend "1"
}
say public_point_to_address
'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'
;
|
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.
| #ERRE | ERRE |
PROGRAM MYFILL_DEMO
!VAR SP%
!$INTEGER
CONST IMAGE_WIDTH=320,IMAGE_HEIGHT=200
DIM STACK[6000,1]
FUNCTION QUEUE_COUNT(X)
QUEUE_COUNT=SP
END FUNCTION
!$INCLUDE="PC.LIB"
PROCEDURE QUEUE_INIT
SP=0
END PROCEDURE
PROCEDURE QUEUE_POP(->XX,YY)
XX=STACK[SP,0]
YY=STACK[SP,1]
SP=SP-1
END PROCEDURE
PROCEDURE QUEUE_PUSH(XX,YY)
SP=SP+1
STACK[SP,0]=XX
STACK[SP,1]=YY
END PROCEDURE
PROCEDURE FLOOD_FILL(XSTART,YSTART,COLORE_PRIMA,COLORE_RIEMP)
LOCAL XEST,XWEST,YNORD,YSUD,X,Y
QUEUE_INIT
QUEUE_PUSH(XSTART,YSTART)
WHILE (QUEUE_COUNT(0)>0) DO
QUEUE_POP(->X,Y)
XWEST=X
XEST=X
IF Y>0 THEN
YNORD=Y-1
ELSE
YNORD=-1
END IF
IF Y<IMAGE_HEIGHT-1 THEN
YSUD=Y+1
ELSE
YSUD=-1
END IF
LOOP
POINT(XEST+1,Y->ZC%)
EXIT IF NOT((XEST<IMAGE_WIDTH-1) AND (ZC%=COLORE_PRIMA))
XEST=XEST+1
END LOOP
LOOP
POINT(XWEST-1,Y->ZC%)
EXIT IF NOT((XWEST>0) AND (ZC%=COLORE_PRIMA))
XWEST=XWEST-1
END LOOP
FOR X=XWEST TO XEST DO
PSET(X,Y,COLORE_RIEMP)
POINT(X,YNORD->ZC%)
IF YNORD>=0 AND ZC%=COLORE_PRIMA THEN
QUEUE_PUSH(X,YNORD)
END IF
POINT(X,YSUD->ZC%)
IF YSUD>=0 AND ZC%=COLORE_PRIMA THEN
QUEUE_PUSH(X,YSUD)
END IF
END FOR
END WHILE
END PROCEDURE ! Flood_Fill
BEGIN
SCREEN(1)
CIRCLE(100,100,75,2)
CIRCLE(120,120,20,2)
CIRCLE(80,80,15,2)
CIRCLE(120,80,10,2)
FLOOD_FILL(100,100,0,1)
END PROGRAM
|
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.
| #Euler_Math_Toolbox | Euler Math Toolbox |
>file="test.png";
>A=loadrgb(file); ...
>insrgb(A);
>function floodfill (A0,i,j,color,dist) ...
$ A=A0;
$ R=getred(A); G=getgreen(A); B=getblue(A);
$ d=sqrt((R-R[i,j])^2+(G-G[i,j])^2+(B-B[i,j])^2);
$ n=rows(A); m=cols(A);
$ V=zeros(n,m);
$ S=zeros(n*m,2); sn=0;
$ A[i,j]=color; V[i,j]=1;
$ repeat;
$ if fill(A,i+1,j,n,m,d,dist,V,S,sn,color) then i=i+1; continue;
$ elseif fill(A,i,j+1,n,m,d,dist,V,S,sn,color) then j=j+1; continue;
$ elseif fill(A,i-1,j,n,m,d,dist,V,S,sn,color) then i=i-1; continue;
$ elseif fill(A,i,j-1,n,m,d,dist,V,S,sn,color) then j=j-1; continue;
$ endif;
$ sn=sn-1; if sn==0 then break; endif;
$ i=S[sn,1]; j=S[sn,2];
$ end;
$ return A;
$endfunction
>function fill (A,i,j,n,m,d,dist,V,S,%sn,color) ...
$ if i<1 or i>n or j<1 or j>n then return 0; endif;
$ if V[i,j] || d[i,j]>dist then A[i,j]=color; return 0; endif;
$ V[i,j]=1;
$ A[i,j]=color;
$ %sn=%sn+1;
$ S[%sn]=[i,j];
$ return 1;
$endfunction
>B=floodfill(A,10,240,rgb(0.5,0,0),0.5);
>B=floodfill(B,10,10,rgb(0.5,0,0),0.5);
>B=floodfill(B,150,60,rgb(0,0.5,0),0.5);
>B=floodfill(B,200,200,rgb(0,0,0.5),0.5);
>insrgb(B);
|
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
| #Erlang | Erlang | 1> 1 < 2.
true
2> 1 < 1.
false
3> 0 == false.
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
| #Excel | Excel | =AND(A1;B1) |
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
| #VBA | VBA |
Option Explicit
Sub Main_Caesar()
Dim ch As String
ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14)
Debug.Print ch
Debug.Print Caesar_Cipher(ch, -14)
End Sub
Function Caesar_Cipher(sText As String, lngNumber As Long) As String
Dim Tbl, strGlob As String, strTemp As String, i As Long, bytAscii As Byte
Const MAJ As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const NB_LETTERS As Byte = 26
Const DIFFASCIIMAJ As Byte = 65 - NB_LETTERS
Const DIFFASCIIMIN As Byte = 97 - NB_LETTERS
strTemp = sText
If lngNumber < NB_LETTERS And lngNumber > NB_LETTERS * -1 Then
strGlob = String(NB_LETTERS * 4, " ")
LSet strGlob = MAJ & MAJ & MAJ
Tbl = Split(StrConv(strGlob, vbUnicode), Chr(0))
For i = 1 To Len(strTemp)
If Mid(strTemp, i, 1) Like "[a-zA-Z]" Then
bytAscii = Asc(Mid(strTemp, i, 1))
If Mid(strTemp, i, 1) = Tbl(bytAscii - DIFFASCIIMAJ) Then
Mid(strTemp, i) = Tbl(bytAscii - DIFFASCIIMAJ + lngNumber)
Else
Mid(strTemp, i) = LCase(Tbl(bytAscii - DIFFASCIIMIN + lngNumber))
End If
End If
Next i
End If
Caesar_Cipher = strTemp
End Function
|
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)..
| #COBOL | COBOL | identification division.
program-id. box-compass.
data division.
working-storage section.
01 point pic 99.
01 degrees usage float-short.
01 degrees-rounded pic 999v99.
01 show-degrees pic zz9.99.
01 box pic z9.
01 fudge pic 9.
01 compass pic x(4).
01 compass-point pic x(18).
01 shortform pic x.
01 short-names.
05 short-name pic x(4) occurs 33 times.
01 overlay.
05 value "N " & "NbE " & "N-NE" & "NEbN" & "NE " &
"NEbE" & "E-NE" & "EbN " & "E " & "EbS " &
"E-SE" & "SEbE" & "SE " & "SEbS" & "S-SE" &
"SbE " & "S " & "SbW " & "S-SW" & "SWbS" &
"SW " & "SWbW" & "W-SW" & "WbS " & "W " &
"WbN " & "W-NW" & "NWbW" & "NW " & "NWbN" &
"N-NW" & "NbW " & "N ".
procedure division.
display "Index Compass point Degree"
move overlay to short-names.
perform varying point from 0 by 1 until point > 32
compute box = function mod(point 32) + 1
compute degrees = point * 11.25
compute fudge = function mod(point 3)
evaluate fudge
when equal 1
add 5.62 to degrees
when equal 2
subtract 5.62 from degrees
end-evaluate
compute degrees-rounded rounded = degrees
move degrees-rounded to show-degrees
inspect show-degrees replacing trailing '00' by '0 '
inspect show-degrees replacing trailing '50' by '5 '
move short-name(point + 1) to compass
move spaces to compass-point
display space box space space space with no advancing
perform varying tally from 1 by 1 until tally > 4
move compass(tally:1) to shortform
move function concatenate(function trim(compass-point),
function substitute(shortform,
"N", "North",
"E", "East",
"S", "South",
"W", "West",
"b", " byZ",
"-", "-"))
to compass-point
end-perform
move function substitute(compass-point, "Z", " ")
to compass-point
move function lower-case(compass-point) to compass-point
move function upper-case(compass-point(1:1))
to compass-point(1:1)
display compass-point space show-degrees
end-perform
goback. |
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.
| #Scala | Scala | object BitmapOps {
def histogram(bm:RgbBitmap)={
val hist=new Array[Int](255)
for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y)))
hist(l)+=1
hist
}
def histogram_median(hist:Array[Int])={
var from=0
var to=hist.size-1
var left=hist(from)
var right=hist(to)
while(from!=to){
if (left<right)
{from+=1; left+=hist(from)}
else
{to-=1; right+=hist(to)}
}
from
}
def monochrom(bm:RgbBitmap, threshold:Int)={
val image=new RgbBitmap(bm.width, bm.height)
val c1=Color.BLACK
val c2=Color.WHITE
for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y)))
image.setPixel(x, y, if(l>threshold) c2 else c1)
image
}
} |
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.
| #Arturo | Arturo | a: 255
b: 2
print [a "AND" b "=" and a b]
print [a "OR" b "=" or a b]
print [a "XOR" b "=" xor a b]
print ["NOT" a "=" not a]
print [a "SHL" b "=" shl a b]
print [a "SHR" b "=" shr 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).
| #Wren | Wren | import "graphics" for Canvas, ImageData, Color, Point
import "dome" for Window
class Game {
static bmpCreate(name, w, h) { ImageData.create(name, w, h) }
static bmpFill(name, col) {
var image = ImageData[name]
for (x in 0...image.width) {
for (y in 0...image.height) image.pset(x, y, col)
}
}
static bmpPset(name, x, y, col) { ImageData[name].pset(x, y, col) }
static bmpPget(name, x, y) { ImageData[name].pget(x, y) }
static bmpLine(name, x0, y0, x1, y1, col) {
var dx = (x1 - x0).abs
var dy = (y1 - y0).abs
var sx = (x0 < x1) ? 1 : -1
var sy = (y0 < y1) ? 1 : -1
var err = ((dx > dy ? dx : - dy) / 2).floor
while (true) {
bmpPset(name, x0, y0, col)
if (x0 == x1 && y0 == y1) break
var e2 = err
if (e2 > -dx) {
err = err - dy
x0 = x0 + sx
}
if (e2 < dy) {
err = err + dx
y0 = y0 + sy
}
}
}
static bmpQuadraticBezier(name, p1, p2, p3, col, n) {
var pts = List.filled(n+1, null)
for (i in 0..n) {
var t = i / n
var u = 1 - t
var a = u * u
var b = 2 * t * u
var c = t * t
var px = (a * p1.x + b * p2.x + c * p3.x).truncate
var py = (a * p1.y + b * p2.y + c * p3.y).truncate
pts[i] = Point.new(px, py, col)
}
for (i in 0...n) {
var j = i + 1
bmpLine(name, pts[i].x, pts[i].y, pts[j].x, pts[j].y, col)
}
}
static init() {
Window.title = "Quadratic Bézier curve"
var size = 320
Window.resize(size, size)
Canvas.resize(size, size)
var name = "quadratic"
var bmp = bmpCreate(name, size, size)
bmpFill(name, Color.white)
var p1 = Point.new( 10, 100)
var p2 = Point.new(250, 270)
var p3 = Point.new(150, 20)
bmpQuadraticBezier(name, p1, p2, p3, Color.darkpurple, 20)
bmp.draw(0, 0)
}
static update() {}
static draw(alpha) {}
} |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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 = [[background] * width] * height
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]
V bitmap = Bitmap(20, 10)
bitmap.fillrect(4, 5, 6, 3)
assert(bitmap.get(5, 5) == black)
assert(bitmap.get(0, 1) == white)
bitmap.set(0, 1, black)
assert(bitmap.get(0, 1) == black)
bitmap.chardisplay() |
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).
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | SetAttributes[drawcircle, HoldFirst];
drawcircle[img_, {x0_, y0_}, r_, color_: White] :=
Module[{f = 1 - r, ddfx = 1, ddfy = -2 r, x = 0, y = r,
pixels = {{0, r}, {0, -r}, {r, 0}, {-r, 0}}},
While[x < y,
If[f >= 0, y--; ddfy += 2; f += ddfy];
x++; ddfx += 2; f += ddfx;
pixels = Join[pixels, {{x, y}, {x, -y}, {-x, y}, {-x, -y},
{y, x}, {y, -x}, {-y, x}, {-y, -x}}]];
img = ReplacePixelValue[img, {x0, y0} + # -> color & /@ pixels]] |
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).
| #Modula-3 | Modula-3 | INTERFACE Circle;
IMPORT Bitmap;
PROCEDURE Draw(
img: Bitmap.T;
center: Bitmap.Point;
radius: CARDINAL;
color: Bitmap.Pixel);
END Circle. |
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).
| #J | J | require 'numeric'
bik=: 2 : '((*&(u!v))@(^&u * ^&(v-u)@-.))'
basiscoeffs=: <: 4 : 'x bik y t. i.>:y'"0~ i.
linearcomb=: basiscoeffs@#@[
evalBernstein=: ([ +/ .* linearcomb) p. ] NB. evaluate Bernstein Polynomial (general)
NB.*getBezierPoints v Returns points for bezier curve given control points (y)
NB. eg: getBezierPoints controlpoints
NB. y is: y0 x0, y1 x1, y2 x2 ...
getBezierPoints=: monad define
ctrlpts=. (/: {:"1) _2]\ y NB. sort ctrlpts for increasing x
xvals=. ({: ,~ {. + +:@:i.@<.@-:@-~/) ({:"1) 0 _1{ctrlpts
tvals=. ((] - {.) % ({: - {.)) xvals
xvals ,.~ ({."1 ctrlpts) evalBernstein tvals
)
NB.*drawBezier v Draws bezier curve defined by (x) on image (y)
NB. eg: (42 40 10 30 186 269 26 187;255 0 0) drawBezier myimg
NB. x is: 2-item list of boxed (controlpoints) ; (color)
drawBezier=: (1&{:: ;~ 2 ]\ [: roundint@getBezierPoints"1 (0&{::))@[ drawLines ] |
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).
| #JavaScript | JavaScript |
function draw() {
var canvas = document.getElementById("container");
context = canvas.getContext("2d");
bezier3(20, 200, 700, 50, -300, 50, 380, 150);
// bezier3(160, 10, 10, 40, 30, 160, 150, 110);
// bezier3(0,149, 30,50, 120,130, 160,30, 0);
}
// http://rosettacode.org/wiki/Cubic_bezier_curves#C
function bezier3(x1, y1, x2, y2, x3, y3, x4, y4) {
var px = [], py = [];
for (var i = 0; i <= b3Seg; i++) {
var d = i / b3Seg;
var a = 1 - d;
var b = a * a;
var c = d * d;
a = a * b;
b = 3 * b * d;
c = 3 * a * c;
d = c * d;
px[i] = parseInt(a * x1 + b * x2 + c * x3 + d * x4);
py[i] = parseInt(a * y1 + b * y2 + c * y3 + d * y4);
}
var x0 = px[0];
var y0 = py[0];
for (i = 1; i <= b3Seg; i++) {
var x = px[i];
var y = py[i];
drawPolygon(context, [[x0, y0], [x, y]], "red", "red");
x0 = x;
y0 = y;
}
}
function drawPolygon(context, polygon, strokeStyle, fillStyle) {
context.strokeStyle = strokeStyle;
context.beginPath();
context.moveTo(polygon[0][0],polygon[0][1]);
for (i = 1; i < polygon.length; i++)
context.lineTo(polygon[i][0],polygon[i][1]);
context.closePath();
context.stroke();
if (fillStyle == undefined)
return;
context.fillStyle = fillStyle;
context.fill();
}
|
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #Common_Lisp | Common Lisp | ;;;; Common Lisp biorhythms
;;; Get the days to J2000
;;; FNday only works between 1901 to 2099 - see Meeus chapter 7
(defun day (y m d)
(+ (truncate (* -7 (+ y (truncate (+ m 9) 12))) 4)
(truncate (* 275 m) 9) d -730530 (* 367 y)))
;;; Get the difference in days between two dates
(defun diffday (y1 m1 d1 y2 m2 d2)
(abs (- (day y2 m2 d2) (day y1 m1 d1))))
;;; Print state of a single cycle
(defun print-cycle (diff len nm)
(let ((perc (round (* 100 (sin (* 2 pi diff (/ 1 len)))))))
(format t "~A cycle: ~D% " nm perc)
(if (< (abs perc) 15)
(format t "(critical)~%")
(format t "~%"))))
;;; Print all cycles
(defun print-bio (y1 m1 d1 y2 m2 d2)
(let ((diff (diffday y1 m1 d1 y2 m2 d2)))
(format t "Age in days: ~D ~%" diff)
(print-cycle diff 23 "physical")
(print-cycle diff 28 "emotional")
(print-cycle diff 33 "intellectual"))) |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #Delphi | Delphi |
program Biorhythms;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
var
cycles: array[0..2] of string = ('Physical day ', 'Emotional day', 'Mental day ');
lengths: array[0..2] of Integer = (23, 28, 33);
quadrants: array[0..3] of array[0..1] of string = (('up and rising', 'peak'),
('up but falling', 'transition'), ('down and falling', 'valley'), ('down but rising',
'transition'));
datePairs: array[0..2] of array[0..1] of string = (('1943-03-09', '1972-07-11'),
('1809-01-12', '1863-11-19'), ('1809-02-12', '1863-11-19') // correct DOB for Abraham Lincoln
);
procedure Check(err: string);
begin
if not err.IsEmpty then
raise Exception.Create(err);
end;
function ParseDate(sDate: string; var Date: TDateTime): string;
var
dtFormat: TFormatSettings;
begin
Result := '';
with dtFormat do
begin
DateSeparator := '-';
ShortDateFormat := 'yyyy-mm-dd';
end;
try
Date := StrtoDateTime(sDate, dtFormat);
except
on E: Exception do
Result := E.Message;
end;
end;
function DateToStr(dt: TDateTime): string;
var
dtFormat: TFormatSettings;
begin
Result := '';
with dtFormat do
begin
DateSeparator := '-';
ShortDateFormat := 'yyyy-mm-dd';
end;
Result := DateTimeToStr(dt, dtFormat);
end;
// Parameters assumed to be in YYYY-MM-DD format.
procedure CalcBiorhythms(birthDate, targetDate: string);
var
bd, td: TDateTime;
days: Integer;
begin
Check(ParseDate(birthDate, bd));
Check(ParseDate(targetDate, td));
days := Trunc(td - bd);
writeln('Born ', birthDate, ', Target ', targetDate);
Writeln('Days ', days);
for var i := 0 to 2 do
begin
var len := lengths[i];
var cycle := cycles[i];
var position := days mod len;
var quadrant: Integer := trunc(position * 4 / len);
var percent := sin(2.0 * PI * position / len);
percent := floor(percent * 1000) / 10;
var descript := '';
if percent > 95 then
descript := ' peak'
else if percent < -95 then
descript := ' valley'
else if abs(percent) < 5 then
descript := ' critical transition'
else
begin
var daysToAdd := trunc((quadrant + 1) * len / 4 - position);
var transition := td + daysToAdd;
var trend := quadrants[quadrant, 0];
var next := quadrants[quadrant, 1];
var transStr := DateToStr(transition);
var percentRounded := percent;
descript := format('%5.3f%% (%s, next %s %s)', [percentRounded, trend,
next, transStr]);
end;
writeln(format('%s %2d : %s', [cycle, position, descript]));
end;
writeln;
end;
begin
for var i := 0 to High(datePairs) do
CalcBiorhythms(datePairs[i, 0], datePairs[i, 1]);
readln;
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.)
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def Width=180, Height=135, Color=$123456;
proc WriteImage; \Write screen image to a a PPM file
int X, Y, C;
[Text(3,"P6 "); IntOut(3,Width); ChOut(3,^ ); IntOut(3,Height); Text(3," 255
");
for Y:= 0 to Height-1 do
for X:= 0 to Width-1 do
[C:= ReadPix(X, Y);
ChOut(3, C>>16);
ChOut(3, C>>8);
ChOut(3, C);
];
];
proc OpenOutFile(FN); \Open for output the named file
char FN; \file name string
int H; \handle
[H:= FOpen(FN, 1);
FSet(H, ^o); \small buffer allows multiple files, and it is
OpenO(3); \ closed automatically when the program exits
];
proc MakeImage; \Make a bitmap image
int X, Y;
[for Y:= 0 to Height-1 do \fill area with Color
for X:= 0 to Width-1 do
Point(X, Y, Color);
Move(60, 60); HexOut(6, ReadPix(0,0)); \show hex value of color of pixel at 0,0
];
[SetVid($112); \set display for 640x480 graphics in 24-bit RGB color
MakeImage;
OpenOutFile("IMAGE.PPM");
WriteImage;
SetVid(3); \restore display to normal text mode
] |
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.)
| #Yabasic | Yabasic | clear screen
wid = 150 : hei = 200
open window wid, hei
window origin "cc"
color 255, 0, 0
fill circle 0, 0, 50
color 0, 255, 0
fill circle 0, 0, 35
color 0, 0, 255
fill circle 0, 0, 20
window origin "lt"
header$ = "P6\n" + str$(wid) + " " + str$(hei) + "\n255\n"
fn = open("exmaple.PPM", "wb")
print #fn header$
for x = 0 to hei - 1
for y = 0 to wid - 1
c$ = right$(getbit$(y, x, y, x), 6)
poke #fn, dec(left$(c$, 2))
poke #fn, dec(right$(c$, 2))
poke #fn, dec(mid$(c$, 3, 2))
next y
next x
poke #fn, asc("\n")
close #fn |
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.
| #Assembly | Assembly | .486
IDEAL
;---------------------------------------------
; case: DeltaY is bigger than DeltaX
; input: p1X p1Y,
; p2X p2Y,
; Color -> variable
; output: line on the screen
;---------------------------------------------
Macro DrawLine2DDY p1X, p1Y, p2X, p2Y
local l1, lp, nxt
mov dx, 1
mov ax, [p1X]
cmp ax, [p2X]
jbe l1
neg dx ; turn delta to -1
l1:
mov ax, [p2Y]
shr ax, 1 ; div by 2
mov [TempW], ax
mov ax, [p1X]
mov [pointX], ax
mov ax, [p1Y]
mov [pointY], ax
mov bx, [p2Y]
sub bx, [p1Y]
absolute bx
mov cx, [p2X]
sub cx, [p1X]
absolute cx
mov ax, [p2Y]
lp:
pusha
call PIXEL
popa
inc [pointY]
cmp [TempW], 0
jge nxt
add [TempW], bx ; bx = (p2Y - p1Y) = deltay
add [pointX], dx ; dx = delta
nxt:
sub [TempW], cx ; cx = abs(p2X - p1X) = daltax
cmp [pointY], ax ; ax = p2Y
jne lp
call PIXEL
ENDM DrawLine2DDY
;---------------------------------------------
; case: DeltaX is bigger than DeltaY
; input: p1X p1Y,
; p2X p2Y,
; Color -> variable
; output: line on the screen
;---------------------------------------------
Macro DrawLine2DDX p1X, p1Y, p2X, p2Y
local l1, lp, nxt
mov dx, 1
mov ax, [p1Y]
cmp ax, [p2Y]
jbe l1
neg dx ; turn delta to -1
l1:
mov ax, [p2X]
shr ax, 1 ; div by 2
mov [TempW], ax
mov ax, [p1X]
mov [pointX], ax
mov ax, [p1Y]
mov [pointY], ax
mov bx, [p2X]
sub bx, [p1X]
absolute bx
mov cx, [p2Y]
sub cx, [p1Y]
absolute cx
mov ax, [p2X]
lp:
pusha
call PIXEL
popa
inc [pointX]
cmp [TempW], 0
jge nxt
add [TempW], bx ; bx = abs(p2X - p1X) = deltax
add [pointY], dx ; dx = delta
nxt:
sub [TempW], cx ; cx = abs(p2Y - p1Y) = deltay
cmp [pointX], ax ; ax = p2X
jne lp
call PIXEL
ENDM DrawLine2DDX
Macro absolute a
local l1
cmp a, 0
jge l1
neg a
l1:
Endm
MODEL small
STACK 256
DATASEG
TempW dw ?
pointX dw ?
pointY dw ?
point1X dw ?
point1Y dw ?
point2X dw ?
point2Y dw ?
Color db ?
CODESEG
start:
mov ax, @data
mov ds, ax
mov ax, 13h
int 10h ; set graphic mode
mov [Color], 61
mov [point1X], 300
mov [point2X], 6
mov [point1Y], 122
mov [point2Y], 88
call DrawLine2D
mov ah, 00h
int 16h
exit:
mov ax,03h
int 10h ; set text mode
mov ax, 4C00h
int 21h
; procedures
;---------------------------------------------
; input: point1X point1Y,
; point2X point2Y,
; Color
; output: line on the screen
;---------------------------------------------
PROC DrawLine2D
mov cx, [point1X]
sub cx, [point2X]
absolute cx
mov bx, [point1Y]
sub bx, [point2Y]
absolute bx
cmp cx, bx
jae DrawLine2Dp1 ; deltaX > deltaY
mov ax, [point1X]
mov bx, [point2X]
mov cx, [point1Y]
mov dx, [point2Y]
cmp cx, dx
jbe DrawLine2DpNxt1 ; point1Y <= point2Y
xchg ax, bx
xchg cx, dx
DrawLine2DpNxt1:
mov [point1X], ax
mov [point2X], bx
mov [point1Y], cx
mov [point2Y], dx
DrawLine2DDY point1X, point1Y, point2X, point2Y
ret
DrawLine2Dp1:
mov ax, [point1X]
mov bx, [point2X]
mov cx, [point1Y]
mov dx, [point2Y]
cmp ax, bx
jbe DrawLine2DpNxt2 ; point1X <= point2X
xchg ax, bx
xchg cx, dx
DrawLine2DpNxt2:
mov [point1X], ax
mov [point2X], bx
mov [point1Y], cx
mov [point2Y], dx
DrawLine2DDX point1X, point1Y, point2X, point2Y
ret
ENDP DrawLine2D
;-----------------------------------------------
; input: pointX pointY,
; Color
; output: point on the screen
;-----------------------------------------------
PROC PIXEL
mov bh,0h
mov cx,[pointX]
mov dx,[pointY]
mov al,[Color]
mov ah,0Ch
int 10h
ret
ENDP PIXEL
END start
|
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Ada | Ada | with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
with Ada.Text_Io;
procedure Mutations is
Width : constant := 60;
type Nucleotide_Type is (A, C, G, T);
type Operation_Type is (Delete, Insert, Swap);
type Position_Type is new Natural;
package Position_Io is new Ada.Text_Io.Integer_Io (Position_Type);
package Nucleotide_Io is new Ada.Text_Io.Enumeration_Io (Nucleotide_Type);
package Operation_Io is new Ada.Text_Io.Enumeration_Io (Operation_Type);
use Ada.Text_Io, Position_Io, Nucleotide_Io, Operation_Io;
package Sequence_Vectors is new Ada.Containers.Vectors (Index_Type => Position_Type,
Element_Type => Nucleotide_Type);
package Nucleotide_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Nucleotide_Type);
package Operation_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Operation_Type);
procedure Pretty_Print (Sequence : Sequence_Vectors.Vector) is
First : Position_Type := Sequence.First_Index;
Last : Position_Type;
Count : array (Nucleotide_Type) of Natural := (others => 0);
begin
Last := Position_Type'Min (First + Width - 1,
Sequence.Last_Index);
loop
Position_Io.Put (First, Width => 4);
Put (": ");
for N in First .. Last loop
declare
Nucleotide : Nucleotide_Type renames Sequence (N);
begin
Put (Nucleotide);
Count (Nucleotide) := Count (Nucleotide) + 1;
end;
end loop;
New_Line;
exit when Last = Sequence.Last_Index;
First := Last + 1;
Last := Position_Type'Min (First + Width - 1,
Sequence.Last_Index);
end loop;
for N in Count'Range loop
Put ("Count of "); Put (N); Put (" is "); Put (Natural'Image (Count (N))); New_Line;
end loop;
end Pretty_Print;
function Random_Position (First, Last : Position_Type) return Position_Type is
subtype Position_Range is Position_Type range First .. Last;
package Position_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Position_Range);
Generator : Position_Generators.Generator;
begin
Position_Generators.Reset (Generator);
return Position_Generators.Random (Generator);
end Random_Position;
Nucleotide_Generator : Nucleotide_Generators.Generator;
Operation_Generator : Operation_Generators.Generator;
Sequence : Sequence_Vectors.Vector;
Position : Position_Type;
Nucleotide : Nucleotide_Type;
Operation : Operation_Type;
begin
Nucleotide_Generators.Reset (Nucleotide_Generator);
Operation_Generators.Reset (Operation_Generator);
for A in 1 .. 200 loop
Sequence.Append (Nucleotide_Generators.Random (Nucleotide_Generator));
end loop;
Put_Line ("Initial sequence:");
Pretty_Print (Sequence);
New_Line;
Put_Line ("Mutations:");
for Mutate in 1 .. 10 loop
Operation := Operation_Generators.Random (Operation_Generator);
case Operation is
when Delete =>
Position := Random_Position (Sequence.First_Index, Sequence.Last_Index);
Sequence.Delete (Index => Position);
Put (Operation); Put (" at position "); Put (Position, Width => 0); New_Line;
when Insert =>
Position := Random_Position (Sequence.First_Index, Sequence.Last_Index + 1);
Nucleotide := Nucleotide_Generators.Random (Nucleotide_Generator);
Sequence.Insert (Before => Position,
New_Item => Nucleotide);
Put (Operation); Put (" "); Put (Nucleotide); Put (" at position ");
Put (Position, Width => 0); New_Line;
when Swap =>
Position := Random_Position (Sequence.First_Index, Sequence.Last_Index);
Nucleotide := Nucleotide_Generators.Random (Nucleotide_Generator);
Sequence.Replace_Element (Index => Position,
New_Item => Nucleotide);
Put (Operation); Put (" at position "); Put (Position, Width => 0);
Put (" to "); Put (Nucleotide); New_Line;
end case;
end loop;
New_Line;
Put_Line ("Mutated sequence:");
Pretty_Print (Sequence);
end Mutations; |
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.
| #Dart | Dart | import 'package:crypto/crypto.dart';
class Bitcoin {
final String ALPHABET =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
List<int> bigIntToByteArray(BigInt data) {
String str;
bool neg = false;
if (data < BigInt.zero) {
str = (~data).toRadixString(16);
neg = true;
} else str = data.toRadixString(16);
int p = 0;
int len = str.length;
int blen = (len + 1) ~/ 2;
int boff = 0;
List bytes;
if (neg) {
if (len & 1 == 1) {
p = -1;
}
int byte0 = ~int.parse(str.substring(0, p + 2), radix: 16);
if (byte0 < -128) byte0 += 256;
if (byte0 >= 0) {
boff = 1;
bytes = new List<int>(blen + 1);
bytes[0] = -1;
bytes[1] = byte0;
} else {
bytes = new List<int>(blen);
bytes[0] = byte0;
}
for (int i = 1; i < blen; ++i) {
int byte = ~int.parse(str.substring(p + (i << 1), p + (i << 1) + 2),
radix: 16);
if (byte < -128) byte += 256;
bytes[i + boff] = byte;
}
} else {
if (len & 1 == 1) {
p = -1;
}
int byte0 = int.parse(str.substring(0, p + 2), radix: 16);
if (byte0 > 127) byte0 -= 256;
if (byte0 < 0) {
boff = 1;
bytes = new List<int>(blen + 1);
bytes[0] = 0;
bytes[1] = byte0;
} else {
bytes = new List<int>(blen);
bytes[0] = byte0;
}
for (int i = 1; i < blen; ++i) {
int byte =
int.parse(str.substring(p + (i << 1), p + (i << 1) + 2), radix: 16);
if (byte > 127) byte -= 256;
bytes[i + boff] = byte;
}
}
return bytes;
}
List<int> arrayCopy(bytes, srcOffset, result, destOffset, bytesLength) {
for (int i = srcOffset; i < bytesLength; i++) {
result[destOffset + i] = bytes[i];
}
return result;
}
List<int> decodeBase58To25Bytes(String input) {
BigInt number = BigInt.zero;
for (String t in input.split('')) {
int p = ALPHABET.indexOf(t);
if (p == (-1))
return null;
number = number * (BigInt.from(58)) + (BigInt.from(p));
}
List<int> result = new List<int>(24);
List<int> numBytes = bigIntToByteArray(number);
return arrayCopy(
numBytes, 0, result, result.length - numBytes.length, numBytes.length);
}
validateAddress(String address) {
List<int> decoded = new List.from(decodeBase58To25Bytes(address));
List<int> temp = new List<int>.from(decoded);
temp.insert(0, 0);
List<int> hash1 = sha256.convert(temp.sublist(0, 21)).bytes;
List<int> hash2 = sha256.convert(hash1).bytes;
if (hash2[0] != decoded[20] ||
hash2[1] != decoded[21] ||
hash2[2] != decoded[22] ||
hash2[3] != decoded[23]) return false;
return true;
}
} |
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.
| #Delphi | Delphi |
uses
DCPsha256;
type
TByteArray = array of Byte;
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 DecodeBase58(const Input: string): TByteArray;
const
Size = 25;
Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var
C: Char;
I, J: Integer;
begin
SetLength(Result, Size);
for C in Input do
begin
I := Pos(C, Alphabet) - 1;
if I = -1 then
raise Exception.CreateFmt('Invalid character found: %s', [C]);
for J := High(Result) downto 0 do
begin
I := I + (58 * Result[J]);
Result[J] := I mod 256;
I := I div 256;
end;
if I <> 0 then
raise Exception.Create('Address too long');
end;
end;
procedure ValidateBitcoinAddress(const Address: string);
var
Hashed: TByteArray;
Decoded: TByteArray;
begin
if (Length(Address) < 26) or (Length(Address) > 35) then
raise Exception.Create('Wrong length');
Decoded := DecodeBase58(Address);
Hashed := HashSHA256(HashSHA256(Copy(Decoded, 0, 21)));
if not CompareMem(@Decoded[21], @Hashed[0], 4) then
raise Exception.Create('Bad digest');
end;
|
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
| #Phix | Phix | without javascript_semantics -- no ripemd160.js as yet
include builtins\sha256.e
include builtins\ripemd160.e
constant b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
function base58(string s)
string out = ""
if length(s)!=25 then ?9/0 end if
for n=1 to 34 do
integer c = 0
for i=1 to 25 do
c = c*256+s[i]
s[i] = floor(c/58)
c = mod(c,58)
end for
out &= b58[c+1]
end for
if out[$]='1' then
for i=length(out)-1 to 1 by -1 do
if out[i]!='1' then
out = out[1..i+1]
exit
end if
end for
end if
return reverse(out)
end function
function coin_encode(string x, y)
if length(x)!=32
or length(y)!=32 then
return "bad public point string"
end if
string s = "\x04" & x & y
string rmd = '\0'&ripemd160(sha256(s),false)
rmd &= sha256(sha256(rmd))[1..4]
string res = base58(rmd)
return res
end function
?coin_encode(x"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
x"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
|
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.
| #FBSL | FBSL | #DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_CLOSE 16
FBSLSETTEXT(ME, "Before Flood Fill") ' 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)
DrawCircles() ' Initialize circles
BEGIN EVENTS
SELECT CASE CBMSG
CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles
CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up
END SELECT
END EVENTS
SUB FillCircles()
FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics
FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively
FOR DIM y = 0 TO Height / 2
IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF)
NEXT
NEXT
FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption
END SUB
SUB DrawCircles() ' Concatenate function calls
CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White
(FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black
END SUB |
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
| #F.23 | F# | type bool = System.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
| #Factor | Factor | TRUE . \ -1
FALSE . \ 0 |
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
| #VBScript | VBScript |
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
Wscript.Echo str
Wscript.Echo Rotate(str,5)
Wscript.Echo Rotate(Rotate(str,5),-5)
'Rotate (Caesar encrypt/decrypt) test <numpos> positions.
' numpos < 0 - rotate left
' numpos > 0 - rotate right
'Left rotation is converted to equivalent right rotation
Function Rotate (text, numpos)
dim dic: set dic = CreateObject("Scripting.Dictionary")
dim ltr: ltr = Split("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z")
dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation
dim ch
dim i
for i = 0 to ubound(ltr)
dic(ltr(i)) = ltr((rot+i) Mod 26)
next
Rotate = ""
for i = 1 to Len(text)
ch = Mid(text,i,1)
if dic.Exists(ch) Then
Rotate = Rotate & dic(ch)
else
Rotate = Rotate & ch
end if
next
End Function
|
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)..
| #D | D | import std.stdio, std.string, std.math, std.array;
struct boxTheCompass {
immutable static string[32] points;
pure nothrow static this() {
immutable cardinal = ["north", "east", "south", "west"];
immutable desc = ["1", "1 by 2", "1-C", "C by 1", "C",
"C by 2", "2-C", "2 by 1"];
foreach (immutable i; 0 .. 4) {
immutable s1 = cardinal[i];
immutable s2 = cardinal[(i + 1) % 4];
immutable sc = (s1 == "north" || s1 == "south") ?
(s1 ~ s2) : (s2 ~ s1);
foreach (immutable j; 0 .. 8)
points[i * 8 + j] = desc[j].replace("1", s1).
replace("2", s2).replace("C", sc);
}
}
static string opCall(in double degrees) pure /*nothrow*/ {
immutable testD = (degrees / 11.25) + 0.5;
return points[cast(int)floor(testD % 32)].capitalize;
}
}
void main() {
foreach (immutable i; 0 .. 33) {
immutable heading = i * 11.25 + [0, 5.62, -5.62][i % 3];
writefln("%s\t%18s\t%s", i % 32 + 1,
heading.boxTheCompass, heading);
}
} |
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.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc convert_to_blackandwhite {filename} {
set img [image create photo]
readPPM $img $filename
grayscale $img
set hist [histogram $img]
set median [median $img $hist]
blackandwhite $img $median
output_ppm $img bw_$filename
}
proc histogram {image} {
set hist [dict create]
for {set x 0} {$x < [image width $image]} {incr x} {
for {set y 0} {$y < [image height $image]} {incr y} {
dict incr hist [luminance {*}[$image get $x $y]]
}
}
return $hist
}
proc luminance {r g b} {
expr {
int(0.2126*$r + 0.7152*$g + 0.0722*$b)
}
}
proc median {img hist} {
set sum [expr {[image width $img] * [image height $img]}]
set total 0
foreach luminance [lsort -integer [dict keys $hist]] {
incr total [dict get $hist $luminance]
if {$total > $sum / 2} break
}
return $luminance
}
proc blackandwhite {image median} {
for {set x 0} {$x < [image width $image]} {incr x} {
for {set y 0} {$y < [image height $image]} {incr y} {
if {[luminance {*}[$image get $x $y]] < $median} {
$image put black -to $x $y
} else {
$image put white -to $x $y
}
}
}
} |
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.
| #AutoHotkey | AutoHotkey | bitwise(3, 4)
bitwise(a, b)
{
MsgBox % "a and b: " . a & b
MsgBox % "a or b: " . a | b
MsgBox % "a xor b: " . a ^ b
MsgBox % "not a: " . ~a ; treated as unsigned integer
MsgBox % "a << b: " . a << b ; left shift
MsgBox % "a >> b: " . a >> b ; arithmetic 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).
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Bezier(P0, P1, P2); \Draw quadratic Bezier curve
real P0, P1, P2;
def Segments = 8;
int I;
real T, A, B, C, X, Y;
[Move(fix(P0(0)), fix(P0(1)));
for I:= 1 to Segments do
[T:= float(I)/float(Segments);
A:= sq(1.-T);
B:= 2.*T*(1.-T);
C:= sq(T);
X:= A*P0(0) + B*P1(0) + C*P2(0);
Y:= A*P0(1) + B*P1(1) + C*P2(1);
Line(fix(X), fix(Y), $00FFFF); \cyan line segments
];
Point(fix(P0(0)), fix(P0(1)), $FF0000); \red control points
Point(fix(P1(0)), fix(P1(1)), $FF0000);
Point(fix(P2(0)), fix(P2(1)), $FF0000);
];
[SetVid($112); \set 640x480x24 video graphics
Bezier([0., 0.], [80., 100.], [160., 20.]);
if ChIn(1) then []; \wait for keystroke
SetVid(3); \restore normal text display
] |
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).
| #zkl | zkl | fcn qBezier(p0x,p0y, p1x,p1y, p2x,p2y, rgb, numPts=500){
numPts.pump(Void,'wrap(t){ // B(t)
t=t.toFloat()/numPts; t1:=(1.0 - t);
a:=t1*t1; b:=t*t1*2; c:=t*t;
x:=a*p0x + b*p1x + c*p2x + 0.5;
y:=a*p0y + b*p1y + c*p2y + 0.5;
__sSet(rgb,x,y);
});
} |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #Action.21 | Action! | INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap
RGB black,yellow,violet,blue
PROC DrawImage(RgbImage POINTER img BYTE x,y)
RGB c
BYTE i,j
FOR j=0 TO img.h-1
DO
FOR i=0 TO img.w-1
DO
GetRgbPixel(img,i,j,c)
IF RgbEqual(c,yellow) THEN
Color=1
ELSEIF RgbEqual(c,violet) THEN
Color=2
ELSEIF RgbEqual(c,blue) THEN
Color=3
ELSE
Color=0
FI
Plot(x+i,y+j)
OD
OD
RETURN
PROC Main()
RgbImage img
BYTE CH=$02FC,width=[80],height=[60]
BYTE ARRAY ptr(14400)
BYTE i,x,y,c
Graphics(7+16)
SetColor(0,13,12) ;yellow
SetColor(1,4,10) ;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,blue)
FOR i=1 TO 1000
DO
c=Rand(3)
x=Rand(width)
y=Rand(height)
IF c=0 THEN
SetRgbPixel(img,x,y,yellow)
ELSEIF c=1 THEN
SetRgbPixel(img,x,y,violet)
ELSE
SetRgbPixel(img,x,y,black)
FI
OD
DrawImage(img,(160-width)/2,(96-height)/2)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
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).
| #Nim | Nim | import bitmap
proc setPixel(img: Image; x, y: int; color: Color) {.inline.} =
# Set a pixel at a given color.
# Ignore if the point is outside of the image.
if x in 0..<img.w and y in 0..<img.h:
img[x, y] = color
proc drawCircle(img: Image; center: Point; radius: Natural; color: Color) =
## Draw a circle using midpoint circle algorithm.
var
f = 1 - radius
ddFX = 0
ddFY = -2 * radius
x = 0
y = radius
img.setPixel(center.x, center.y + radius, color)
img.setPixel(center.x, center.y - radius, color)
img.setPixel(center.x + radius, center.y, color)
img.setPixel(center.x - radius, center.y, color)
while x < y:
if f >= 0:
dec y
inc ddFY, 2
inc f, ddFY
inc x
inc ddFX, 2
inc f, ddFX + 1
img.setPixel(center.x + x, center.y + y, color)
img.setPixel(center.x - x, center.y + y, color)
img.setPixel(center.x + x, center.y - y, color)
img.setPixel(center.x - x, center.y - y, color)
img.setPixel(center.x + y, center.y + x, color)
img.setPixel(center.x - y, center.y + x, color)
img.setPixel(center.x + y, center.y - x, color)
img.setPixel(center.x - y, center.y - x, color)
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
var img = newImage(16, 16)
img.fill(White)
img.drawCircle((7, 7), 5, Black)
img.print() |
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).
| #Perl | Perl | # 20220301 Perl programming solution
use strict;
use warnings;
use Algorithm::Line::Bresenham 'circle';
my @points;
my @circle = circle((10) x 3);
for (@circle) { $points[$_->[0]][$_->[1]] = '#' }
print join "\n", map { join '', map { $_ || ' ' } @$_ } @points |
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).
| #Julia | Julia | using Images
function cubicbezier!(xy::Matrix,
img::Matrix = fill(RGB(255.0, 255.0, 255.0), 17, 17),
col::ColorTypes.Color = convert(eltype(img), Gray(0.0)),
n::Int = 20)
t = collect(0:n) ./ n
M = hcat((1 .- t) .^ 3, # a
3t .* (1 .- t) .^ 2, # b
3t .^ 2 .* (1 .- t), # c
t .^ 3) # d
p = floor.(Int, M * xy)
for i in 1:n
drawline!(img, p[i, :]..., p[i+1, :]..., col)
end
return img
end
xy = [16 1; 1 4; 3 16; 15 11]
cubicbezier!(xy) |
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).
| #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 cubicBezier(p1: Point, p2: Point, p3: Point, p4: 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 * u
val b = 3.0 * t * u * u
val c = 3.0 * t * t * u
val d = t * t * t
pts[i].x = (a * p1.x + b * p2.x + c * p3.x + d * p4.x).toInt()
pts[i].y = (a * p1.y + b * p2.y + c * p3.y + d * p4.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 = 200
val height = 200
val bbs = BasicBitmapStorage(width, height)
with (bbs) {
fill(Color.cyan)
val p1 = Point(0, 149)
val p2 = Point(30, 50)
val p3 = Point(120, 130)
val p4 = Point(160, 30)
cubicBezier(p1, p2, p3, p4, Color.black, 20)
val cbFile = File("cubic_bezier.jpg")
ImageIO.write(image, "jpg", cbFile)
}
} |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #Emacs_Lisp | Emacs Lisp | (require 'calendar)
(setq biorhythm-birthdate '(3 16 1953))
(defun biorhythm ()
"Show today's biorhythm."
(interactive)
(let* ((diff (abs (- (string-to-number (calendar-astro-date-string
biorhythm-birthdate)) (string-to-number
(calendar-astro-date-string)))))
(rhyt '(23 28 33))
(perc (mapcar (lambda (x) (round (* 100 (sin
(* 2 pi diff (/ 1.0 x)))))) rhyt)))
(message "age: %i physical: %i%% emotional: %i%% intellectual: %i%%"
diff (car perc) (cadr perc) (caddr perc)))) |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #Factor | Factor | USING: calendar calendar.parser formatting io kernel math
math.constants math.functions ;
: days-between ( ymd-str ymd-str -- n )
[ ymd>timestamp ] bi@ time- duration>days abs ;
: trend ( pos len -- str ) / 4 * floor 3 divisor? "↑" "↓" ? ;
: percent ( pos len -- x ) [ 2pi * ] [ / sin 100 * ] bi* ;
: .day ( days cycle-length day-type -- )
write [ mod ] keep [ drop ] [ percent ] [ trend ] 2tri
" day %d: %.1f%%%s\n" printf ;
: .biorhythm ( ymd-str ymd-str -- )
2dup "Born %s, Target %s\n" printf days-between dup
"Day %d\n" printf
[ 23 "Physical" .day ]
[ 28 "Emotional" .day ]
[ 33 "Mental" .day ] tri ;
"1809-02-12" "1863-11-19" .biorhythm |
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.)
| #zkl | zkl | // convert Windows BMP (bit map) image to PPM
// Read BMP file
bmp:=File.stdin.read().howza(0); // BMP to memory (byte bucket), treat as bytes
_assert_(bmp[0]==0x42,"Stdin not a BMP file");
width:=bmp.toLittleEndian(18,2,False); height:=bmp.toLittleEndian(22,2,False); // signed
println(width," x ",height);
bmp.del(0,14 + bmp.toLittleEndian(14,2)); // get rid of header
// Write BMP to PPM image (in memory)
ppm:=Data(width*height*3 + 100); // sized byte bucket plus some header slop
ppm.write("P6\n#rosettacode BMP to PPM test\n%d %d\n255\n".fmt(width,height));
foreach y in ([height - 1 .. 0,-1]){ // BGR 1 byte each, image is stored upside down
bmp[y*width*3,width*3].pump(ppm,T(Void.Read,2),fcn(b,g,r){ return(r,g,b) });
}
File("foo.ppm","wb").write(ppm); // File.stdout isn't binary, let GC close file |
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.
| #AutoHotkey | AutoHotkey | Blue := Color(0,0,255)
White := Color(255,255,255)
Bitmap := Bitmap(100,100,Blue) ;create a 100*100 blue bitmap
Line(Bitmap,White,5,10,60,80) ;draw a white line from (5,10) to (60,80)
Bitmap.Write("Line.ppm") ;write the bitmap to file
Line(ByRef Bitmap,ByRef Color,PosX1,PosY1,PosX2,PosY2)
{
DeltaX := Abs(PosX2 - PosX1), DeltaY := -Abs(PosY2 - PosY1) ;calculate deltas
StepX := ((PosX1 < PosX2) ? 1 : -1), StepY := ((PosY1 < PosY2) ? 1 : -1) ;calculate steps
ErrorValue := DeltaX + DeltaY ;calculate error value
Loop ;loop over the pixel values
{
Bitmap[PosX1,PosX2] := Color
If (PosX1 = PosX2 && PosY1 = PosY2)
Break
Temp1 := ErrorValue << 1, ((Temp1 > DeltaY) ? (ErrorValue += DeltaY, PosX1 += StepX) : ""), ((Temp1 < DeltaX) ? (ErrorValue += DeltaX, PosY1 += StepY) : "") ;move forward
}
} |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Arturo | Arturo | bases: ["A" "T" "G" "C"]
dna: map 1..200 => [sample bases]
prettyPrint: function [in][
count: #[ A: 0, T: 0, G: 0, C: 0 ]
loop.with:'i split.every:50 in 'line [
prints [pad to :string i*50 3 ":"]
print map split.every:10 line => join
loop split line 'ch [
case [ch=]
when? -> "A" -> count\A: count\A + 1
when? -> "T" -> count\T: count\T + 1
when? -> "G" -> count\G: count\G + 1
when? -> "C" -> count\C: count\C + 1
else []
]
]
print ["Total count => A:" count\A, "T:" count\T "G:" count\G "C:" count\C]
]
performRandomModifications: function [seq,times][
result: new seq
loop times [x][
what: random 1 3
case [what=]
when? -> 1 [
ind: random 0 (size result)
previous: get result ind
next: sample bases
set result ind next
print ["changing base at position" ind "from" previous "to" next]
]
when? -> 2 [
ind: random 0 (size result)
next: sample bases
result: insert result ind next
print ["inserting base" next "at position" ind]
]
else [
ind: random 0 (size result)
previous: get result ind
result: remove result .index ind
print ["deleting base" previous "at position" ind]
]
]
return result
]
print "------------------------------"
print " Initial sequence"
print "------------------------------"
prettyPrint dna
print ""
print "------------------------------"
print " Modifying sequence"
print "------------------------------"
dna: performRandomModifications dna 10
print ""
print "------------------------------"
print " Final sequence"
print "------------------------------"
prettyPrint dna
print "" |
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.
| #Erlang | Erlang |
-module( bitcoin_address ).
-export( [task/0, validate/1] ).
task() ->
io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"] ),
io:fwrite( "~p~n", [validate("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")] ),
io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW622"] ),
io:fwrite( "~p~n", [validate("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW622")] ).
validate( String ) ->
{length_25, <<Address:21/binary, Checksum:4/binary>>} = {length_25, base58:base58_to_binary( String )},
<<Version:1/binary, _/binary>> = Address,
{version_0, <<0>>} = {version_0, Version},
<<Four_bytes:4/binary, _T/binary>> = crypto:hash( sha256, crypto:hash(sha256, Address) ),
{checksum, Checksum} = {checksum, Four_bytes},
ok.
|
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
| #PicoLisp | PicoLisp | (load "ripemd160.l")
(load "sha256.l")
(setq *B58Alpha
(chop "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") )
(de hex2L (H)
(make
(for (L (chop H) L (cddr L))
(link (hex (pack (car L) (cadr L)))) ) ) )
(de b58enc (Lst)
(let
(P 1
Z 0
A
(sum
'((X)
(* X (swap 'P (>> -8 P))) )
(reverse Lst) ) )
(for L Lst
(T (n0 L))
(inc 'Z) )
(pack
(need Z "1")
(make
(while (gt0 A)
(yoke
(prog1
(get *B58Alpha (inc (% A 58)))
(setq A (/ A 58)) ) ) ) ) ) ) )
(de point2address (X Y)
(let L (conc (cons 4) (hex2L X) (hex2L Y))
(b58enc
(and
(conc (cons 0) (ripemd160 (sha256 L)))
(conc @ (head 4 (sha256 (sha256 @)))) ) ) ) )
(println
(point2address
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6" ) ) |
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
| #Python | Python | #!/usr/bin/env python3
import binascii
import functools
import hashlib
digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58(n):
return b58(n//58) + digits58[n%58:n%58+1] if n else b''
def public_point_to_address(x, y):
c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(c).digest())
c = b'\x00' + r.digest()
d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))
if __name__ == '__main__':
print(public_point_to_address(
b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6')) |
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.
| #Forth | Forth | : third 2 pick ;
: 3dup third third third ;
: 4dup 2over 2over ;
: flood ( color x y bmp -- )
3dup b@ >r ( R: color to fill )
4dup b!
third 0 > if
rot 1- -rot
3dup b@ r@ = if recurse then
rot 1+ -rot
then
third 1+ over bwidth < if
rot 1+ -rot
3dup b@ r@ = if recurse then
rot 1- -rot
then
over 0 > if
swap 1- swap
3dup b@ r@ = if recurse then
swap 1+ swap
then
over 1+ over bheight < if
swap 1+ swap
3dup b@ r@ = if recurse then
swap 1- swap
then
r> drop ; |
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
| #FALSE | FALSE | TRUE . \ -1
FALSE . \ 0 |
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
| #Fantom | Fantom | TRUE . \ -1
FALSE . \ 0 |
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
| #Vedit_macro_language | Vedit macro language | #10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)
Goto_Pos(Block_Begin)
while(Cur_Pos < Block_End) {
#11 = Cur_Char & 0x60 + 1
if (Cur_Char >= 'A') {
Ins_Char((Cur_Char - #11 + 26 + #10) % 26 + #11, OVERWRITE)
} else {
Char(1)
}
} |
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)..
| #Delphi | Delphi | defmodule Box do
defp head do
Enum.chunk(~w(north east south west north), 2, 1)
|> Enum.flat_map(fn [a,b] ->
c = if a=="north" or a=="south", do: "#{a}#{b}", else: "#{b}#{a}"
[ a, "#{a} by #{b}", "#{a}-#{c}", "#{c} by #{a}",
c, "#{c} by #{b}", "#{b}-#{c}", "#{b} by #{a}" ]
end)
|> Enum.with_index
|> Enum.map(fn {s, i} -> {i+1, String.capitalize(s)} end)
|> Map.new
end
def compass do
header = head()
angles = Enum.map(0..32, fn i -> i * 11.25 + elem({0, 5.62, -5.62}, rem(i, 3)) end)
Enum.each(angles, fn degrees ->
index = rem(round(32 * degrees / 360), 32) + 1
:io.format "~2w ~-20s ~6.2f~n", [index, header[index], degrees]
end)
end
end
Box.compass |
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.
| #Vedit_macro_language | Vedit macro language | :HISTOGRAM:
#30 = Buf_Free // #30 = buffer to store histogram data
for (#9=0; #9<256; #9++) {
Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted
Buf_Switch(#15) // switch to image buffer
#8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values
Buf_Switch(#30) // switch to histogram buffer
Num_Ins(#8, FILL) // store count
}
Return |
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.
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, ImageData
class ImageHistogram {
construct new(filename, filename2) {
_image = ImageData.loadFromFile(filename)
Window.resize(_image.width, _image.height)
Canvas.resize(_image.width, _image.height)
Window.title = filename2
_image2 = ImageData.create("Grayscale", _image.width, _image.height)
_image3 = ImageData.create("B & W", _image.width, _image.height)
}
init() {
toGrayScale()
var h = histogram
var m = median(h)
toBlackAndWhite(m)
_image3.draw(0, 0)
_image3.saveToFile(Window.title)
}
luminance(c) { (0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b).floor }
toGrayScale() {
for (x in 0..._image.width) {
for (y in 0..._image.height) {
var c1 = _image.pget(x, y)
var lumin = luminance(c1)
var c2 = Color.rgb(lumin, lumin, lumin, c1.a)
_image2.pset(x, y, c2)
}
}
}
toBlackAndWhite(median) {
for (x in 0..._image2.width) {
for (y in 0..._image2.height) {
var c = _image2.pget(x, y)
var lum = luminance(c)
if (lum < median) {
_image3.pset(x, y, Color.black)
} else {
_image3.pset(x, y, Color.white)
}
}
}
}
histogram {
var h = List.filled(256, 0)
for (x in 0..._image2.width) {
for (y in 0..._image2.height) {
var c = _image2.pget(x, y)
var lum = luminance(c)
h[lum] = h[lum] + 1
}
}
return h
}
median(h) {
var lSum = 0
var rSum = 0
var left = 0
var right = 255
while (true) {
if (lSum < rSum) {
lSum = lSum + h[left]
left = left + 1
} else {
rSum = rSum + h[right]
right = right - 1
}
if (left == right) break
}
return left
}
update() {}
draw(alpha) {}
}
var Game = ImageHistogram.new("Lenna100.jpg", "Lenna100_B&W.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.
| #AutoIt | AutoIt | bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
$a & " AND " & $b & ": " & BitAND($a, $b) & @CRLF & _
$a & " OR " & $b & ": " & BitOR($a, $b) & @CRLF & _
$a & " XOR " & $b & ": " & BitXOR($a, $b) & @CRLF & _
"NOT " & $a & ": " & BitNOT($a) & @CRLF & _
$a & " SHL " & $b & ": " & BitShift($a, $b * -1) & @CRLF & _
$a & " SHR " & $b & ": " & BitShift($a, $b) & @CRLF & _
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF )
EndFunc |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #ActionScript | ActionScript |
// To import the BitmapData class:
import flash.display.BitmapData;
// Creates a new BitmapData object with a width of 500 pixels and a height of 300 pixels.
var bitmap:BitmapData = new BitmapData(500, 300);
// Create a BitmapData with transparency disallowed
var opaqueBitmap:BitmapData = new BitmapData(500, 300, false);
// Bitmap with initial fill colour, as 0xAARRGGBB (default is white)
var redFilledBitmap:BitmapData = new BitmapData(400, 300, true, 0xFFFF0000);
// Get the colour value of the pixel at point (200, 200)
bitmap.getPixel(200, 200) // As 0xRRGGBB
bitmap.getPixel32(200, 200) // As 0xAARRGGBB
// Set the colour value of the pixel at point (300, 200) to blue
bitmap.setPixel(300, 200, 0x0000FF); // As 0xRRGGBB
bitmap.setPixel32(300, 200, 0xFF0000FF); // As 0xAARRGGBB
// Fill the bitmap with a given colour (as 0xAARRGGBB) after construction
bitmap.fillRect(bitmap.rect, 0xFF44FF44);
|
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).
| #Phix | Phix | -- demo\rosetta\Bitmap_Circle.exw (runnable version)
include ppm.e -- red, yellow, new_image(), write_ppm() -- (covers above requirements)
function SetPx(sequence img, atom x, y, integer colour)
if x>=1 and x<=length(img)
and y>=1 and y<=length(img[x]) then
img[x][y] = colour
end if
return img
end function
function Circle(sequence img, atom x, y, r, integer colour)
atom x1 = -r,
y1 = 0,
err = 2-2*r
if r>=0 then
-- Bresenham algorithm
while 1 do
img = SetPx(img, x-x1, y+y1, colour)
img = SetPx(img, x-y1, y-x1, colour)
img = SetPx(img, x+x1, y-y1, colour)
img = SetPx(img, x+y1, y+x1, colour)
r = err
if r>x1 then
x1 += 1
err += x1*2 + 1
end if
if r<=y1 then
y1 += 1
err += y1*2 + 1
end if
if x1>=0 then exit end if
end while
end if
return img
end function
sequence img = new_image(400,300,yellow)
img = Circle(img, 200, 150, 100, red)
write_ppm("Circle.ppm",img) |
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).
| #PicoLisp | PicoLisp | (de midPtCircle (Img CX CY Rad)
(let (F (- 1 Rad) DdFx 0 DdFy (* -2 Rad) X 0 Y Rad)
(set (nth Img (+ CY Rad) CX) 1)
(set (nth Img (- CY Rad) CX) 1)
(set (nth Img CY (+ CX Rad)) 1)
(set (nth Img CY (- CX Rad)) 1)
(while (> Y X)
(when (ge0 F)
(dec 'Y)
(inc 'F (inc 'DdFy 2)) )
(inc 'X)
(inc 'F (inc (inc 'DdFx 2)))
(set (nth Img (+ CY Y) (+ CX X)) 1)
(set (nth Img (+ CY Y) (- CX X)) 1)
(set (nth Img (- CY Y) (+ CX X)) 1)
(set (nth Img (- CY Y) (- CX X)) 1)
(set (nth Img (+ CY X) (+ CX Y)) 1)
(set (nth Img (+ CY X) (- CX Y)) 1)
(set (nth Img (- CY X) (+ CX Y)) 1)
(set (nth Img (- CY X) (- CX Y)) 1) ) ) )
(let Img (make (do 120 (link (need 120 0)))) # Create image 120 x 120
(midPtCircle Img 60 60 50) # Draw circle
(out "img.pbm" # Write to bitmap file
(prinl "P1")
(prinl 120 " " 120)
(mapc prinl Img) ) ) |
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).
| #Lua | Lua | Bitmap.cubicbezier = function(self, x1, y1, x2, y2, x3, y3, x4, y4, nseg)
nseg = nseg or 10
local prevx, prevy, currx, curry
for i = 0, nseg do
local t = i / nseg
local a, b, c, d = (1-t)^3, 3*t*(1-t)^2, 3*t^2*(1-t), t^3
prevx, prevy = currx, curry
currx = math.floor(a * x1 + b * x2 + c * x3 + d * x4 + 0.5)
curry = math.floor(a * y1 + b * y2 + c * y3 + d * y4 + 0.5)
if i > 0 then
self:line(prevx, prevy, currx, curry)
end
end
end
local bitmap = Bitmap(61,21)
bitmap:clear()
bitmap:cubicbezier( 1,1, 15,41, 45,-20, 59,19 )
bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'}) |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #FOCAL | FOCAL | 1.01 T "Enter birthdate (y,m,d)",!
1.02 ASK Y,M,D
1.03 D 2; S BZ=Z
1.04 T "Enter today's date (y,m,d)",!
1.05 ASK Y,M,D
1.06 D 2; S DI=Z - BZ
1.07 T %6,"Age in days", DI,!
1.08 T "Physical cycle: "
1.09 S L=23; D 3
1.10 T "Emotional cycle: "
1.11 S L=28; D 3
1.12 T "Intellectual cycle: "
1.13 S L=33; D 3
1.14 Q
2.1 S QA = FITR((M + 9) / 12)
2.2 S QB = FITR(275 * M / 9)
2.3 S QC = FITR(7 * (Y + QA) / 4)
2.4 S Z = 367 * Y - QC + QB + D - 730530
3.1 S P = 100 * FSIN(2*3.1415926536*DI/L)
3.2 T %3,P,"%"
3.3 I (FABS(P)-15)4.1,5.1,5.1
4.1 T " CRITICAL",!
5.1 T ! |
http://rosettacode.org/wiki/Biorhythms | Biorhythms | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
Cycle
Length
Physical
23 days
Emotional
28 days
Mental
33 days
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
Output:
Day 10717:
Physical day 22: -27% (down but rising, next transition 1972-07-12)
Emotional day 21: valley
Mental day 25: valley
Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
| #Fortran | Fortran | C ------------------------------------------------------------------
PROGRAM BIORHYTHM
C ------------------------------------------------------------------
DOUBLE PRECISION GETJD
CHARACTER*3 DOW
DOUBLE PRECISION JD0, JD1, JD2, PI2, DIF
INTEGER BYEAR, BMON, BDAY, TYEAR, TMON, TDAY
INTEGER I, J, PHY, EMO, MEN, NDAY, DNUM, YR, DOY
CHARACTER*3 DNAME
CHARACTER*1 GRID, ROW(65)
C ------------------------------------------------------------------
PI2 = ACOS(-1.0D0)*2.0D0
WRITE(*,*) 'ENTER YOUR BIRTHDAY YYYY MM DD'
READ(*,*) BYEAR, BMON, BDAY
WRITE(*,*) 'ENTER START DATE YYYY MM DD'
READ(*,*) TYEAR, TMON, TDAY
WRITE(*,*) 'ENTER NUMBER OF DAYS TO PLOT'
READ(*,*) NDAY
JD0 = GETJD( TYEAR, 1, 1 )
JD1 = GETJD( BYEAR, BMON, BDAY )
JD2 = GETJD( TYEAR, TMON, TDAY )
WRITE(*,1010)
WRITE(*,1000) DOW(JD1), INT( JD2-JD1 )
WRITE(*,1010)
WRITE(*,1020)
DO I=1,NDAY
DIF = JD2 - JD1
PHY = INT(3.3D1+3.2D1*SIN( PI2 * DIF / 2.3D1 ))
EMO = INT(3.3D1+3.2D1*SIN( PI2 * DIF / 2.8D1 ))
MEN = INT(3.3D1+3.2D1*SIN( PI2 * DIF / 3.3D1 ))
IF ( PHY.LT.1 ) PHY = 1
IF ( EMO.LT.1 ) EMO = 1
IF ( MEN.LT.1 ) MEN = 1
IF ( PHY.GT.65 ) PHY = 65
IF ( EMO.GT.65 ) EMO = 65
IF ( MEN.GT.65 ) MEN = 65
DNAME = DOW(JD2)
DOY = INT(JD2-JD0)+1
IF ( DNAME.EQ.'SUN' ) THEN
GRID = '.'
ELSE
GRID = ' '
END IF
DO J=1,65
ROW(J) = GRID
END DO
ROW(1) = '|'
ROW(17) = ':'
ROW(33) = '|'
ROW(49) = ':'
ROW(65) = '|'
ROW(PHY) = 'P'
ROW(EMO) = 'E'
ROW(MEN) = 'M'
IF ( PHY.EQ.EMO ) ROW(PHY) = '*'
IF ( PHY.EQ.MEN ) ROW(PHY) = '*'
IF ( EMO.EQ.MEN ) ROW(EMO) = '*'
WRITE(*,1030) ROW,DNAME,DOY
JD2 = JD2 + 1.0D0
END DO
WRITE(*,1010)
C ------------------------------------------------------------------
1000 FORMAT( 'YOU WERE BORN ON A (', A3, ') YOU WERE ',I0,
$ ' DAYS OLD AT THE START.' )
1010 FORMAT( 75('=') )
1020 FORMAT( '-1',31X,'0',30X,'+1 DOY' )
1030 FORMAT( 1X,65A1, 1X, A3, 1X, I3 )
STOP
END
C ------------------------------------------------------------------
FUNCTION DOW( JD )
C ------------------------------------------------------------------
C RETURN THE ABBREVIATION FOR THE DAY OF THE WEEK
C JD JULIAN DATE - GREATER THAN 1721423.5 (JAN 1, 0001 SATURDAY)
C ------------------------------------------------------------------
DOUBLE PRECISION JD
INTEGER IDX
CHARACTER*3 DOW, NAMES(7)
DATA NAMES/'SAT','SUN','MON','TUE','WED','THR','FRI'/
IDX = INT(MODULO(JD-1.721423500D6,7.0D0)+1)
DOW = NAMES(IDX)
RETURN
END
C ------------------------------------------------------------------
FUNCTION ISGREG( Y, M, D )
C ------------------------------------------------------------------
C IS THIS DATE ON IN THE GREGORIAN CALENDAR
C DATES BEFORE OCT 5 1582 ARE JULIAN
C DATES AFTER OCT 14 1582 ARE GREGORIAN
C DATES OCT 5-14 1582 INCLUSIVE DO NOT EXIST
C ------------------------------------------------------------------
C YEAR 1-ANYTHING
C MONTH 1-12
C DAY 1-31
C ------------------------------------------------------------------
LOGICAL ISGREG
INTEGER Y, M, D
C ------------------------------------------------------------------
ISGREG=.TRUE.
IF ( Y.LT.1582 ) GOTO 888
IF ( Y.GT.1582 ) GOTO 999
IF ( M.LT.10 ) GOTO 888
IF ( M.GT.10 ) GOTO 999
IF ( D.LT.5 ) GOTO 888
IF ( D.GT.14 ) GOTO 999
WRITE(*,*) Y,M,D,' DOES NOT EXIST'
GOTO 999
888 CONTINUE
ISGREG=.FALSE.
999 CONTINUE
RETURN
END
C ------------------------------------------------------------------
FUNCTION GETJD( YEAR, MONTH, DAY )
C ------------------------------------------------------------------
C RETURN THE JULIAN DATE
C YEAR 1-ANYTHING
C MONTH 1-12
C DAY 1-31
C ------------------------------------------------------------------
DOUBLE PRECISION GETJD
INTEGER YEAR, MONTH, DAY
INTEGER Y, M, D, A, B, P1, P2
C ------------------------------------------------------------------
DOUBLE PRECISION TEMP
LOGICAL ISGREG, IG
IG = ISGREG( YEAR, MONTH, DAY )
Y = YEAR
M = MONTH
D = DAY
IF (M.LT.3) THEN
Y = Y - 1
M = M + 12
ENDIF
IF (IG) THEN
A = FLOOR( DBLE(Y) * 1.0D-2 )
B = 2 - A + FLOOR( DBLE(A) * 2.5D-1 )
ELSE
A = 0
B = 0
ENDIF
P1 = FLOOR( 3.65250D2 * DBLE(Y + 4716) )
P2 = FLOOR( 3.06001D1 * DBLE(M + 1) )
GETJD = DBLE(P1 + P2 + D + B) - 1.5245D3
RETURN
END |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.