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
| #i | i | main
//Bits aka Booleans.
b $= bit()
b $= true
print(b)
b $= false
print(b)
//Non-zero values are true.
b $= bit(1)
print(b)
b $= -1
print(b)
//Zero values are false
b $= 0
print(b)
} |
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
| #XBS | XBS | set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();
func caesar(text,shift:number=1){
set res:string="";
for(i=0;?text-1;1){
set t=text::at(i);
set n=(letters::find(t::upper())+shift)%?letters;
while(n<0){
n=?letters+n;
}
set l=letters[n];
(t::upper()==t)|=>l=l::lower()
res+=l;
}
send res;
}
func decode(text,shift:number=1){
set res:string="";
for(i=0;?text-1;1){
set t=text::at(i);
set n=(letters::find(t::upper())-shift)%?letters;
while(n<0){
n=?letters+n;
}
set l=letters[n];
(t::upper()==t)|=>l=l::lower()
res+=l;
}
send res;
}
set e=caesar("Hi",20);
set d=decode(e,20);
log(e);
log(d); |
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)..
| #FreeBASIC | FreeBASIC | ' version 04-11-2016
' compile with: fbc -s console
Dim As String names(0 To ...) = { "North", "North by east", "North-northeast", _
"Northeast by north", "Northeast", "Northeast by east", "East-northeast", _
"East by north", "East", "East by south", "East-southeast", _
"Southeast by east", "Southeast", "Southeast by south", "South-southeast", _
"South by east", "South", "South by west", "South-southwest", _
"Southwest by south", "Southwest", "Southwest by west", "West-southwest", _
"West by south", "West", "West by north", "West-northwest", _
"Northwest by west", "Northwest", "Northwest by north", "North-northwest", _
"North by west", "North" }
Dim As Double degrees(0 To ...) = { 0, 16.87, 16.88, 33.75, 50.62, 50.63, _
67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135, 151.87, 151.88, 168.75, _
185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270, _
286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 }
Dim As ULong i, j
For i = LBound(degrees) To UBound(degrees)
j = Int((degrees(i) + 5.625) / 11.25)
If j > 31 Then j = j - 32
Print Using "####.## ## "; degrees(i); j;
Print names(j)
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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.
| #Batch_File | Batch File |
@echo off
setlocal
set /a "a=%~1, b=%~2"
call :num2bin %a% aStr
call :num2bin %b% bStr
::AND
set /a "val=a&b"
call :display "%a% AND %b%" %val% %aStr% %bStr%
::OR
set /a "val=a|b"
call :display "%a% OR %b%" %val% %aStr% %bStr%
::XOR
set /a "val=a^b"
call :display "%a% XOR %b%" %val% %aStr% %bStr%
::NOT
set /a "val=~a"
call :display "NOT %a%" %val% %aStr%
::LEFT SHIFT
set /a "val=a<<b"
call :display "%a% Left Shift %b%" %val% %aStr%
::ARITHMETIC RIGHT SHIFT
set /a "val=a>>b"
call :display "%a% Arithmetic Right Shift %b%" %val% %aStr%
::The remaining operations do not have native support
::The implementations use additional operators
:: %% = mod
:: ! = logical negation where !(zero)=1 and !(non-zero)=0
:: * = multiplication
:: - = subtraction
::LOGICAL RIGHT SHIFT (No native support)
set /a "val=(a>>b)&~((0x80000000>>b-1)*!!b)"
call :display "%a% Logical Right Shift %b%" %val% %aStr%
::ROTATE LEFT (No native support)
set /a "val=(a<<b%%32) | (a>>32-b%%32)&~((0x80000000>>31-b%%32)*!!(32-b%%32))"
call :display "%a% Rotate Left %b%" %val% %aStr%
::ROTATE RIGHT (No native support)
set /a "val=(a<<32-b%%32) | (a>>b%%32)&~((0x80000000>>b%%32-1)*!!(b%%32)) "
call :display "%a% Rotate Right %b%" %val% %aStr%
exit /b
:display op result aStr [bStr]
echo(
echo %~1 = %2
echo %3
if "%4" neq "" echo %4
call :num2bin %2
exit /b
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
set n=%~1
set rtn=
for /l %%b in (0,1,31) do (
set /a "d=n&1, n>>=1"
set rtn=!d!!rtn!
)
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b
|
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.
| #Axe | Axe | Buff(768)→Pic1
Fill(Pic1,768,255)
Pxl-Off(45,30,Pic1)
.Display the bitmap to demonstrate
Copy(Pic1)
DispGraph
Pause 4500
Disp pxl-Test(50,50,Pic1)▶Dec,i |
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).
| #Ruby | Ruby | Pixel = Struct.new(:x, :y)
class Pixmap
def draw_circle(pixel, radius, colour)
validate_pixel(pixel.x, pixel.y)
self[pixel.x, pixel.y + radius] = colour
self[pixel.x, pixel.y - radius] = colour
self[pixel.x + radius, pixel.y] = colour
self[pixel.x - radius, pixel.y] = colour
f = 1 - radius
ddF_x = 1
ddF_y = -2 * radius
x = 0
y = radius
while x < y
if f >= 0
y -= 1
ddF_y += 2
f += ddF_y
end
x += 1
ddF_x += 2
f += ddF_x
self[pixel.x + x, pixel.y + y] = colour
self[pixel.x + x, pixel.y - y] = colour
self[pixel.x - x, pixel.y + y] = colour
self[pixel.x - x, pixel.y - y] = colour
self[pixel.x + y, pixel.y + x] = colour
self[pixel.x + y, pixel.y - x] = colour
self[pixel.x - y, pixel.y + x] = colour
self[pixel.x - y, pixel.y - x] = colour
end
end
end
bitmap = Pixmap.new(30, 30)
bitmap.draw_circle(Pixel[14,14], 12, RGBColour::BLACK) |
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).
| #Python | Python | def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append( (x, y) )
for i in range(n):
self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier
bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
'''
The origin, 0,0; is the lower left, with x increasing to the right,
and Y increasing upwards.
The chardisplay above produces the following output :
+-----------------+
| |
| |
| |
| |
| @@@@ |
| @@@ @@@ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @@@@ |
| @@@@|
| |
+-----------------+
''' |
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).
| #R | R | # x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
{
outx <- NULL
outy <- NULL
i <- 1
for (t in seq(0, 1, length.out=n))
{
b <- bez(x, y, t)
outx[i] <- b$x
outy[i] <- b$y
i <- i+1
}
return (list(x=outx, y=outy))
}
bez <- function(x, y, t)
{
outx <- 0
outy <- 0
n <- length(x)-1
for (i in 0:n)
{
outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
}
return (list(x=outx, y=outy))
}
# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red") |
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...
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | targetdate = "1972-07-11";
birthdate = "1943-03-09";
targetdate //= DateObject;
birthdate //= DateObject;
cyclelabels = {"Physical", "Emotional", "Mental"};
cyclelengths = {23, 28, 33};
quadrants = {{"up and rising", "peak"}, {"up but falling",
"transition"}, {"down and falling", "valley"}, {"down but rising",
"transition"}};
d = QuantityMagnitude[DateDifference[birthdate, targetdate], "Days"];
Print["Day ", d, ":"];
Do[
label = cyclelabels[[i]];
length = cyclelengths[[i]];
position = Mod[d, length];
quadrant = Floor[4 (position + 1)/length];
percentage = Round[100*Sin[2*Pi*position/length]];
transitiondate =
DatePlus[targetdate, Floor[(quadrant + 1)/4*length] - position];
{trend, next} = quadrants[[quadrant]];
If[percentage > 95,
description = "peak"
,
If[percentage < -95,
description = "valley"
,
If[Abs[percentage] < 5,
description = "critical transition"
,
description =
ToString[percentage] <> "% (" <> trend <> ", next " <> next <>
" " <> DateString[transitiondate, "ISODate"] <> ")"
]
]
];
Print[label <> " day " <> ToString[position] <> ": " <>
description];
,
{i, 3}
] |
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...
| #Nim | Nim | import math
import strformat
import times
type Cycle {.pure.} = enum Physical, Emotional, Mental
const
Lengths: array[Cycle, int] = [23, 28, 33]
Quadrants = [("up and rising", "peak"),
("up but falling", "transition"),
("down and falling", "valley"),
("down but rising", "transition")]
DateFormat = "YYYY-MM-dd"
#---------------------------------------------------------------------------------------------------
proc biorythms(birthDate: DateTime; targetDate: DateTime = now()) =
## Display biorythms data. Arguments are DateTime values.
echo fmt"Born {birthDate.format(DateFormat)}, target date {targetDate.format(DateFormat)}"
let days = (targetDate - birthDate).inDays
echo "Day ", days
for cycle, length in Lengths:
let position = int(days mod length)
let quadrant = int(4 * position / length)
let percentage = round(100 * sin(2 * PI * (position / length)), 1)
var description: string
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
let (trend, next) = Quadrants[quadrant]
let transition = targetDate + initDuration(days = (quadrant + 1) * length div 4 - position)
description = fmt"{percentage}% ({trend}, next {next} {transition.format(DateFormat)})"
echo fmt"{cycle} day {position}: {description}"
echo ""
#---------------------------------------------------------------------------------------------------
proc biorythms(birthDate, targetDate = "") =
## Display biorythms data. Arguments are strings in ISO format year-month-day.
let date = if targetDate.len == 0: now() else: targetDate.parse(DateFormat)
biorythms(birthDate.parse(DateFormat), date)
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
biorythms("1943-03-09", "1972-07-11")
biorythms("1809-01-12", "1863-11-19")
biorythms("1809-02-12", "1863-11-19") |
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...
| #Perl | Perl | use strict;
use warnings;
use DateTime;
use constant PI => 2 * atan2(1, 0);
my %cycles = ( 'Physical' => 23, 'Emotional' => 28, 'Mental' => 33 );
my @Q = ( ['up and rising', 'peak'],
['up but falling', 'transition'],
['down and falling', 'valley'],
['down but rising', 'transition']
);
my $target = DateTime->new(year=>1863, month=>11, day=>19);
my $bday = DateTime->new(year=>1809, month=> 2, day=>12);
my $days = $bday->delta_days( $target )->in_units('days');
print "Day $days:\n";
for my $label (sort keys %cycles) {
my($length) = $cycles{$label};
my $position = $days % $length;
my $quadrant = int $position / $length * 4;
my $percentage = int(sin($position / $length * 2 * PI )*1000)/10;
my $description;
if ( $percentage > 95) { $description = 'peak' }
elsif ( $percentage < -95) { $description = 'valley' }
elsif (abs($percentage) < 5) { $description = 'critical transition' }
else {
my $transition = $target->clone->add( days => (int(($quadrant + 1)/4 * $length) - $position))->ymd;
my ($trend, $next) = @{$Q[$quadrant]};
$description = sprintf "%5.1f%% ($trend, next $next $transition)", $percentage;
}
printf "%-13s %2d: %s", "$label day\n", $position, $description;
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #11l | 11l | V x = Bytes(‘abc’)
print(x[0]) |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
// Map each character to a counter
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
} |
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.
| #C.23 | C# | using System;
using System.Drawing;
using System.Drawing.Imaging;
static class Program
{
static void Main()
{
new Bitmap(200, 200)
.DrawLine(0, 0, 199, 199, Color.Black).DrawLine(199,0,0,199,Color.Black)
.DrawLine(50, 75, 150, 125, Color.Blue).DrawLine(150, 75, 50, 125, Color.Blue)
.Save("line.png", ImageFormat.Png);
}
static Bitmap DrawLine(this Bitmap bitmap, int x0, int y0, int x1, int y1, Color color)
{
int dx = Math.Abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = Math.Abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = (dx > dy ? dx : -dy) / 2, e2;
for(;;) {
bitmap.SetPixel(x0, y0, color);
if (x0 == x1 && y0 == y1) break;
e2 = err;
if (e2 > -dx) { err -= dy; x0 += sx; }
if (e2 < dy) { err += dx; y0 += sy; }
}
return bitmap;
}
} |
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. | #Java | Java | import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
} |
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.
| #Oberon-2 | Oberon-2 |
MODULE BitcoinAddress;
IMPORT
Object,
NPCT:Tools,
Crypto:SHA256,
S := SYSTEM,
Out;
CONST
BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
TYPE
BC_RAW = ARRAY 25 OF CHAR;
SHA256_HASH = ARRAY 32 OF CHAR;
VAR
b58: Object.CharsLatin1;
PROCEDURE IndexOfB58Char(c: CHAR): INTEGER;
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE (b58[i] # 0X) & (b58[i] # c) DO INC(i) END;
IF b58[i] = 0X THEN RETURN -1 ELSE RETURN i END
END IndexOfB58Char;
PROCEDURE DecodeB58(s [NO_COPY]: ARRAY OF CHAR;VAR out: BC_RAW): BOOLEAN;
VAR
i,j,k: LONGINT;
BEGIN
FOR i := 0 TO LEN(out) - 1 DO; out[i] := CHR(0) END;
i := 0;
WHILE (s[i] # 0X) DO;
k := IndexOfB58Char(s[i]);
IF k < 0 THEN
Out.String("Error: Bad base58 character");Out.Ln;
RETURN FALSE
END;
FOR j := LEN(out) - 1 TO 0 BY -1 DO
k := k + 58 * ORD(out[j]);
out[j] := CHR(k MOD 256);
k := k DIV 256;
END;
IF k # 0 THEN Out.String("Error: Address to long");Out.Ln; RETURN FALSE END;
INC(i)
END;
RETURN TRUE
END DecodeB58;
PROCEDURE Valid(s [NO_COPY]: ARRAY OF CHAR): BOOLEAN;
VAR
dec: BC_RAW;
d1, d2: SHA256.Hash;
d1Str, d2Str: SHA256_HASH;
x,y: LONGINT;
BEGIN
Out.String(s);Out.String(" is valid? ");
IF ~DecodeB58(s,dec) THEN RETURN FALSE END;
d1 := SHA256.NewHash();d1.Initialize();
d2 := SHA256.NewHash();d2.Initialize();
d1.Update(dec,0,21);d1.GetHash(d1Str,0);
d2.Update(d1Str,0,d1.size);d2.GetHash(d2Str,0);
S.MOVE(S.ADR(dec) + 21,S.ADR(x),4);
S.MOVE(S.ADR(d2Str),S.ADR(y),4);
RETURN (x = y)
END Valid;
BEGIN
b58 := Tools.AsString(BASE58);
Out.Bool(Valid("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9"));Out.Ln;
Out.Bool(Valid("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"));Out.Ln;
Out.Bool(Valid("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9"));Out.Ln;
Out.Bool(Valid("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"));Out.Ln
END BitcoinAddress.
|
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.
| #Julia | Julia | using Images, FileIO
function floodfill!(img::Matrix{<:Color}, initnode::CartesianIndex{2}, target::Color, replace::Color)
img[initnode] != target && return img
# constants
north = CartesianIndex(-1, 0)
south = CartesianIndex( 1, 0)
east = CartesianIndex( 0, 1)
west = CartesianIndex( 0, -1)
queue = [initnode]
while !isempty(queue)
node = pop!(queue)
if img[node] == target
wnode = node
enode = node + east
end
# Move west until color of node does not match target color
while checkbounds(Bool, img, wnode) && img[wnode] == target
img[wnode] = replace
if checkbounds(Bool, img, wnode + north) && img[wnode + north] == target
push!(queue, wnode + north)
end
if checkbounds(Bool, img, wnode + south) && img[wnode + south] == target
push!(queue, wnode + south)
end
wnode += west
end
# Move east until color of node does not match target color
while checkbounds(Bool, img, enode) && img[enode] == target
img[enode] = replace
if checkbounds(Bool, img, enode + north) && img[enode + north] == target
push!(queue, enode + north)
end
if checkbounds(Bool, img, enode + south) && img[enode + south] == target
push!(queue, enode + south)
end
enode += east
end
end
return img
end
img = Gray{Bool}.(load("data/unfilledcircle.png"))
floodfill!(img, CartesianIndex(100, 100), Gray(false), Gray(true))
save("data/filledcircle.png", img) |
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.
| #Kotlin | Kotlin | // version 1.1.4-3
import java.awt.Color
import java.awt.Point
import java.awt.image.BufferedImage
import java.util.LinkedList
import java.io.File
import javax.imageio.ImageIO
import javax.swing.JOptionPane
import javax.swing.JLabel
import javax.swing.ImageIcon
fun floodFill(image: BufferedImage, node: Point, targetColor: Color, replColor: Color) {
val target = targetColor.getRGB()
val replacement = replColor.getRGB()
if (target == replacement) return
val width = image.width
val height = image.height
val queue = LinkedList<Point>()
var nnode: Point? = node
do {
var x = nnode!!.x
val y = nnode.y
while (x > 0 && image.getRGB(x - 1, y) == target) x--
var spanUp = false
var spanDown = false
while (x < width && image.getRGB(x, y) == target) {
image.setRGB(x, y, replacement)
if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
queue.add(Point(x, y - 1))
spanUp = true
}
else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) {
spanUp = false
}
if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) {
queue.add(Point(x, y + 1))
spanDown = true
}
else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) {
spanDown = false
}
x++
}
nnode = queue.pollFirst()
}
while (nnode != null)
}
fun main(args: Array<String>) {
val image = ImageIO.read(File("Unfilledcirc.png"))
floodFill(image, Point(50, 50), Color.white, Color.yellow)
val title = "Floodfilledcirc.png"
ImageIO.write(image, "png", File(title))
JOptionPane.showMessageDialog(null, JLabel(ImageIcon(image)), title, JOptionPane.PLAIN_MESSAGE)
} |
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
| #Icon_and_Unicon | Icon and Unicon | Idris> :doc Bool
Data type Prelude.Bool.Bool : Type
Boolean Data Type
Constructors:
False : Bool
True : Bool
|
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
| #Idris | Idris | Idris> :doc Bool
Data type Prelude.Bool.Bool : Type
Boolean Data Type
Constructors:
False : Bool
True : Bool
|
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
| #XLISP | XLISP | (defun caesar-encode (text key)
(defun encode (ascii-code)
(defun rotate (character alphabet)
(define code (+ character key))
(cond
((> code (+ alphabet 25)) (- code 26))
((< code alphabet) (+ code 26))
(t code)))
(cond
((and (>= ascii-code 65) (<= ascii-code 90)) (rotate ascii-code 65))
((and (>= ascii-code 97) (<= ascii-code 122)) (rotate ascii-code 97))
(t ascii-code)))
(list->string (mapcar integer->char (mapcar encode (mapcar char->integer (string->list text))))))
(defun caesar-decode (text key)
(caesar-encode text (- 26 key))) |
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)..
| #Gambas | Gambas | Public Sub Main()
Dim fDeg As Float[] = [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]
Dim cHeading As Collection = ["N": "North", "S": "South", "W": "West", "E": "East", "b": "by"]
Dim sHeading As String[] = ["N", "NbE", "NNE", "NEbE", "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"]
Dim siLoop As Short
Dim sDirection As String
Dim fCount, fTemp As Float
For Each fCount In fDeg
fTemp = Round(fCount / 11.25)
If fTemp = 32 Then fTemp = 0
For siLoop = 0 To Len(sHeading[fTemp])
sDirection &= cHeading[Mid(sHeading[fTemp], siLoop + 1, 1)] & " "
Next
Print "Index=" & Format(fTemp + 1, "#0") & " " & Format(Str(fCount), "##0.00") & " degrees = " & sDirection
sDirection = ""
Next
End |
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.
| #BBC_BASIC | BBC BASIC | number1% = &89ABCDEF
number2% = 8
PRINT ~ number1% AND number2% : REM bitwise AND
PRINT ~ number1% OR number2% : REM bitwise OR
PRINT ~ number1% EOR number2% : REM bitwise exclusive-OR
PRINT ~ NOT number1% : REM bitwise NOT
PRINT ~ number1% << number2% : REM left shift
PRINT ~ number1% >>> number2% : REM right shift (logical)
PRINT ~ number1% >> number2% : REM right shift (arithmetic)
PRINT ~ (number1% << number2%) OR (number1% >>> (32-number2%)) : REM left rotate
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate |
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.
| #BASIC256 | BASIC256 | graphsize 30,30
call fill(rgb(255,0,0))
call setpixel(10,10,rgb(0,255,255))
print "pixel 10,10 is " + pixel(10,10)
print "pixel 20,20 is " + pixel(20,10)
imgsave "BASIC256_bitmap.png"
end
subroutine fill(c)
color c
rect 0,0,graphwidth, graphheight
end subroutine
subroutine setpixel(x,y,c)
color c
plot x,y
end subroutine |
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).
| #Scala | Scala | object BitmapOps {
def midpoint(bm:RgbBitmap, x0:Int, y0:Int, radius:Int, c:Color)={
var f=1-radius
var ddF_x=1
var ddF_y= -2*radius
var x=0
var y=radius
bm.setPixel(x0, y0+radius, c)
bm.setPixel(x0, y0-radius, c)
bm.setPixel(x0+radius, y0, c)
bm.setPixel(x0-radius, y0, c)
while(x < y)
{
if(f >= 0)
{
y-=1
ddF_y+=2
f+=ddF_y
}
x+=1
ddF_x+=2
f+=ddF_x
bm.setPixel(x0+x, y0+y, c)
bm.setPixel(x0-x, y0+y, c)
bm.setPixel(x0+x, y0-y, c)
bm.setPixel(x0-x, y0-y, c)
bm.setPixel(x0+y, y0+x, c)
bm.setPixel(x0-y, y0+x, c)
bm.setPixel(x0+y, y0-x, c)
bm.setPixel(x0-y, y0-x, c)
}
}
} |
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).
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc drawCircle {image colour point radius} {
lassign $point x0 y0
setPixel $image $colour [list $x0 [expr {$y0 + $radius}]]
setPixel $image $colour [list $x0 [expr {$y0 - $radius}]]
setPixel $image $colour [list [expr {$x0 + $radius}] $y0]
setPixel $image $colour [list [expr {$x0 - $radius}] $y0]
set f [expr {1 - $radius}]
set ddF_x 1
set ddF_y [expr {-2 * $radius}]
set x 0
set y $radius
while {$x < $y} {
assert {$ddF_x == 2 * $x + 1}
assert {$ddF_y == -2 * $y}
assert {$f == $x*$x + $y*$y - $radius*$radius + 2*$x - $y + 1}
if {$f >= 0} {
incr y -1
incr ddF_y 2
incr f $ddF_y
}
incr x
incr ddF_x 2
incr f $ddF_x
setPixel $image $colour [list [expr {$x0 + $x}] [expr {$y0 + $y}]]
setPixel $image $colour [list [expr {$x0 - $x}] [expr {$y0 + $y}]]
setPixel $image $colour [list [expr {$x0 + $x}] [expr {$y0 - $y}]]
setPixel $image $colour [list [expr {$x0 - $x}] [expr {$y0 - $y}]]
setPixel $image $colour [list [expr {$x0 + $y}] [expr {$y0 + $x}]]
setPixel $image $colour [list [expr {$x0 - $y}] [expr {$y0 + $x}]]
setPixel $image $colour [list [expr {$x0 + $y}] [expr {$y0 - $x}]]
setPixel $image $colour [list [expr {$x0 - $y}] [expr {$y0 - $x}]]
}
}
# create the image and display it
set img [newImage 200 100]
label .l -image $img
pack .l
fill $img black
drawCircle $img blue {100 50} 49 |
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).
| #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 p3)
(for/list ([t (in-range 0.0 1.0 (/ 1.0 20))])
(int t (int t p0 p1) (int t p2 p3))))
(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) '(15 11)))
bm
|
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).
| #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) {
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 cubic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), ($x4, $y4), $pix, $segments = 30 ) {
my @line-segments = map -> $t {
my \a = (1-$t)³;
my \b = $t * (1-$t)² * 3;
my \c = $t² * (1-$t) * 3;
my \d = $t³;
(a*$x1 + b*$x2 + c*$x3 + d*$x4).round(1),(a*$y1 + b*$y2 + c*$y3 + d*$y4).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 = (85,390), (5,5), (580,370), (270,10);
my %seen;
my $c = 0;
for @points.permutations -> @this {
%seen{@this.reverse.join.Str}++;
next if %seen{@this.join.Str};
$b.cubic( |@this, color(255-$c,127,$c+=22) );
}
@points.map: { $b.dot( $_, color(255,0,0), 3 )}
$*OUT.write: $b.P6; |
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...
| #Phix | Phix | with javascript_semantics
include timedate.e
constant cycles = {"Physical day ", "Emotional day", "Mental day "},
lengths = {23, 28, 33},
quadrants = {{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"}}
procedure biorhythms(string birthDate, targetDate)
timedate bd = parse_date_string(birthDate,{"YYYY-MM-DD"}),
td = parse_date_string(targetDate,{"YYYY-MM-DD"})
integer days = floor(timedate_diff(bd, td, DT_DAY)/(60*60*24))
printf(1,"Born %s, Target %s\n",{birthDate,targetDate})
printf(1,"Day %d\n",days)
for i=1 to 3 do
integer len = lengths[i],
posn = remainder(days,len),
quadrant = floor(posn/len*4)+1
atom percent = floor(sin(2*PI*posn/len)*1000)/10
string cycle = cycles[i],
desc = iff(percent>95 ? " peak" :
iff(percent<-95 ? " valley" :
iff(abs(percent)<5 ? " critical transition" : "other")))
if desc == "other" then
timedate t = adjust_timedate(td,timedelta(days:=floor(quadrant/4*len)-posn))
string transition = format_timedate(t,"YYYY-MM-DD"),
{trend,next} = quadrants[quadrant]
desc = sprintf("%5.1f%% (%s, next %s %s)", {percent, trend, next, transition})
end if
printf(1,"%s %2d : %s\n", {cycle, posn, desc})
end for
printf(1,"\n")
end procedure
constant datePairs = {
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"} // correct DOB for Abraham Lincoln
}
for i=1 to length(datePairs) do biorhythms(datePairs[i][1], datePairs[i][2]) end for
|
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #8086_Assembly | 8086 Assembly | ;this code assumes that both DS and ES point to the correct segments.
cld
mov si,offset TestMessage
mov di,offset EmptyRam
mov cx,5 ;length of the source string, you'll need to either know this
;ahead of time or calculate it.
rep movsb
ret
;there is no buffer overflow protection built into these functions so be careful!
TestMessage byte "Hello"
EmptyRam byte 0,0,0,0,0 |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #11l | 11l | F bisect_right(a, x)
V lo = 0
V hi = a.len
L lo < hi
V mid = (lo + hi) I/ 2
I x < a[mid]
hi = mid
E
lo = mid + 1
R lo
F bin_it(limits, data)
‘Bin data according to (ascending) limits.’
V bins = [0] * (limits.len + 1)
L(d) data
bins[bisect_right(limits, d)]++
R bins
F bin_print(limits, bins)
print(‘ < #3 := #3’.format(limits[0], bins[0]))
L(lo, hi, count) zip(limits, limits[1..], bins[1..])
print(‘>= #3 .. < #3 := #3’.format(lo, hi, count))
print(‘>= #3 := #3’.format(limits.last, bins.last))
print("RC FIRST EXAMPLE\n")
V limits = [23, 37, 43, 53, 67, 83]
V data = [95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55]
V bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins) |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi |
program base_count;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Generics.Collections,
System.Console;
const
DNA = 'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG' +
'CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' +
'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT' +
'GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT' +
'CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG' +
'TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA' +
'TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT' +
'CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG' +
'TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC' +
'GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT';
procedure Println(code: ansistring);
var
c: ansichar;
begin
console.ForegroundColor := TConsoleColor.Black;
for c in code do
begin
case c of
'A':
console.BackgroundColor := TConsoleColor.Red;
'C':
console.BackgroundColor := TConsoleColor.Blue;
'T':
console.BackgroundColor := TConsoleColor.Green;
'G':
console.BackgroundColor := TConsoleColor.Yellow;
else
console.BackgroundColor := TConsoleColor.Black;
end;
console.Write(c);
end;
console.ForegroundColor := TConsoleColor.White;
console.BackgroundColor := TConsoleColor.Black;
console.WriteLine;
end;
begin
console.WriteLine('SEQUENCE:');
var le := Length(DNA);
var index := 0;
while index < le do
begin
Write(index: 5, ': ');
Println(dna.Substring(index, 50));
inc(index, 50);
end;
var baseMap := TDictionary<byte, integer>.Create;
for var i := 1 to le do
begin
var key := ord(dna[i]);
if baseMap.ContainsKey(key) then
baseMap[key] := baseMap[key] + 1
else
baseMap.Add(key, 1);
end;
var bases: TArray<byte>;
for var k in baseMap.Keys do
begin
SetLength(bases, Length(bases) + 1);
bases[High(bases)] := k;
end;
TArray.Sort<Byte>(bases);
console.WriteLine(#10'BASE COUNT:');
for var base in bases do
console.WriteLine(' {0}: {1}', [ansichar(base), baseMap[base]]);
console.WriteLine(' ------');
console.WriteLine(' S: {0}', [le]);
console.WriteLine(' ======');
readln;
end. |
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.
| #C.2B.2B | C++ |
void Line( float x1, float y1, float x2, float y2, const Color& color )
{
// Bresenham's line algorithm
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<=maxX; x++)
{
if(steep)
{
SetPixel(y,x, color);
}
else
{
SetPixel(x,y, color);
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
|
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. | #JavaScript | JavaScript | // Basic set-up
const numBases = 250
const numMutations = 30
const bases = ['A', 'C', 'G', 'T'];
// Utility functions
/**
* Return a shallow copy of an array
* @param {Array<*>} arr
* @returns {*[]}
*/
const copy = arr => [...arr];
/**
* Get a random int up to but excluding the the given number
* @param {number} max
* @returns {number}
*/
const randTo = max => (Math.random() * max) | 0;
/**
* Given an array return a random element and the index of that element from
* the array.
* @param {Array<*>} arr
* @returns {[*[], number]}
*/
const randSelect = arr => {
const at = randTo(arr.length);
return [arr[at], at];
};
/**
* Given a number or string, return a left padded string
* @param {string|number} v
* @returns {string}
*/
const pad = v => ('' + v).padStart(4, ' ');
/**
* Count the number of elements that match the given value in an array
* @param {Array<string>} arr
* @returns {function(string): number}
*/
const filterCount = arr => s => arr.filter(e => e === s).length;
/**
* Utility logging function
* @param {string|number} v
* @param {string|number} n
*/
const print = (v, n) => console.log(`${pad(v)}:\t${n}`)
/**
* Utility function to randomly select a new base, and an index in the given
* sequence.
* @param {Array<string>} seq
* @param {Array<string>} bases
* @returns {[string, string, number]}
*/
const getVars = (seq, bases) => {
const [newBase, _] = randSelect(bases);
const [extBase, randPos] = randSelect(seq);
return [newBase, extBase, randPos];
};
// Bias the operations
/**
* Given a map of function to ratio, return an array of those functions
* appearing ratio number of times in the array.
* @param weightMap
* @returns {Array<function>}
*/
const weightedOps = weightMap => {
return [...weightMap.entries()].reduce((p, [op, weight]) =>
[...p, ...(Array(weight).fill(op))], []);
};
// Pretty Print functions
const prettyPrint = seq => {
let idx = 0;
const rem = seq.reduce((p, c) => {
const s = p + c;
if (s.length === 50) {
print(idx, s);
idx = idx + 50;
return '';
}
return s;
}, '');
if (rem !== '') {
print(idx, rem);
}
}
const printBases = seq => {
const filterSeq = filterCount(seq);
let tot = 0;
[...bases].forEach(e => {
const cnt = filterSeq(e);
print(e, cnt);
tot = tot + cnt;
})
print('Σ', tot);
}
// Mutation definitions
const swap = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 1, newBase);
return [[...hist, `Swapped ${extBase} for ${newBase} at ${randPos}`], arr];
};
const del = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 1);
return [[...hist, `Deleted ${extBase} at ${randPos}`], arr];
}
const insert = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 0, newBase);
return [[...hist, `Inserted ${newBase} at ${randPos}`], arr];
}
// Create the starting sequence
const seq = Array(numBases).fill(undefined).map(
() => randSelect(bases)[0]);
// Create a weighted set of mutations
const weightMap = new Map()
.set(swap, 1)
.set(del, 1)
.set(insert, 1);
const operations = weightedOps(weightMap);
const mutations = Array(numMutations).fill(undefined).map(
() => randSelect(operations)[0]);
// Mutate the sequence
const [hist, mut] = mutations.reduce((p, c) => c(p), [[], seq]);
console.log('ORIGINAL SEQUENCE:')
prettyPrint(seq);
console.log('\nBASE COUNTS:')
printBases(seq);
console.log('\nMUTATION LOG:')
hist.forEach((e, i) => console.log(`${i}:\t${e}`));
console.log('\nMUTATED SEQUENCE:')
prettyPrint(mut);
console.log('\nMUTATED BASE COUNTS:')
printBases(mut);
|
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.
| #Perl | Perl | my @b58 = qw{
1 2 3 4 5 6 7 8 9
A B C D E F G H J K L M N P Q R S T U V W X Y Z
a b c d e f g h i j k m n o p q r s t u v w x y z
};
my %b58 = map { $b58[$_] => $_ } 0 .. 57;
sub unbase58 {
use integer;
my @out;
my $azeroes = length($1) if $_[0] =~ /^(1*)/;
for my $c ( map { $b58{$_} } $_[0] =~ /./g ) {
for (my $j = 25; $j--; ) {
$c += 58 * ($out[$j] // 0);
$out[$j] = $c % 256;
$c /= 256;
}
}
my $bzeroes = length($1) if join('', @out) =~ /^(0*)/;
die "not a 25 byte address\n" if $bzeroes != $azeroes;
return @out;
}
sub check_bitcoin_address {
# Does nothing if address is valid
# dies otherwise
use Digest::SHA qw(sha256);
my @byte = unbase58 shift;
die "wrong checksum\n" unless
(pack 'C*', @byte[21..24]) eq
substr sha256(sha256 pack 'C*', @byte[0..20]), 0, 4;
} |
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.
| #Liberty_BASIC | Liberty BASIC | 'This example requires the Windows API
NoMainWin
WindowWidth = 267.5
WindowHeight = 292.5
UpperLeftX=int((DisplayWidth-WindowWidth)/2)
UpperLeftY=int((DisplayHeight-WindowHeight)/2)
Global hDC : hDC = GetDC(0)
Struct point, x As long, y As long
Struct RGB, Red As long, Green As long, Blue As long
Struct rect, left As long, top As long, right As long, bottom As long
StyleBits #main.gbox, 0, _WS_BORDER, 0, 0
GraphicBox #main.gbox, 2.5, 2.5, 253, 252
Open "Flood Fill - Click a Color" For Window As #main
Print #main, "TrapClose quit"
Print #main.gbox, "Down; Fill Black; Place 125 125; BackColor White; " _
+ "CircleFilled 115; Place 105 105; BackColor Black; CircleFilled 50; Flush"
Print #main.gbox, "When leftButtonUp gBoxClick"
Print #main.gbox, "Size 1"
Wait
Sub quit handle$
Call ReleaseDC 0, hDC
Close #main
End
End Sub
Sub gBoxClick handle$, MouseX, MouseY
result = GetCursorPos()
targetRGB = GetPixel(hDC, point.x.struct, point.y.struct)
ColorDialog "", replacementColor$
If replacementColor$ = "" Then Exit Sub
Print #main.gbox, "Color " + Word$(replacementColor$, 1) + " " + Word$(replacementColor$, 2) + " " + Word$(replacementColor$, 3)
result = FloodFill(MouseX, MouseY, targetRGB)
Print #main.gbox, "DelSegment FloodFill"
Print #main.gbox, "GetBMP FloodFill 0 0 500 500; CLS; DrawBMP FloodFill 0 0; Flush FloodFill"
Notice "Complete!"
UnLoadBMP "FloodFill"
End Sub
Sub ReleaseDC hWnd, hDC
CallDLL #user32,"ReleaseDC", hWnd As uLong, hDC As uLong, ret As Long
End Sub
Function GetDC(hWnd)
CallDLL #user32, "GetDC", hWnd As uLong, GetDC As uLong
End Function
Function GetCursorPos()
CallDLL #user32, "GetCursorPos", point As struct, GetCursorPos As uLong
End Function
Function GetPixel(hDC, x, y)
CallDLL #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long
End Function
Function getLongRGB(RGB.Blue)
getLongRGB = (RGB.Blue * (256 * 256))
End Function
Function GetWindowRect(hWnd)
'Get ClientRectangle
CallDLL #user32, "GetWindowRect", hWnd As ulong, rect As struct, GetWindowRect As ulong
End Function
Function FloodFill(mouseXX, mouseYY, targetColor)
Scan
result = GetWindowRect(Hwnd(#main.gbox))
X = Int(mouseXX + rect.left.struct)
Y = Int(mouseYY + rect.top.struct)
If (GetPixel(hDC, X, Y) <> targetColor) Then
Exit Function
Else
CLS
Print str$(mouseXX) + " " + str$(mouseYY)
Print #main.gbox, "Set " + str$(mouseXX) + " " + str$(mouseYY)
End If
If (mouseXX > 0) And (mouseXX < 253) Then
result = FloodFill((mouseXX - 1), mouseYY, targetColor)
result = FloodFill((mouseXX + 1), mouseYY, targetColor)
End If
If (mouseYY > 0) And (mouseYY < 252) Then
result = FloodFill(mouseXX, (mouseYY + 1), targetColor)
result = FloodFill(mouseXX, (mouseYY - 1), targetColor)
End If
End Function |
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
| #Inform_6 | Inform 6 | let B be whether or not 123 is greater than 100; |
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
| #Inform_7 | Inform 7 | let B be whether or not 123 is greater than 100; |
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
| #J | J | $ jq type
true
"boolean"
false
"boolean"
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #XPL0 | XPL0 | code ChIn=7, ChOut=8, IntIn=10;
int Key, C;
[Key:= IntIn(8);
repeat C:= ChIn(1);
if C>=^a & C<=^z then C:= C-$20;
if C>=^A & C<=^Z then
[C:= C+Key;
if C>^Z then C:= C-26
else if C<^A then C:= C+26;
];
ChOut(0, C);
until C=$1A; \EOF
] |
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)..
| #Go | Go | package main
import "fmt"
// function required by task
func degrees2compasspoint(h float32) string {
return compassPoint[cpx(h)]
}
// cpx returns integer index from 0 to 31 corresponding to compass point.
// input heading h is in degrees. Note this index is a zero-based index
// suitable for indexing into the table of printable compass points,
// and is not the same as the index specified to be printed in the output.
func cpx(h float32) int {
x := int(h/11.25+.5) % 32
if x < 0 {
x += 32
}
return x
}
// printable compass points
var compassPoint = []string{
"North",
"North by east",
"North-northeast",
"Northeast by north",
"Northeast",
"Northeast by east",
"East-northeast",
"East by north",
"East",
"East by south",
"East-southeast",
"Southeast by east",
"Southeast",
"Southeast by south",
"South-southeast",
"South by east",
"South",
"South by west",
"South-southwest",
"Southwest by south",
"Southwest",
"Southwest by west",
"West-southwest",
"West by south",
"West",
"West by north",
"West-northwest",
"Northwest by west",
"Northwest",
"Northwest by north",
"North-northwest",
"North by west",
}
func main() {
fmt.Println("Index Compass point Degree")
for i, h := range []float32{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} {
index := i%32 + 1 // printable index computed per pseudocode
fmt.Printf("%4d %-19s %7.2f°\n", index, degrees2compasspoint(h), h)
}
} |
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.
| #beeswax | beeswax | #eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
##>{` OR `~{~` = `|{Nz1~5J
UXe#
##>{` XOR `~{~` = `${Nz1~7J
UXe#
##>`NOT `{` = `!{Nz1~9J
UXe#
##>{` << `~{~` = `({Nz1~9PPJ
UXe#
##>{` >>> `~{~` = `){` (logical shift right)`N7F+M~1~J
UXe#
##>{` ROL `~{~` = `[{N7F+P~1~J
UXe#
##>{` ROR `~{~` = `]{NN8F+P~1~J
UXe#
##>`Arithmetic shift right is not originally implemented in beeswax.`N q
qN`,noitagen yb dezilaer eb nac srebmun evitagen rof RSA ,yllacinhcet tuB`N<
##>`logical shift right, and negating the result again:`NN7F++~1~J
UXe# #>e#
#>~1~[&'pUX{` >> `~{~` = `){` , interpreted as (positive) signed Int64 number (MSB=0), equivalent to >>>`NN;
###
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN;
#>e# |
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.
| #BBC_BASIC | BBC BASIC | Width% = 200
Height% = 200
REM Set window size:
VDU 23,22,Width%;Height%;8,16,16,128
REM Fill with an RGB colour:
PROCfill(100,150,200)
REM Set a pixel:
PROCsetpixel(100,100,255,255,0)
REM Get a pixel:
rgb% = FNgetpixel(100,100)
PRINT RIGHT$("00000" + STR$~rgb%, 6)
END
DEF PROCfill(r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1+128
CLG
ENDPROC
DEF PROCsetpixel(x%,y%,r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC
DEF FNgetpixel(x%,y%)
LOCAL col%
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col% |
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).
| #Vedit_macro_language | Vedit macro language |
// Draw a circle using Bresenham's circle algorithm.
// #21 = center x, #22 = center y; #23 = radius
:DRAW_CIRCLE:
#30 = 1 - #23 // f
#31 = 0 // ddF_x
#32 = -2 * #23 // ddF_y
#41 = 0 // x
#42 = #23 // y
while (#41 <= #42) {
#1 = #21+#41; #2 = #22+#42; Call("DRAW_PIXEL")
#1 = #21-#41; #2 = #22+#42; Call("DRAW_PIXEL")
#1 = #21+#41; #2 = #22-#42; Call("DRAW_PIXEL")
#1 = #21-#41; #2 = #22-#42; Call("DRAW_PIXEL")
#1 = #21+#42; #2 = #22+#41; Call("DRAW_PIXEL")
#1 = #21-#42; #2 = #22+#41; Call("DRAW_PIXEL")
#1 = #21+#42; #2 = #22-#41; Call("DRAW_PIXEL")
#1 = #21-#42; #2 = #22-#41; Call("DRAW_PIXEL")
if (#30 >= 0) {
#42--
#32 += 2
#30 += #32
}
#41++
#31 += 2
#30 += #31 + 1
}
return
|
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #Ruby | Ruby | class Pixmap
def draw_bezier_curve(points, colour)
# ensure the points are increasing along the x-axis
points = points.sort_by {|p| [p.x, p.y]}
xmin = points[0].x
xmax = points[-1].x
increment = 2
prev = points[0]
((xmin + increment) .. xmax).step(increment) do |x|
t = 1.0 * (x - xmin) / (xmax - xmin)
p = Pixel[x, bezier(t, points).round]
draw_line(prev, p, colour)
prev = p
end
end
end
# the generalized n-degree Bezier summation
def bezier(t, points)
n = points.length - 1
points.each_with_index.inject(0.0) do |sum, (point, i)|
sum += n.choose(i) * (1-t)**(n - i) * t**i * point.y
end
end
class Fixnum
def choose(k)
self.factorial / (k.factorial * (self - k).factorial)
end
def factorial
(2 .. self).reduce(1, :*)
end
end
bitmap = Pixmap.new(400, 400)
points = [
Pixel[40,100], Pixel[100,350], Pixel[150,50],
Pixel[150,150], Pixel[350,250], Pixel[250,250]
]
points.each {|p| bitmap.draw_circle(p, 3, RGBColour::RED)}
bitmap.draw_bezier_curve(points, RGBColour::BLUE) |
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...
| #Python | Python |
"""
Python implementation of
http://rosettacode.org/wiki/Biorhythms
"""
from datetime import date, timedelta
from math import floor, sin, pi
def biorhythms(birthdate,targetdate):
"""
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 dates
print("Born: "+birthdate+" Target: "+targetdate)
# convert to date types - Python 3.7 or later
birthdate = date.fromisoformat(birthdate)
targetdate = date.fromisoformat(targetdate)
# days between
days = (targetdate - birthdate).days
print("Day: "+str(days))
# cycle logic - mostly from Julia example
cycle_labels = ["Physical", "Emotional", "Mental"]
cycle_lengths = [23, 28, 33]
quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
("down and falling", "valley"), ("down but rising", "transition")]
for i in range(3):
label = cycle_labels[i]
length = cycle_lengths[i]
position = days % length
quadrant = int(floor((4 * position) / length))
percentage = int(round(100 * sin(2 * pi * position / length),0))
transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
trend, next = quadrants[quadrant]
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
print(label+" day "+str(position)+": "+description)
biorhythms("1943-03-09","1972-07-11")
|
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Ada | Ada | declare
Data : Storage_Array (1..20); -- Data created
begin
Data := (others => 0); -- Assign all zeros
if Data = (1..10 => 0) then -- Compare with 10 zeros
declare
Copy : Storage_Array := Data; -- Copy Data
begin
if Data'Length = 0 then -- If empty
...
end if;
end;
end if;
... Data & 1 ... -- The result is Data with byte 1 appended
... Data & (1,2,3,4) ... -- The result is Data with bytes 1,2,3,4 appended
... Data (3..5) ... -- The result the substring of Data from 3 to 5
end; -- Data destructed |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Action.21 | Action! | DEFINE MAX_BINS="20"
PROC Count(INT ARRAY limits INT nLimits INT ARRAY data INT nData INT ARRAY bins)
INT i,j,v
BYTE found
FOR i=0 TO nLimits
DO
bins(i)=0
OD
FOR j=0 TO nData-1
DO
v=data(j) found=0
FOR i=0 TO nLimits-1
DO
IF v<limits(i) THEN
bins(i)==+1
found=1
EXIT
FI
OD
IF found=0 THEN
bins(nLimits)==+1
FI
OD
RETURN
PROC Test(INT ARRAY limits INT nLimits INT ARRAY data INT nData)
INT ARRAY bins(MAX_BINS)
INT i
Count(limits,nLimits,data,nData,bins)
FOR i=0 TO nLimits
DO
IF i=0 THEN
PrintF("<%I",limits(i))
ELSEIF i=nLimits THEN
PrintF(">=%I",limits(i-1))
ELSE
PrintF("%I..%I",limits(i-1),limits(i)-1)
FI
PrintF(": %I%E",bins(i))
OD
RETURN
PROC Main()
INT ARRAY
limits1(6)=[23 37 43 53 67 83],
data1(50)=[
95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47
16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55],
limits2(10)=[14 18 249 312 389 392 513 591 634 720],
data2(200)=[
445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933
416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306
655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247
346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123
345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97
854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395
787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692
698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237
605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791
466 23 707 467 33 670 921 180 991 396 160 436 717 918 8 374 101 684 727 749]
Test(limits1,6,data1,50) PutE()
Test(limits2,10,data2,200)
RETURN |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Ada | Ada | package binning is
type Nums_Array is array (Natural range <>) of Integer;
function Is_Sorted (Item : Nums_Array) return Boolean;
subtype Limits_Array is Nums_Array with
Dynamic_Predicate => Is_Sorted (Limits_Array);
function Bins (Limits : Limits_Array; Data : Nums_Array) return Nums_Array;
procedure Print (Limits : Limits_Array; Bin_Result : Nums_Array);
end binning;
|
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: assocs formatting grouping io kernel literals math
math.statistics prettyprint qw sequences sorting ;
CONSTANT: dna
$[
qw{
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
} concat
]
: .dna ( seq n -- )
"SEQUENCE:" print [ group ] keep
[ * swap " %3d: %s\n" printf ] curry each-index ;
: show-counts ( seq -- )
"BASE COUNTS:" print histogram >alist [ first ] sort-with
[ [ " %c: %3d\n" printf ] assoc-each ]
[ "TOTAL: " write [ second ] [ + ] map-reduce . ] bi ;
dna [ 50 .dna nl ] [ show-counts ] bi |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Forth | Forth |
( Gforth 0.7.3 )
: dnacode s" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" ;
variable #A \ Gforth initialises variables to 0
variable #C
variable #G
variable #T
variable #ch
50 constant pplength
: basecount ( adr u -- )
." Sequence:"
swap dup rot + swap ?do \ count while pretty-printing
#ch @ pplength mod 0= if cr #ch @ 10 .r 2 spaces then
i c@ dup emit
dup 'A = if drop #A @ 1+ #A ! else
dup 'C = if drop #C @ 1+ #C ! else
dup 'G = if drop #G @ 1+ #G ! else
dup 'T = if drop #T @ 1+ #T ! else drop then then then then
#ch @ 1+ #ch !
loop
cr cr ." Base counts:"
cr 4 spaces 'A emit ': emit #A @ 5 .r
cr 4 spaces 'C emit ': emit #C @ 5 .r
cr 4 spaces 'G emit ': emit #G @ 5 .r
cr 4 spaces 'T emit ': emit #T @ 5 .r
cr ." ----------"
cr ." Sum:" #ch @ 5 .r
cr ." ==========" cr cr
;
( demo run: )
dnacode basecount
|
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.
| #Clojure | Clojure |
(defn draw-line
"Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel."
[buffer x1 y1 x2 y2 pixel]
(let [dist-x (Math/abs (- x1 x2))
dist-y (Math/abs (- y1 y2))
steep (> dist-y dist-x)]
(let [[x1 y1 x2 y2] (if steep [y1 x1 y2 x2] [x1 y1 x2 y2])]
(let [[x1 y1 x2 y2] (if (> x1 x2) [x2 y2 x1 y1] [x1 y1 x2 y2])]
(let [delta-x (- x2 x1)
delta-y (Math/abs (- y1 y2))
y-step (if (< y1 y2) 1 -1)]
(let [plot (if steep
#(.setRGB buffer (int %1) (int %2) pixel)
#(.setRGB buffer (int %2) (int %1) pixel))]
(loop [x x1 y y1 error (Math/floor (/ delta-x 2)) ]
(plot x y)
(if (< x x2)
; Rather then rebind error, test that it is less than delta-y rather than zero
(if (< error delta-y)
(recur (inc x) (+ y y-step) (+ error (- delta-x delta-y)))
(recur (inc x) y (- error delta-y)))))))))))
|
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. | #Julia | Julia | dnabases = ['A', 'C', 'G', 'T']
randpos(seq) = rand(1:length(seq)) # 1
mutateat(pos, seq) = (s = seq[:]; s[pos] = rand(dnabases); s) # 2-1
deleteat(pos, seq) = [seq[1:pos-1]; seq[pos+1:end]] # 2-2
randinsertat(pos, seq) = [seq[1:pos]; rand(dnabases); seq[pos+1:end]] # 2-3
function weightedmutation(seq, pos, weights=[1, 1, 1], verbose=true) # Extra credit
p, r = weights ./ sum(weights), rand()
f = (r <= p[1]) ? mutateat : (r < p[1] + p[2]) ? deleteat : randinsertat
verbose && print("Mutate by ", f == mutateat ? "swap" :
f == deleteat ? "delete" : "insert")
return f(pos, seq)
end
function weightedrandomsitemutation(seq, weights=[1, 1, 1], verbose=true)
position = randpos(seq)
newseq = weightedmutation(seq, position, weights, verbose)
verbose && println(" at position $position")
return newseq
end
randdnasequence(n) = rand(dnabases, n) # 3
function dnasequenceprettyprint(seq, colsize=50) # 4
println(length(seq), "nt DNA sequence:\n")
rows = [seq[i:min(length(seq), i + colsize - 1)] for i in 1:colsize:length(seq)]
for (i, r) in enumerate(rows)
println(lpad(colsize * (i - 1), 5), " ", String(r))
end
bases = [[c, 0] for c in dnabases]
for c in seq, base in bases
if c == base[1]
base[2] += 1
end
end
println("\nNucleotide counts:\n")
for base in bases
println(lpad(base[1], 10), lpad(string(base[2]), 12))
end
println(lpad("Other", 10), lpad(string(length(seq) - sum(x[2] for x in bases)), 12))
println(" _________________\n", lpad("Total", 10), lpad(string(length(seq)), 12))
end
function testbioseq()
sequence = randdnasequence(500)
dnasequenceprettyprint(sequence)
for _ in 1:10 # 5
sequence = weightedrandomsitemutation(sequence)
end
println("\n Mutated:"); dnasequenceprettyprint(sequence) # 6
end
testbioseq()
|
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. | #Lua | Lua | math.randomseed(os.time())
bases = {"A","C","T","G"}
function randbase() return bases[math.random(#bases)] end
function mutate(seq)
local i,h = math.random(#seq), "%-6s %3s at %3d"
local old,new = seq:sub(i,i), randbase()
local ops = {
function(s) h=h:format("Swap", old..">"..new, i) return s:sub(1,i-1)..new..s:sub(i+1) end,
function(s) h=h:format("Delete", " -"..old, i) return s:sub(1,i-1)..s:sub(i+1) end,
function(s) h=h:format("Insert", " +"..new, i) return s:sub(1,i-1)..new..s:sub(i) end,
}
local weighted = { 1,1,2,3 }
local n = weighted[math.random(#weighted)]
return ops[n](seq), h
end
local seq,hist="",{} for i = 1, 200 do seq=seq..randbase() end
print("ORIGINAL:")
prettyprint(seq)
print()
for i = 1, 10 do seq,h=mutate(seq) hist[#hist+1]=h end
print("MUTATIONS:")
for i,h in ipairs(hist) do print(" "..h) end
print()
print("MUTATED:")
prettyprint(seq) |
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.
| #Phix | Phix | --
-- demo\rosetta\bitcoin_address_validation.exw
-- ===========================================
--
with javascript_semantics
include builtins\sha256.e
constant b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
string charmap = ""
function valid(string s, bool expected)
bool res := (expected==false)
if charmap="" then
charmap = repeat('\0',256)
for i=1 to length(b58) do
charmap[b58[i]] = i
end for
end if
-- not at all sure about this:
-- if length(s)!=34 then
-- return {expected==false,"bad length"}
-- end if
if not find(s[1],"13") then
return {res,"first character is not 1 or 3"}
end if
string out = repeat('\0',25)
for i=1 to length(s) do
integer c = charmap[s[i]]
if c=0 then
return {res,"bad char"}
end if
c -= 1
for j=25 to 1 by -1 do
c += 58 * out[j];
out[j] = and_bits(c,#FF)
c = floor(c/#100)
end for
if c!=0 then
return {res,"address too long"}
end if
end for
if out[1]!='\0' then
return {res,"not version 0"}
end if
if out[22..$]!=sha256(sha256(out[1..21]))[1..4] then
return {res,"bad digest"}
end if
res := (expected==true)
return {res,"OK"}
end function
constant tests = {{"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",true}, -- OK
{"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",false}, -- bad digest
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",true}, -- OK
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j",false}, -- bad disgest
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X",false}, -- bad digest (checksum changed, original data.)
{"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",false}, -- bad digest (data changed, original checksum.)
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz",false}, -- not version 0
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz",false}, -- address too long
{"1BGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",false}, -- bad digest
{"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",false}, -- bad char
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I",false}, -- bad char
{"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!",false}, -- bad char
{"1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i",false}, -- bad digest
{"1111111111111111111114oLvT2", true}, -- OK
{"17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j",true}, -- OK
{"1badbadbadbadbadbadbadbadbadbadbad",false}, -- not version 0
{"BZbvjr",false}, -- first character is not 1 or 3 (checksum is fine, address too short)
{"i55j",false}, -- first character is not 1 or 3 (checksum is fine, address too short)
{"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", true}, -- OK (from public_point_to_address)
$}
for i=1 to length(tests) do
{string ti, bool expected} = tests[i]
{bool res, string coin_err} = valid(ti,expected)
if not res then
printf(1,"%s: %s\n", {ti, coin_err})
{} = wait_key()
end if
end for
?"done"
{} = wait_key()
|
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.
| #Lingo | Lingo | img.floodFill(x, y, rgb(r,g,b)) |
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.
| #Lua | Lua | $ magick unfilledcirc.png -depth 8 unfilledcirc.ppm |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Java | Java | $ jq type
true
"boolean"
false
"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
| #JavaScript | JavaScript | $ jq type
true
"boolean"
false
"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
| #jq | jq | $ jq type
true
"boolean"
false
"boolean"
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Yabasic | Yabasic |
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***
text$ = "You are encouraged to solve this task according to the task description, using any language you may know."
key$ = "desoxirribonucleic acid" // With a single character you get a Caesar encryption. With more characters the key is much more difficult to discover.
CIPHER = 1 : DECIPHER = -1
print text$ : print
encrypted$ = criptex$(text$, key$, CIPHER)
a = open("cryptedText.txt", "w") : if a then print #a encrypted$ : close #a end if
print encrypted$ : print
print criptex$(encrypted$, key$, DECIPHER)
sub criptex$(text$, key$, mode)
local i, k, delta, longtext, longPattern, longkey, pattern$, res$
pattern$ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 .,;:()-"
longPattern = len(pattern$)
longtext = len(text$)
longkey = len(key$)
for i = 1 to longtext
k = k + 1 : if k > longkey k = 1
delta = instr(pattern$, mid$(text$, i, 1))
delta = delta + (mode * instr(pattern$, mid$(key$, k, 1)))
if delta > longPattern then
delta = delta - longPattern
elseif delta < 1 then
delta = longPattern + delta
end if
res$ = res$ + mid$(pattern$, delta, 1)
next i
return res$
end sub |
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)..
| #Groovy | Groovy | def asCompassPoint(angle) {
def cardinalDirections = ["north", "east", "south", "west"]
int index = Math.floor(angle / 11.25 + 0.5)
int cardinalIndex = (index / 8)
def c1 = cardinalDirections[cardinalIndex % 4]
def c2 = cardinalDirections[(cardinalIndex + 1) % 4]
def c3 = (cardinalIndex == 0 || cardinalIndex == 2) ? "$c1$c2" : "$c2$c1"
def point = [
"$c1", "$c1 by $c2", "$c1-$c3", "$c3 by $c1", "$c3", "$c3 by $c2", "$c2-$c3", "$c2 by $c1"
][index % 8]
point.substring(0, 1).toUpperCase() + point.substring(1)
}
Number.metaClass.asCompassPoint = { asCompassPoint(delegate) }
[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].eachWithIndex { angle, index ->
println "${(index % 32) + 1}".padRight(3) + "${angle.asCompassPoint().padLeft(20)} $angle\u00b0"
} |
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.
| #Befunge | Befunge | > v MCR >v
1 2 3 4 5 6>61g-:| 8 9
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv
>v>v>v>v < > ^
>#A 1 $^ ^ <
B 6^ <
^>^>^>^1 C |!`5p18:+1g18$ <
^ 9 p#p17*93p189p150 < >61g71g81gg+71g81gpv D
>071g81gp v ^ <
AND >+2\`!#^_> v
XOR +2% #^_> v
OR +1\`!#^_> v
NOT ! #^_> v
LSHFT 0 #^_>48*71g3+81gp v
RSHFT $ 48*71g3+81gp #^_>v E
END v #^_> >61g2*61pv
@ F
v_^# `2:<
>71g81gg.48*71g2+81gp79*1-71g2+81g1+pv
^ <_v#!`2p15:+1g15p18+1g18<
^ < G
|
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.
| #C | C | #ifndef _IMGLIB_0
#define _IMGLIB_0
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <sys/queue.h>
typedef unsigned char color_component;
typedef color_component pixel[3];
typedef struct {
unsigned int width;
unsigned int height;
pixel * buf;
} image_t;
typedef image_t * image;
image alloc_img(unsigned int width, unsigned int height);
void free_img(image);
void fill_img(image img,
color_component r,
color_component g,
color_component b );
void put_pixel_unsafe(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
void put_pixel_clip(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
#define GET_PIXEL(IMG, X, Y) (IMG->buf[ ((Y) * IMG->width + (X)) ])
#endif |
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).
| #Wren | Wren | import "graphics" for Canvas, Color, ImageData
import "dome" for Window
class MidpointCircle {
construct new(width, height) {
Window.title = "Midpoint Circle"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_bmp = ImageData.create("midpoint circle", width, height)
}
init() {
fill(Color.pink)
drawCircle(200, 200, 100, Color.black)
drawCircle(200, 200, 50, Color.white)
_bmp.draw(0, 0)
}
fill(col) {
for (x in 0..._w) {
for (y in 0..._h) pset(x, y, col)
}
}
drawCircle(centerX, centerY, radius, circleColor) {
var d = ((5 - radius * 4)/4).truncate
var x = 0
var y = radius
while (true) {
pset(centerX + x, centerY + y, circleColor)
pset(centerX + x, centerY - y, circleColor)
pset(centerX - x, centerY + y, circleColor)
pset(centerX - x, centerY - y, circleColor)
pset(centerX + y, centerY + x, circleColor)
pset(centerX + y, centerY - x, circleColor)
pset(centerX - y, centerY + x, circleColor)
pset(centerX - y, centerY - x, circleColor)
if (d < 0) {
d = d + 2 * x + 1
} else {
d = d + 2 * (x - y) + 1
y = y - 1
}
x = x + 1
if (x > y) break
}
}
pset(x, y, col) { _bmp.pset(x, y, col) }
pget(x, y) { _bmp.pget(x, y) }
update() {}
draw(alpha) {}
}
var Game = MidpointCircle.new(400, 400) |
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).
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc drawBezier {img colour args} {
# ensure the points are increasing along the x-axis
set points [lsort -real -index 0 $args]
set xmin [x [lindex $points 0]]
set xmax [x [lindex $points end]]
set prev [lindex $points 0]
set increment 2
for {set x [expr {$xmin + $increment}]} {$x <= $xmax} {incr x $increment} {
set t [expr {1.0 * ($x - $xmin) / ($xmax - $xmin)}]
set this [list $x [::tcl::mathfunc::round [bezier $t $points]]]
drawLine $img $colour $prev $this
set prev $this
}
}
# the generalized n-degree Bezier summation
proc bezier {t points} {
set n [expr {[llength $points] - 1}]
for {set i 0; set sum 0.0} {$i <= $n} {incr i} {
set sum [expr {$sum + [C $n $i] * (1-$t)**($n - $i) * $t**$i * [y [lindex $points $i]]}]
}
return $sum
}
proc C {n i} {expr {[ifact $n] / ([ifact $i] * [ifact [expr {$n - $i}]])}}
proc ifact n {
for {set i $n; set sum 1} {$i >= 2} {incr i -1} {
set sum [expr {$sum * $i}]
}
return $sum
}
proc x p {lindex $p 0}
proc y p {lindex $p 1}
proc newbezier {n w} {
set size 400
set bezier [newImage $size $size]
fill $bezier white
for {set i 1} {$i <= $n} {incr i} {
set point [list [expr {int($size*rand())}] [expr {int($size*rand())}]]
lappend points $point
drawCircle $bezier red $point 3
}
puts $points
drawBezier $bezier blue {*}$points
$w configure -image $bezier
}
set degree 4 ;# cubic bezier -- for quadratic, use 3
label .img
button .new -command [list newbezier $degree .img] -text New
button .exit -command exit -text Exit
pack .new .img .exit -side top |
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...
| #R | R | bioR <- function(bDay, targetDay) {
bDay <- as.Date(bDay)
targetDay <- as.Date(targetDay)
n <- as.numeric(targetDay - bDay)
cycles <- c(23, 28, 33)
mods <- n %% cycles
bioR <- c(sin(2 * pi * mods / cycles))
loc <- mods / cycles
current <- ifelse(bioR > 0, ': Up', ': Down')
current <- paste(current, ifelse(loc < 0.25 | loc > 0.75,
"and rising",
"and falling"))
df <- data.frame(dates = seq.Date(from = targetDay - 30,
to = targetDay + 30,
by = 1))
df$n <- as.numeric(df$dates - bDay)
df$P <- sin(2 * pi * (df$n %% cycles[1]) / cycles[1])
df$E <- sin(2 * pi * (df$n %% cycles[2]) / cycles[2])
df$M <- sin(2 * pi * (df$n %% cycles[3]) / cycles[3])
plot(df$dates, df$P, col = 'blue',
main = paste(targetDay, 'Biorhythm for Birthday on', bDay),
xlab = "",
ylab = "Intensity")
points(df$dates, df$E, col = 'green')
points(df$dates, df$M, col = 'red')
abline(v = targetDay)
legend('topleft', legend = c("Phys", "Emot", "Ment"),
col =c("blue", "green", "red"),
cex = 0.8,
pch = 21)
cat(paste0('Birthday = ', as.character(bDay),
'\nTarget Date = ', as.character(targetDay),
'\n', n, ' days',
'\nPhysical = ', mods[1], current[1],
'\nEmotional = ', mods[2], current[2],
'\nMental = ', mods[3], current[3]))
}
bioR('1943-03-09', '1972-07-11') |
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...
| #Raku | Raku | #!/usr/bin/env raku
unit sub MAIN($birthday=%*ENV<BIRTHDAY>, $date = Date.today()) {
my %cycles = ( :23Physical, :28Emotional, :33Mental );
my @quadrants = [ ('up and rising', 'peak'),
('up but falling', 'transition'),
('down and falling', 'valley'),
('down but rising', 'transition') ];
if !$birthday {
die "Birthday not specified.\n" ~
"Supply --birthday option or set \$BIRTHDAY in environment.\n";
}
my ($bday, $target) = ($birthday, $date).map: { Date.new($_) };
my $days = $target - $bday;
say "Day $days:";
for %cycles.sort(+*.value)».kv -> ($label, $length) {
my $position = $days % $length;
my $quadrant = floor($position / $length * 4);
my $percentage = floor(sin($position / $length * 2 * π )*1000)/10;
my $description;
if $percentage > 95 {
$description = 'peak';
} elsif $percentage < -95 {
$description = 'valley';
} elsif abs($percentage) < 5 {
$description = 'critical transition'
} else {
my $transition = $target + floor(($quadrant + 1)/4 * $length) - $position;
my ($trend, $next) = @quadrants[$quadrant];
$description = "$percentage% ($trend, next $next $transition)";
}
say "$label day $position: $description";
}
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #ALGOL_68 | ALGOL 68 | # String creation #
STRING a,b,c,d,e,f,g,h,i,j,l,r;
a := "hello world";
print((a, new line));
# String destruction (for garbage collection) #
b := ();
BEGIN
LOC STRING lb := "hello earth"; # allocate off the LOC stack #
HEAP STRING hb := "hello moon"; # allocate out of the HEAP space #
~
END; # local variable "lb" has LOC stack space recovered at END #
# String assignment #
c := "a"+REPR 0+"b";
print (("string length c:", UPB c, new line));# ==> 3 #
# String comparison #
l := "ab"; r := "CD";
BOOL result;
FORMAT summary = $""""g""" is "b("","NOT ")"lexicographically "g" """g""""l$ ;
result := l < r OR l LT r; printf((summary, l, result, "less than", r));
result := l <= r OR l LE r # OR l ≤ r #; printf((summary, l, result, "less than or equal to", r));
result := l = r OR l EQ r; printf((summary, l, result, "equal to", r));
result := l /= r OR l NE r # OR l ≠ r #; printf((summary, l, result, "not equal to", r));
result := l >= r OR l GE r # OR l ≥ r #; printf((summary, l, result, "greater than or equal to", r));
result := l > r OR l GT r; printf((summary, l, result, "greater than", r));
# String cloning and copying #
e := f;
# Check if a string is empty #
IF g = "" THEN print(("g is empty", new line)) FI;
IF UPB g = 0 THEN print(("g is empty", new line)) FI;
# Append a byte to a string #
h +:= "A";
# Append a string to a string #
h +:= "BCD";
h PLUSAB "EFG";
# Prepend a string to a string - because STRING addition isn't communitive #
"789" +=: h;
"456" PLUSTO h;
print(("The result of prepends and appends: ", h, new line));
# Extract a substring from a string #
i := h[2:3];
print(("Substring 2:3 of ",h," is ",i, new line));
# Replace every occurrences of a byte (or a string) in a string with another string #
PROC replace = (STRING string, old, new, INT count)STRING: (
INT pos;
STRING tail := string, out;
TO count WHILE string in string(old, pos, tail) DO
out +:= tail[:pos-1]+new;
tail := tail[pos+UPB old:]
OD;
out+tail
);
j := replace("hello world", "world", "planet", max int);
print(("After replace string: ", j, new line));
INT offset = 7;
# Replace a character at an offset in the string #
j[offset] := "P";
print(("After replace 7th character: ", j, new line));
# Replace a substring at an offset in the string #
j[offset:offset+3] := "PlAN";
print(("After replace 7:10th characters: ", j, new line));
# Insert a string before an offset in the string #
j := j[:offset-1]+"INSERTED "+j[offset:];
print(("Insert string before 7th character: ", j, new line));
# Join strings #
a := "hel";
b := "lo w";
c := "orld";
d := a+b+c;
print(("a+b+c is ",d, new line));
# Pack a string into the target CPU's word #
BYTES word := bytes pack(d);
# Extract a CHAR from a CPU word #
print(("7th byte in CPU word is: ", offset ELEM word, new line)) |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #ALGOL_68 | ALGOL 68 | BEGIN # count the number pf items that fall into "bins" given he limits #
# returns an array of "bins" containing the counts of the data items #
# that fall into the bins given the limits #
PRIO INTOBINS = 1;
OP INTOBINS = ( []INT data, []INT limits )[]INT:
BEGIN
[ LWB limits : UPB limits + 1 ]INT bins;
FOR bin number FROM LWB bins TO UPB bins DO bins[ bin number ] := 0 OD;
FOR d pos FROM LWB data TO UPB data DO
INT bin number := LWB bins;
INT item = data[ d pos ];
FOR b pos FROM LWB bins TO UPB bins - 1 WHILE item >= limits[ b pos ] DO
bin number +:= 1
OD;
bins[ bin number ] +:= 1
OD;
bins
END # INTOBINS # ;
# shows the limits of the bins and the number of items in each #
PROC show bins = ( []INT limits, []INT bins )VOID:
BEGIN
print( ( " < ", whole( limits[ LWB limits ], -4 )
, ": ", whole( bins[ LWB bins ], -4 )
, newline
)
);
INT bin number := LWB bins + 1;
FOR l pos FROM LWB limits + 1 TO UPB limits DO
print( ( ">= ", whole( limits[ l pos - 1 ], -4 )
, " and < ", whole( limits[ l pos ], -4 )
, ": ", whole( bins[ bin number ], -4 )
, newline
)
);
bin number +:= 1
OD;
print( ( " > ", whole( limits[ UPB limits ], -4 )
, ": ", whole( bins[ UPB bins ], -4 )
, newline
)
)
END # show bins # ;
# task test cases #
BEGIN
print( ( "data set 1", newline ) );
[]INT limits =
( 23, 37, 43, 53, 67, 83 );
[]INT data =
( 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47
, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55
);
show bins( limits, data INTOBINS limits )
END;
print( ( newline ) );
BEGIN
print( ( "data set 2", newline ) );
[]INT limits =
( 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 );
[]INT data =
( 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933
, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306
, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247
, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123
, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97
, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395
, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692
, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237
, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791
, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749
);
show bins( limits, data INTOBINS limits )
END
END |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | #define SCW 36
#define GRP 3
function padto( n as integer, w as integer ) as string
dim as string r = str(n)
while len(r)<w
r = " "+r
wend
return r
end function
dim as string dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"+_
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"+_
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"+_
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"+_
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"+_
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"+_
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"+_
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"+_
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"+_
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
dim as string outstr = "", currb
dim as integer bases(0 to 3), curr = 1, first = 1
while curr <= len(dna)
currb = mid(dna, curr, 1)
if currb = "A" then bases(0) += 1
if currb = "C" then bases(1) += 1
if currb = "G" then bases(2) += 1
if currb = "T" then bases(3) += 1
outstr += currb
curr += 1
if curr mod GRP = 1 then outstr += " "
if curr mod SCW = 1 or curr=len(dna)+1 then
outstr = padto(first,3) + "--" + padto(curr-1,3) + ": " + outstr
print outstr
outstr = ""
first = curr
end if
wend
print
print "Base counts"
print "-----------"
print " A: " + str(bases(0))
print " C: " + str(bases(1))
print " G: " + str(bases(2))
print " T: " + str(bases(3))
print
print " total: " + str(bases(0)+bases(1)+bases(2)+bases(3)) |
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.
| #CoffeeScript | CoffeeScript |
drawBresenhamLine = (x0, y0, x1, y1) ->
dx = Math.abs(x1 - x0)
sx = if x0 < x1 then 1 else -1
dy = Math.abs(y1 - y0)
sy = if y0 < y1 then 1 else -1
err = (if dx>dy then dx else -dy) / 2
loop
setPixel(x0, y0)
break if x0 == x1 && y0 == y1
e2 = err
if e2 > -dx
err -= dy
x0 += sx
if e2 < dy
err += dx
y0 += sy
null
|
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. | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | SeedRandom[13122345];
seq = BioSequence["DNA", "ATAAACGTACGTTTTTAGGCT"];
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringReplacePart[seq, RandomChoice[{"A", "T", "C", "G"}], {randompos, randompos}];
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringReplacePart[seq, "", {randompos, randompos}];
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringInsert[seq, RandomChoice[{"A", "T", "C", "G"}], randompos];
seq = BioSequence["DNA", StringJoin@RandomChoice[{"A", "T", "C", "G"}, 250]];
size = 50;
parts = StringPartition[seq["SequenceString"], UpTo[size]];
begins = Most[Accumulate[Prepend[StringLength /@ parts, 1]]];
ends = Rest[Accumulate[Prepend[StringLength /@ parts, 0]]];
StringRiffle[MapThread[ToString[#1] <> "-" <> ToString[#2] <> ": " <> #3 &, {begins, ends, parts}], "\n"]
Tally[Characters[seq["SequenceString"]]]
Do[
type = RandomChoice[{1, 2, 3}];
Switch[type, 1,
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringReplacePart[seq, RandomChoice[{"A", "T", "C", "G"}], {randompos, randompos}];
, 2,
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringReplacePart[seq, "", {randompos, randompos}];
, 3,
randompos = RandomInteger[seq["SequenceLength"]];
seq = StringInsert[seq, RandomChoice[{"A", "T", "C", "G"}], randompos];
]
,
{10}
]
parts = StringPartition[seq["SequenceString"], UpTo[size]];
begins = Most[Accumulate[Prepend[StringLength /@ parts, 1]]];
ends = Rest[Accumulate[Prepend[StringLength /@ parts, 0]]];
StringRiffle[MapThread[ToString[#1] <> "-" <> ToString[#2] <> ": " <> #3 &, {begins, ends, parts}], "\n"]
Tally[Characters[seq["SequenceString"]]] |
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. | #Nim | Nim | import random
import strformat
import strutils
type
# Enumeration type for bases.
Base {.pure.} = enum A, C, G, T, Other = "other"
# Sequence of bases.
DnaSequence = string
# Kind of mutation.
Mutation = enum mutSwap, mutDelete, mutInsert
const MaxBaseVal = ord(Base.high) - 1 # Maximum base value.
#---------------------------------------------------------------------------------------------------
template toChar(base: Base): char = ($base)[0]
#---------------------------------------------------------------------------------------------------
proc newDnaSeq(length: Natural): DnaSequence =
## Create a DNA sequence of given length.
result = newStringOfCap(length)
for _ in 1..length:
result.add($Base(rand(MaxBaseVal)))
#---------------------------------------------------------------------------------------------------
proc mutate(dnaSeq: var DnaSequence) =
## Mutate a sequence (it is changed in place).
# Choose randomly the position of mutation.
let idx = rand(dnaSeq.high)
# Choose randomly the kind of mutation.
let mut = Mutation(rand(ord(Mutation.high)))
# Apply the mutation.
case mut
of mutSwap:
let newBase = Base(rand(MaxBaseVal))
echo fmt"Changing base at position {idx + 1} from {dnaSeq[idx]} to {newBase}"
dnaSeq[idx] = newBase.toChar
of mutDelete:
echo fmt"Deleting base {dnaSeq[idx]} at position {idx + 1}"
dnaSeq.delete(idx, idx)
of mutInsert:
let newBase = Base(rand(MaxBaseVal))
echo fmt"Inserting base {newBase} at position {idx + 1}"
dnaSeq.insert($newBase, idx)
#---------------------------------------------------------------------------------------------------
proc display(dnaSeq: DnaSequence) =
## Display a DNA sequence using EMBL format.
var counts: array[Base, Natural] # Count of bases.
for c in dnaSeq:
inc counts[parseEnum[Base]($c, Other)] # Use Other as default value.
# Display the SQ line.
var sqline = fmt"SQ {dnaSeq.len} BP; "
for (base, count) in counts.pairs:
sqline &= fmt"{count} {base}; "
echo sqline
# Display the sequence.
var idx = 0
var row = newStringOfCap(80)
var remaining = dnaSeq.len
while remaining > 0:
row.setLen(0)
row.add(" ")
# Add groups of 10 bases.
for group in 1..6:
let nextIdx = idx + min(10, remaining)
for i in idx..<nextIdx:
row.add($dnaSeq[i])
row.add(' ')
dec remaining, nextIdx - idx
idx = nextIdx
if remaining == 0:
break
# Append the number of the last base in the row.
row.add(spaces(72 - row.len))
row.add(fmt"{idx:>8}")
echo row
# Add termination.
echo "//"
#———————————————————————————————————————————————————————————————————————————————————————————————————
randomize()
var dnaSeq = newDnaSeq(200)
echo "Initial sequence"
echo "———————————————\n"
dnaSeq.display()
echo "\nMutations"
echo "—————————\n"
for _ in 1..10:
dnaSeq.mutate()
echo "\nMutated sequence"
echo "————————————————\n"
dnaSeq.display() |
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.
| #PHP | PHP |
function validate($address){
$decoded = decodeBase58($address);
$d1 = hash("sha256", substr($decoded,0,21), true);
$d2 = hash("sha256", $d1, true);
if(substr_compare($decoded, $d2, 21, 4)){
throw new \Exception("bad digest");
}
return true;
}
function decodeBase58($input) {
$alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
$out = array_fill(0, 25, 0);
for($i=0;$i<strlen($input);$i++){
if(($p=strpos($alphabet, $input[$i]))===false){
throw new \Exception("invalid character found");
}
$c = $p;
for ($j = 25; $j--; ) {
$c += (int)(58 * $out[$j]);
$out[$j] = (int)($c % 256);
$c /= 256;
$c = (int)$c;
}
if($c != 0){
throw new \Exception("address too long");
}
}
$result = "";
foreach($out as $val){
$result .= chr($val);
}
return $result;
}
function main () {
$s = array(
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I",
);
foreach($s as $btc){
$message = "OK";
try{
validate($btc);
}catch(\Exception $e){ $message = $e->getMessage(); }
echo "$btc: $message\n";
}
}
main();
|
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | createMask[img_, pos_, tol_] :=
RegionBinarize[img, Image[SparseArray[pos -> 1, ImageDimensions[img]]], tol];
floodFill[img_Image, pos_List, tol_Real, color_List] :=
ImageCompose[
SetAlphaChannel[ImageSubtract[img, createMask[img, pos, tol]], 1],
SetAlphaChannel[Image[ConstantArray[color, ImageDimensions[img]]],
Dilation[createMask[img, pos, tol],1]
]
] |
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.
| #Nim | Nim | import bitmap
proc floodFill*(img: Image; initPoint: Point; targetColor, replaceColor: Color) =
var stack: seq[Point]
let width = img.w
let height = img.h
if img[initPoint.x, initPoint.y] != targetColor:
return
stack.add(initPoint)
while stack.len > 0:
var w, e: Point
let pt = stack.pop()
if img[pt.x, pt.y] == targetColor:
w = pt
e = if pt.x + 1 < width: (pt.x + 1, pt.y) else: pt
else:
continue # Already processed.
# Move west until color of node does not match "targetColor".
while w.x >= 0 and img[w.x, w.y] == targetColor:
img[w.x, w.y] = replaceColor
if w.y + 1 < height and img[w.x, w.y + 1] == targetColor:
stack.add((w.x, w.y + 1))
if w.y - 1 >= 0 and img[w.x, w.y - 1] == targetColor:
stack.add((w.x, w.y - 1))
dec w.x
# Move east until color of node does not match "targetColor".
while e.x < width and img[e.x, e.y] == targetColor:
img[e.x, e.y] = replaceColor
if e.y + 1 < height and img[e.x, e.y + 1] == targetColor:
stack.add((e.x, e.y + 1))
if e.y - 1 >= 0 and img[e.x, e.y - 1] == targetColor:
stack.add((e.x, e.y - 1))
inc e.x
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import ppm_read, ppm_write
var img = readPPM("Unfilledcirc.ppm")
img.floodFill((30, 122), White, color(255, 0, 0))
img.writePPM("Unfilledcirc_red.ppm") |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Julia | Julia | julia> if 1
println("true")
end
ERROR: type: non-boolean (Int64) used in boolean context |
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
| #KonsolScript | KonsolScript |
{if true then YES else NO}
-> YES
{if false then YES else NO}
-> NO
|
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
| #Kotlin | Kotlin |
{if true then YES else NO}
-> YES
{if false then YES else NO}
-> NO
|
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
| #zkl | zkl | fcn caesarCodec(str,n,encode=True){
var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static
if(not encode) n=26 - n;
m,sz := n + 26, 26 - n;
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
str.translate(letters,ltrs)
} |
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)..
| #Haskell | Haskell | import Data.Char (toUpper)
import Data.Maybe (fromMaybe)
import Text.Printf (PrintfType, printf)
dirs :: [String]
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"
]
-- Index between 0 and 31 -> the corresponding compass point name.
pointName :: Int -> String
pointName = capitalize . concatMap (fromMaybe "?" . fromChar) . (dirs !!)
where
fromChar c =
lookup
c
[ ('N', "north")
, ('S', "south")
, ('E', "east")
, ('W', "west")
, ('b', " by ")
, ('-', "-")
]
capitalize (c:cs) = toUpper c : cs
-- Degrees -> compass point index between 0 and 31.
pointIndex :: Double -> Int
pointIndex d = (round (d * 1000) + 5625) `mod` 360000 `div` 11250
printPointName :: PrintfType t => String -> t
printPointName d =
let deg = read d :: Double
idx = pointIndex deg
in printf "%2d %-18s %6.2f°\n" (idx + 1) (pointName idx) deg
main :: IO ()
main = mapM_ (printPointName . show) [0 .. 31] |
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.
| #C | C | void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
printf("a or b: %d\n", a | b);
printf("a xor b: %d\n", a ^ b);
printf("not a: %d\n", ~a);
printf("a << n: %d\n", a << b); /* left shift */
printf("a >> n: %d\n", a >> b); /* on most platforms: arithmetic right shift */
/* convert the signed integer into unsigned, so it will perform logical shift */
unsigned int c = a;
printf("c >> b: %d\n", c >> b); /* logical right shift */
/* there are no rotation operators in C */
return 0;
} |
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.
| #C.23 | C# | public class Bitmap
{
public struct Color
{
public byte Red { get; set; }
public byte Blue { get; set; }
public byte Green { get; set; }
}
Color[,] _imagemap;
public int Width { get { return _imagemap.GetLength(0); } }
public int Height { get { return _imagemap.GetLength(1); } }
public Bitmap(int width, int height)
{
_imagemap = new Color[width, height];
}
public void Fill(Color color)
{
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
_imagemap[x, y] = color;
}
}
public Color GetPixel(int x, int y)
{
return _imagemap[x, y];
}
public void SetPixel(int x, int y, Color color)
{
_imagemap[x, y] = color;
}
} |
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).
| #XPL0 | XPL0 | include c:\cxpl\codes; \include 'code' declarations
proc Circle(X0, Y0, Radius, Color); \Display a circle
int X0, Y0, \coordinates of center
Radius, \radius in (pixels)
Color; \line color
int X, Y, E, U, V;
proc PlotOctants; \Segment
[Point(X0+Y, Y0+X, Color); \ 0
Point(X0+X, Y0+Y, Color); \ 1
Point(X0-X, Y0+Y, Color); \ 2
Point(X0-Y, Y0+X, Color); \ 3
Point(X0-Y, Y0-X, Color); \ 4
Point(X0-X, Y0-Y, Color); \ 5
Point(X0+X, Y0-Y, Color); \ 6
Point(X0+Y, Y0-X, Color); \ 7
]; \PlotOctants
[X:= 0; Y:= Radius;
U:= 1;
V:= 1 -Radius -Radius;
E:= 1 -Radius;
while X < Y do
[PlotOctants;
if E < 0 then
[U:= U+2; V:= V+2; E:= E+U]
else [U:= U+2; V:= V+4; E:= E+V; Y:= Y-1];
X:= X+1;
];
if X = Y then PlotOctants;
]; \Circle
[SetVid($112); \640x480 in 24-bit RGB color
Circle(110, 110, 50, $FFFF00);
if ChIn(1) then []; \wait for keystroke
SetVid(3); \restore normal text mode
] |
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).
| #zkl | zkl | fcn circle(x0,y0,r,rgb){
x:=r; y:=0; radiusError:=1-x;
while(x >= y){
__sSet(rgb, x + x0, y + y0);
__sSet(rgb, y + x0, x + y0);
__sSet(rgb,-x + x0, y + y0);
__sSet(rgb,-y + x0, x + y0);
self[-x + x0, -y + y0]=rgb; // or do it this way, __sSet gets called as above
self[-y + x0, -x + y0]=rgb;
self[ x + x0, -y + y0]=rgb;
self[ y + x0, -x + y0]=rgb;
y+=1;
if (radiusError<0) radiusError+=2*y + 1;
else{ x-=1; radiusError+=2*(y - x + 1); }
}
} |
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic | Bitmap/Bézier curves/Cubic | Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve
(definition on Wikipedia).
| #TI-89_BASIC | TI-89 BASIC | Define cubic(p1,p2,p3,p4,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^3*p1 + 3t*u^2*p2 + 3t^2*u*p3 + t^3*p4 → 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/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).
| #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 bmpCubicBezier(name, p1, p2, p3, p4, 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 * u
var b = 3 * t * u * u
var c = 3 * t * t * u
var d = t * t * t
var px = (a * p1.x + b * p2.x + c * p3.x + d * p4.x).truncate
var py = (a * p1.y + b * p2.y + c * p3.y + d * p4.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 = "Cubic Bézier curve"
var size = 200
Window.resize(size, size)
Canvas.resize(size, size)
var name = "cubic"
var bmp = bmpCreate(name, size, size)
bmpFill(name, Color.white)
var p1 = Point.new(160, 10)
var p2 = Point.new( 10, 40)
var p3 = Point.new( 30, 160)
var p4 = Point.new(150, 110)
bmpCubicBezier(name, p1, p2, p3, p4, Color.darkblue, 20)
bmp.draw(0, 0)
}
static update() {}
static draw(alpha) {}
} |
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...
| #REXX | REXX | , (a comma) indicates today's date
* (an asterisk) indicates today's date
yyyy-mm-dd where yyyy may be a 2- or 4-digit year, mm may be a 1- or 2-digit month, dd may be a 1- or 2-digit day of month
mm/dd/yyyy (as above)
mm/dd (as above), but the current year is assumed
dd\mm\yyyy (as above)
dd\mm (as above), but the current year is assumed
|
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...
| #Ruby | Ruby | require 'date'
CYCLES = {physical: 23, emotional: 28, mental: 33}
def biorhythms(date_of_birth, target_date = Date.today.to_s)
days_alive = Date.parse(target_date) - Date.parse(date_of_birth)
CYCLES.each do |name, num_days|
cycle_day = days_alive % num_days
state = case cycle_day
when 0, num_days/2 then "neutral"
when (1.. num_days/2) then "positive"
when (num_days/2+1..num_days) then "negative"
end
puts "%-10s: cycle day %2s, %s" % [name, cycle_day.to_i, state]
end
end
biorhythms("1943-03-09", "1972-07-11")
|
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...
| #Tcl | Tcl | #!/usr/bin/env wish
# Biorhythm calculator
set today [clock format [clock seconds] -format %Y-%m-%d ]
proc main [list birthday [list target $today]] {
set day [days-between $birthday $target]
array set cycles {
Physical {23 red}
Emotional {28 green}
Mental {33 blue}
}
set pi [expr atan2(0,-1)]
canvas .c -width 306 -height 350 -bg black
.c create rectangle 4 49 306 251 -outline grey
.c create line 5 150 305 150 -fill grey
.c create line 145 50 145 250 -fill cyan
.c create text 145 15 -text "$target" -fill cyan
.c create text 145 30 -text "(Day $day)" -fill cyan
set ly 305
foreach {name data} [array get cycles] {
lassign $data length color
.c create text 60 $ly -anchor nw -text $name -fill $color
set pos [expr $day % $length]
for {set dd -14} {$dd <= 16} {incr dd} {
set d [expr $pos + $dd]
set x [expr 145 + 10 * $dd]
.c create line $x 145 $x 155 -fill grey
set v [expr sin(2*$pi*$d/$length)]
set y [expr 150 - 100 * $v]
if {$dd == 0} {
.c create text 10 $ly -anchor nw \
-text "[format %+04.1f%% [expr $v * 100]]" -fill $color
}
if [info exists ox] {
.c create line $ox $oy $x $y -fill $color
}
set ox $x
set oy $y
}
unset ox oy
set ly [expr $ly - 25]
}
pack .c
}
proc days-between {from to} {
expr int([rd $to] - [rd $from])
}
# parse an (ISO-formatted) date into a day number
proc rd {date} {
lassign [scan $date %d-%d-%d] year month day
set elapsed [expr $year - 1]
expr {$elapsed * 365 +
floor($elapsed/4) -
floor($elapsed/100) +
floor($elapsed/400) +
floor( (367*$month-362)/12 ) +
($month < 3 ? 0 : ([is-leap $year] ? -1 : -2)) +
$day}
}
proc is-leap {year} {
expr {$year % 4 == 0 && ($year % 100 || $year % 400 == 0)}
}
main {*}$argv |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Arturo | Arturo | ; creation
x: "this is a string"
y: "this is another string"
z: "this is a string"
; comparison
if x = z -> print "x is z"
; assignment
z: "now this is another string too"
; copying reference
y: z
; copying value
y: new z
; check if empty
if? empty? x -> print "empty"
else -> print "not empty"
; append a string
'x ++ "!"
print x
; substrings
print slice x 5 8
; join strings
z: x ++ y
print z
; replace occurrences of substring
print replace z "t" "T" |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #AutoHotkey | AutoHotkey | Bin_given_limits(limits, data){
bin := [], counter := 0
for i, val in data {
if (limits[limits.count()] <= val)
bin["∞", ++counter] := val
else for j, limit in limits
if (limits[j-1] <= val && val < limits[j])
bin[limit, ++counter] := val
}
for j, limit in limits {
output .= (prevlimit ? prevlimit : "-∞") ", " limit " : " ((x:=bin[limit].Count())?x:0) "`n"
prevlimit := limit
}
return output .= (prevlimit ? prevlimit : "-∞") ", ∞ : " ((x:=bin["∞"].Count())?x:0) "`n"
} |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int) // allows for 'any' base
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #0815 | 0815 | }:r:|~ Read numbers in a loop.
}:b: Treat the queue as a stack and
<:2:= accumulate the binary digits
/=>&~ of the given number.
^:b:
<:0:-> Enqueue negative 1 as a sentinel.
{ Dequeue the first binary digit.
}:p:
~%={+ Rotate each binary digit into place and print it.
^:p:
<:a:~$ Output a newline.
^:r: |
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.
| #Commodore_BASIC | Commodore BASIC |
10 rem bresenham line algorihm
20 rem translated from purebasic
30 x0=10 : rem start x co-ord
40 y0=15 : rem start y co-ord
50 x1=30 : rem end x co-ord
60 y1=20 : rem end y co-ord
70 se=0 : rem 0 = steep 1 = !steep
80 ns=25 : rem num segments
90 dim pt(ns,2) : rem points in line
100 sc=1024 : rem start of screen memory
110 sw=40 : rem screen width
120 sh=25 : rem screen height
130 pc=42 : rem plot character '*'
140 gosub 1000
150 end
1000 rem plot line
1010 if abs(y1-y0)>abs(x1-x0) then se=1:tp=y0:y0=x0:x0=tp:tp=y1:y1=x1:x1=tp
1020 if x0>x1 then tp=x1:x1=x0:x0=tp:tp=y1:y1=y0:y0=tp
1030 dx=x1-x0
1040 dy=abs(y1-y0)
1050 er=dx/2
1060 y=y0
1070 ys=-1
1080 if y0<y1 then ys = 1
1090 for x=x0 to x1
1100 if se=1 then p0=y: p1=x:gosub 2000:goto 1120
1110 p0=x: p1=y: gosub 2000
1120 er=er-dy
1130 if er<0 then y=y+ys:er=er+dx
1140 next x
1150 return
2000 rem plot individual point
2010 rem p0 == plot point x
2020 rem p1 == plot point y
2030 sl=p0+(p1*sw)
2040 rem make sure we dont write beyond screen memory
2050 if sl<(sw*sh) then poke sc+sl,pc
2060 return
|
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. | #Perl | Perl | use strict;
use warnings;
use feature 'say';
my @bases = <A C G T>;
my $dna;
$dna .= $bases[int rand 4] for 1..200;
my %cnt;
$cnt{$_}++ for split //, $dna;
sub pretty {
my($string) = @_;
my $chunk = 10;
my $wrap = 5 * ($chunk+1);
($string =~ s/(.{$chunk})/$1 /gr) =~ s/(.{$wrap})/$1\n/gr;
}
sub mutate {
my($dna,$count) = @_;
my $orig = $dna;
substr($dna,rand length $dna,1) = $bases[int rand 4] while $count > diff($orig, $dna) =~ tr/acgt//;
$dna
}
sub diff {
my($orig, $repl) = @_;
for my $i (0 .. -1+length $orig) {
substr($repl,$i,1, lc substr $repl,$i,1) if substr($orig,$i,1) ne substr($repl,$i,1);
}
$repl;
}
say "Original DNA strand:\n" . pretty($dna);
say "Total bases: ". length $dna;
say "$_: $cnt{$_}" for @bases;
my $mutate = mutate($dna, 10);
%cnt = ();
$cnt{$_}++ for split //, $mutate;
say "\nMutated DNA strand:\n" . pretty diff $dna, $mutate;
say "Total bases: ". length $mutate;
say "$_: $cnt{$_}" for @bases;
|
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.
| #PicoLisp | PicoLisp | (load "sha256.l")
(setq *Alphabet
(chop "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") )
(de unbase58 (Str)
(let (Str (chop Str) Lst (need 25 0) C)
(while (setq C (dec (index (pop 'Str) *Alphabet)))
(for (L Lst L)
(set
L (& (inc 'C (* 58 (car L))) 255)
'C (/ C 256) )
(pop 'L) ) )
(flip Lst) ) )
(de valid (Str)
(and
(setq @@ (unbase58 Str))
(=
(head 4 (sha256 (sha256 (head 21 @@))))
(tail 4 @@) ) ) )
(test
T
(valid "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j") )
(test
T
(=
NIL
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j")
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!")
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz")
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz") ) ) |
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.
| #PureBasic | PureBasic |
; using PureBasic 5.50 (x64)
EnableExplicit
Macro IsValid(expression)
If expression
PrintN("Valid")
Else
PrintN("Invalid")
EndIf
EndMacro
Procedure.i DecodeBase58(Address$, Array result.a(1))
Protected i, j, p
Protected charSet$ = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
Protected c$
For i = 1 To Len(Address$)
c$ = Mid(Address$, i, 1)
p = FindString(charSet$, c$) - 1
If p = -1 : ProcedureReturn #False : EndIf; Address contains invalid Base58 character
For j = 24 To 1 Step -1
p + 58 * result(j)
result(j) = p % 256
p / 256
Next j
If p <> 0 : ProcedureReturn #False : EndIf ; Address is too long
Next i
ProcedureReturn #True
EndProcedure
Procedure HexToBytes(hex$, Array result.a(1))
Protected i
For i = 1 To Len(hex$) - 1 Step 2
result(i/2) = Val("$" + Mid(hex$, i, 2))
Next
EndProcedure
Procedure.i IsBitcoinAddressValid(Address$)
Protected format$, digest$
Protected i, isValid
Protected Dim result.a(24)
Protected Dim result2.a(31)
Protected result$, result2$
; Address length must be between 26 and 35 - see 'https://en.bitcoin.it/wiki/Address'
If Len(Address$) < 26 Or Len(Address$) > 35 : ProcedureReturn #False : EndIf
; and begin with either 1 or 3 which is the format number
format$ = Left(Address$, 1)
If format$ <> "1" And format$ <> "3" : ProcedureReturn #False : EndIf
isValid = DecodeBase58(Address$, result())
If Not isValid : ProcedureReturn #False : EndIf
UseSHA2Fingerprint(); Using functions from PB's built-in Cipher library
digest$ = Fingerprint(@result(), 21, #PB_Cipher_SHA2, 256); apply SHA2-256 to first 21 bytes
HexToBytes(digest$, result2()); change hex string to ascii array
digest$ = Fingerprint(@result2(), 32, #PB_Cipher_SHA2, 256); apply SHA2-256 again to all 32 bytes
HexToBytes(digest$, result2())
result$ = PeekS(@result() + 21, 4, #PB_Ascii); last 4 bytes
result2$ = PeekS(@result2(), 4, #PB_Ascii); first 4 bytes
If result$ <> result2$ : ProcedureReturn #False : EndIf
ProcedureReturn #True
EndProcedure
If OpenConsole()
Define address$ = "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"
Define address2$ = "1BGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"
Define address3$ = "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"
Print(address$ + " -> ")
IsValid(IsBitcoinAddressValid(address$))
Print(address2$ + " -> ")
IsValid(IsBitcoinAddressValid(address2$))
Print(address3$ + " -> ")
IsValid(IsBitcoinAddressValid(address3$))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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.
| #Pascal | Pascal |
program FloodFillTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
Winapi.Windows,
System.SysUtils,
System.Generics.Collections,
vcl.Graphics;
procedure FloodFill(bmp: tBitmap; pt: TPoint; targetColor: TColor;
replacementColor: TColor);
var
q: TQueue<TPoint>;
n, w, e: TPoint;
begin
q := TQueue<TPoint>.Create;
q.Enqueue(pt);
while (q.Count > 0) do
begin
n := q.Dequeue;
if bmp.Canvas.Pixels[n.X, n.Y] <> targetColor then
Continue;
w := n;
e := TPoint.Create(n.X + 1, n.Y);
while ((w.X >= 0) and (bmp.Canvas.Pixels[w.X, w.Y] = targetColor)) do
begin
bmp.Canvas.Pixels[w.X, w.Y] := replacementColor;
if ((w.Y > 0) and (bmp.Canvas.Pixels[w.X, w.Y - 1] = targetColor)) then
q.Enqueue(TPoint.Create(w.X, w.Y - 1));
if ((w.Y < bmp.Height - 1) and (bmp.Canvas.Pixels[w.X, w.Y + 1] = targetColor)) then
q.Enqueue(TPoint.Create(w.X, w.Y + 1));
dec(w.X);
end;
while ((e.X <= bmp.Width - 1) and (bmp.Canvas.Pixels[e.X, e.Y] = targetColor)) do
begin
bmp.Canvas.Pixels[e.X, e.Y] := replacementColor;
if ((e.Y > 0) and (bmp.Canvas.Pixels[e.X, e.Y - 1] = targetColor)) then
q.Enqueue(TPoint.Create(e.X, e.Y - 1));
if ((e.Y < bmp.Height - 1) and (bmp.Canvas.Pixels[e.X, e.Y + 1] = targetColor)) then
q.Enqueue(TPoint.Create(e.X, e.Y + 1));
inc(e.X);
end;
end;
q.Free;
end;
var
bmp: TBitmap;
begin
bmp := TBitmap.Create;
try
bmp.LoadFromFile('Unfilledcirc.bmp');
FloodFill(bmp, TPoint.Create(200, 200), clWhite, clRed);
FloodFill(bmp, TPoint.Create(100, 100), clBlack, clBlue);
bmp.SaveToFile('Filledcirc.bmp');
finally
bmp.Free;
end;
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.