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...
#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; }   fun...
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...
#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"...
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 |...
#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 "va...
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 pixe...
#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 - radi...
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 ...
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...
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 u...
#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", ...
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 u...
#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 r...
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 u...
#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...
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 la...
#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 TCAGTCCCAATGTG...
#C.2B.2B
C++
#include <map> #include <string> #include <iostream> #include <iomanip>   const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATC...
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.Blu...
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 o...
#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:"); ...
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 th...
#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): INTEG...
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 vall...
#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, -...
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 vall...
#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, targe...
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...
#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 ...
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...
#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 = ["...
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 |...
#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 s...
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 pixe...
#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 sub...
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-ra...
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 $im...
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) ...
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] }   m...
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 u...
#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"}, ...
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 la...
#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...
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] ...
#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)...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Delphi
Delphi
  program base_count;   {$APPTYPE CONSOLE}   uses System.SysUtils, Generics.Collections, System.Console;   const DNA = 'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG' + 'CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' + 'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT' + 'GGGACGTTTCGTCGA...
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 ...
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 o...
#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 {numb...
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 th...
#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{$...
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 vall...
#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...
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...
#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...
#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 th...
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 |...
#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# ##>`Arithmet...
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 pixe...
#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$("000...
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...
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 - xmi...
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 u...
#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 s...
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 la...
#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;...
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] ...
#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 ...
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] ...
#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; proc...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Factor
Factor
USING: assocs formatting grouping io kernel literals math math.statistics prettyprint qw sequences sorting ;   CONSTANT: dna $[ qw{ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Forth
Forth
  ( Gforth 0.7.3 )   : dnacode s" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCG...
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])] (l...
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 o...
#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); se...
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 o...
#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)..ne...
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 th...
#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==fal...
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 vall...
#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 vall...
#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...
#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. W...
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...
#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...
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 |...
#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 ...
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 pixe...
#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; }...
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("m...
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 {se...
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 u...
#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 ...
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 u...
#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 b...
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 la...
#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...
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] ...
#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 ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#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"+_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGG...
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 += s...
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 o...
#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}];...
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 o...
#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 valu...
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 th...
#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; } functio...
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 vall...
#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], SetAlph...
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 vall...
#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.po...
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...
#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...
#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" ...
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 |...
#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 inte...
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 pixe...
#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(...
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...
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 +...
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...
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,...
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 u...
#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...
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 u...
#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...
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 u...
#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,-...
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 la...
#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"   ; ap...
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] ...
#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...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "sort" )   func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTA...
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 ...
#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:~$...
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=1...
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 o...
#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; }   su...
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 th...
#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...
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 th...
#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" P...
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 vall...
#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>....