task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Elena
Elena
  iex(1)> true === :true true iex(2)> false === :false true iex(3)> true === 1 false  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Elixir
Elixir
  iex(1)> true === :true true iex(2)> false === :false true iex(3)> true === 1 false  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Ursala
Ursala
#import std #import nat   enc "n" = * -:~&@T ^p(rep"n" ~&zyC,~&)~~K30K31X letters # encryption function dec "n" = * -:~&@T ^p(~&,rep"n" ~&zyC)~~K30K31X letters # decryption function   plaintext = 'the five boxing wizards jump quickly THE FIVE BOXING WIZARDS JUMP QUICKLY'   #show+ # exhaustive test   test = ("n". ...
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...
#C.2B.2B
C++
#include <string> #include <boost/array.hpp> #include <boost/assign/list_of.hpp> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <iostream> #include <math.h> using std::string; using namespace boost::assign;   int get_Index(float angle) { return static_cast<int>(floor(angle / 11.25 +0.5 )) % 32 + 1...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @.data; }   role PBM { has @.BM; method P4 returns Blob { "P4\n{self.width} {self.height}\n".encode('ascii') ~ Blob.new: self.BM } }   sub getline ( $fh ) { my $line = '#'; # skip comments when read...
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 |...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   -- BIT OPERATIONS FOR APPLESCRIPT (VIA JAVASCRIPT FOR AUTOMATION)   -- bitAND :: Int -> Int -> Int on bitAND(x, y) jsOp2("&", x, y) end bitAND   -- bitOR :: Int -> Int -> Int on bitOR(x, y) jsOp2("|", x, y) end bitOR   -- bitXOr ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Python
Python
  #lang racket (require racket/draw)   (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))   (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p)))   (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#R
R
  #lang racket (require racket/draw)   (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))   (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p)))   (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Racket
Racket
  #lang racket (require racket/draw)   (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)]))   (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p)))   (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @!data;   method fill(Pixel $p) { @!data = $p.clone xx ($!width*$!height) } method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] }   m...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Julia
Julia
function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T x = radius - 1 y = 0 δx = δy = 1 er = δx - (radius << 1)   s = x + y while x ≥ y for opx in (+, -), opy in (+, -), el in (x, y) @inbounds img[opx(x0, el) + 1, opy(y0, s - el) + 1] = col ...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Lua
Lua
function Bitmap:circle(x, y, r, c) local dx, dy, err = r, 0, 1-r while dx >= dy do self:set(x+dx, y+dy, c) self:set(x-dx, y+dy, c) self:set(x+dx, y-dy, c) self:set(x-dx, y-dy, c) self:set(x+dy, y+dx, c) self:set(x-dy, y+dx, c) self:set(x+dy, y-dx, c) self:set(x-dy, y-dx, c) dy = ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#FreeBASIC
FreeBASIC
' version 01-11-2016 ' compile with: fbc -s console   ' translation from Bitmap/Bresenham's line algorithm C entry Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, _ Col As UInteger = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) ...
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...
#11l
11l
F biorhythms(birthdate_str, targetdate_str) ‘ Print out biorhythm data for targetdate assuming you were born on birthdate.   birthdate and targetdata are strings in this format:   YYYY-MM-DD e.g. 1964-12-26 ’   print(‘Born: ’birthdate_str‘ Target: ’targetdate_str)   V birthdate = time:strpti...
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Visual_Basic_.NET
Visual Basic .NET
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) ...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Ada
Ada
procedure Line (Picture : in out Image; Start, Stop : Point; Color : Pixel) is DX  : constant Float := abs Float (Stop.X - Start.X); DY  : constant Float := abs Float (Stop.Y - Start.Y); Err : Float; X  : Positive := Start.X; Y  : Positive := Start.Y; Step_X : Integer := 1; Step_Y : Integer := 1;...
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...
#C.23
C#
  using System; using System.Linq; using System.Security.Cryptography; using NUnit.Framework;   namespace BitcoinValidator { public class ValidateTest { [TestCase] public void ValidateBitcoinAddressTest() { Assert.IsTrue(ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Haskell
Haskell
import Numeric (showIntAtBase) import Data.List (unfoldr) import Data.Binary (Word8) import Crypto.Hash.SHA256 as S (hash) import Crypto.Hash.RIPEMD160 as R (hash) import Data.ByteString (unpack, pack)   publicPointToAddress :: Integer -> Integer -> String publicPointToAddress x y = let toBytes x = reverse $ unfoldr...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Julia
Julia
const digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" function encodebase58(b::Vector{<:Integer}) out = Vector{Char}(34) for j in endof(out):-1:1 local c::Int = 0 for i in eachindex(b) c = c * 256 + b[i] b[i] = c ÷ 58 c %= 58 end ...
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...
#E
E
def floodFill(image, x, y, newColor) { def matchColor := image[x, y] def w := image.width() def h := image.height()   /** For any given pixel x,y, this algorithm first fills a contiguous horizontal line segment of pixels containing that pixel, then recursively scans the two adjacent rows over the s...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Elm
Elm
  --True and False directly represent Boolean values in Elm --For eg to show yes for true and no for false if True then "yes" else "no"   --Same expression differently if False then "no" else "yes"   --This you can run as a program --Elm allows you to take anything you want for representation --In the program we take T...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Emacs_Lisp
Emacs Lisp
1> 1 < 2. true 2> 1 < 1. false 3> 0 == false. false
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Vala
Vala
static void println(string str) { stdout.printf("%s\r\n", str); }   static unichar encrypt_char(unichar ch, int code) { if (!ch.isalpha()) return ch;   unichar offset = ch.isupper() ? 'A' : 'a'; return (unichar)((ch + code - offset) % 26 + offset); }   static string encrypt(string input, int code) { ...
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...
#Clojure
Clojure
(ns boxing-the-compass (:use [clojure.string :only [capitalize]]))   (def headings (for [i (range 0 (inc 32))] (let [heading (* i 11.25)] (case (mod i 3) 1 (+ heading 5.62) 2 (- heading 5.62) heading))))   (defn angle2compass [angle] (let [dirs ["N" "NbE" "N-NE" "NEbN" "NE" "...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Ruby
Ruby
class Pixmap def histogram histogram = Hash.new(0) @height.times do |y| @width.times do |x| histogram[self[x,y].luminosity] += 1 end end histogram end   def to_blackandwhite hist = histogram   # find the median luminosity median = nil sum = 0 hist.keys.sort...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Rust
Rust
extern crate image; use image::{DynamicImage, GenericImageView, ImageBuffer, Rgba};   /// index of the alpha channel in RGBA const ALPHA: usize = 3;   /// Computes the luminance of a single pixel /// Result lies within `u16::MIN..u16::MAX` const fn luminance(rgba: Rgba<u8>) -> u16 { let Rgba([r, g, b, _a]) = rgba; ...
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 |...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program binarydigit.s */ /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data szMessResultAnd: .asciz "Result of And : \n" szMessResultOr: .asciz "Result of Or : \n" szMessResultEor: .asciz "Result of Exclusif Or : \n" szMessResultNot: ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Ruby
Ruby
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 → pt For i,1,segs+1 (i-1.0)/segs → t © Decimal to avoid slow exact arithetic (1-t) → u pt → prev u^2*p1 + 2*t*u*p2 + t^2*p3 → pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf E...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Tcl
Tcl
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 → pt For i,1,segs+1 (i-1.0)/segs → t © Decimal to avoid slow exact arithetic (1-t) → u pt → prev u^2*p1 + 2*t*u*p2 + t^2*p3 → pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf E...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#TI-89_BASIC
TI-89 BASIC
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 → pt For i,1,segs+1 (i-1.0)/segs → t © Decimal to avoid slow exact arithetic (1-t) → u pt → prev u^2*p1 + 2*t*u*p2 + t^2*p3 → pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf E...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Vedit_macro_language
Vedit macro language
// Daw a Cubic bezier curve // #20, #30 = Start point // #21, #31 = Control point 1 // #22, #32 = Control point 2 // #23, #33 = end point // #40 = depth of recursion   :CUBIC_BEZIER: if (#40 > 0) { #24 = (#20+#21)/2; #34 = (#30+#31)/2 #26 = (#22+#23)/2; #36 = (#32+#33)/2 #27 =...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Kotlin
Kotlin
// version 1.1.4-3   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage import javax.swing.JOptionPane import javax.swing.JLabel import javax.swing.ImageIcon   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)  ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Go
Go
package raster   const b3Seg = 30   func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; }   void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf("%12s cycle: %3i%%", t, p); if (abs(p) < 15) ...
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window, Process import "io" for FileSystem   class Bitmap { construct new(name, width, height) { Window.title = name Window.resize(width, height) Canvas.resize(width, height) _bmp = ImageData.create(name, width, height)...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID: BEGIN REAL dx = ABS (x OF stop - x OF start), dy = ABS (y OF stop - y OF start); REAL err; POINT here := start, step := (1, 1); IF x OF start > x OF stop THEN x OF step := -1 ...
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...
#11l
11l
UInt32 seed = 0 F nonrandom(n)  :seed = 1664525 * :seed + 1013904223 R Int(:seed >> 16) % n F nonrandom_choice(lst) R lst[nonrandom(lst.len)]   F basecount(dna) DefaultDict[Char, Int] d L(c) dna d[c]++ R sorted(d.items())   F seq_split(dna, n = 50) R (0 .< dna.len).step(n).map(i -> @dna[i .< i...
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...
#D
D
import std.stdio, std.algorithm, std.array, std.string, sha_256_2;   struct A25 { // Type for a 25 ubyte (not base58 encoded) bitcoin address. ubyte[25] enc;   ubyte bitcoinVersion() const pure nothrow @safe @nogc { return enc[0]; }   ubyte[4] embeddedChecksum() return const pure nothrow @sa...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Wolfram_Language.2FMathematica
Wolfram Language/Mathematica
BlockchainKeyEncode[ PublicKey[ <| "Type"->"EllipticCurve", "PublicCurvePoint"-> { 16^^50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352, 16^^2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6 } |> ], "Address", BlockchainBase-> "Bitcoin" ]
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Nim
Nim
import parseutils import nimcrypto import bignum   func base58Encode(data: seq[byte]): string = ## Encode data to base58 with at most one starting '1'.   var data = data const Base = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" result.setlen(34)   # Convert to base 58. for j in countdown(res...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Perl
Perl
  use Crypt::RIPEMD160; use Digest::SHA qw(sha256); use Encode::Base58::GMP;   sub public_point_to_address { my $ec = join '', '04', @_; # EC: concat x and y to one string and prepend '04' magic value   my $octets = pack 'C*', map { hex } unpack('(a2)65', $ec); # transform the hex va...
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...
#ERRE
ERRE
  PROGRAM MYFILL_DEMO   !VAR SP%   !$INTEGER   CONST IMAGE_WIDTH=320,IMAGE_HEIGHT=200   DIM STACK[6000,1]   FUNCTION QUEUE_COUNT(X) QUEUE_COUNT=SP END FUNCTION   !$INCLUDE="PC.LIB"   PROCEDURE QUEUE_INIT SP=0 END PROCEDURE   PROCEDURE QUEUE_POP(->XX,YY) XX=STACK[SP,0] YY=STACK[SP,1] SP=SP-1 END PROCED...
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...
#Euler_Math_Toolbox
Euler Math Toolbox
  >file="test.png"; >A=loadrgb(file); ... >insrgb(A); >function floodfill (A0,i,j,color,dist) ... $ A=A0; $ R=getred(A); G=getgreen(A); B=getblue(A); $ d=sqrt((R-R[i,j])^2+(G-G[i,j])^2+(B-B[i,j])^2); $ n=rows(A); m=cols(A); $ V=zeros(n,m); $ S=zeros(n*m,2); sn=0; $ A[i,j]=color; V[i,j]=1; $ repeat; $ if fill...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Erlang
Erlang
1> 1 < 2. true 2> 1 < 1. false 3> 0 == false. false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Excel
Excel
=AND(A1;B1)
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#VBA
VBA
  Option Explicit   Sub Main_Caesar() Dim ch As String ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14) Debug.Print ch Debug.Print Caesar_Cipher(ch, -14) End Sub   Function Caesar_Cipher(sT...
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...
#COBOL
COBOL
identification division. program-id. box-compass. data division. working-storage section. 01 point pic 99. 01 degrees usage float-short. 01 degrees-rounded pic 999v99. 01 show-degrees pic zz9.99. 01 box ...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Scala
Scala
object BitmapOps { def histogram(bm:RgbBitmap)={ val hist=new Array[Int](255) for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) hist(l)+=1 hist }   def histogram_median(hist:Array[Int])={ var from=0 var to=hist.size-1 var left=hist(f...
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 |...
#Arturo
Arturo
a: 255 b: 2   print [a "AND" b "=" and a b] print [a "OR" b "=" or a b] print [a "XOR" b "=" xor a b] print ["NOT" a "=" not a] print [a "SHL" b "=" shl a b] print [a "SHR" b "=" shr a b]
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Wren
Wren
import "graphics" for Canvas, ImageData, Color, Point import "dome" for Window   class Game { static bmpCreate(name, w, h) { ImageData.create(name, w, h) }   static bmpFill(name, col) { var image = ImageData[name] for (x in 0...image.width) { for (y in 0...image.height) image.pset(x,...
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...
#11l
11l
T Colour Byte r, g, b   F (r, g, b) .r = r .g = g .b = b   F ==(other) R .r == other.r & .g == other.g & .b == other.b   V black = Colour(0, 0, 0) V white = Colour(255, 255, 255)   T Bitmap Int width, height Colour background [[Colour]] map   F (width = 40, height = 40, back...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
SetAttributes[drawcircle, HoldFirst]; drawcircle[img_, {x0_, y0_}, r_, color_: White] := Module[{f = 1 - r, ddfx = 1, ddfy = -2 r, x = 0, y = r, pixels = {{0, r}, {0, -r}, {r, 0}, {-r, 0}}}, While[x < y, If[f >= 0, y--; ddfy += 2; f += ddfy]; x++; ddfx += 2; f += ddfx; pixels = Join[pixels, {{x, y}, {x, ...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Modula-3
Modula-3
INTERFACE Circle;   IMPORT Bitmap;   PROCEDURE Draw( img: Bitmap.T; center: Bitmap.Point; radius: CARDINAL; color: Bitmap.Pixel);   END Circle.
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#J
J
require 'numeric'   bik=: 2 : '((*&(u!v))@(^&u * ^&(v-u)@-.))' basiscoeffs=: <: 4 : 'x bik y t. i.>:y'"0~ i. linearcomb=: basiscoeffs@#@[ evalBernstein=: ([ +/ .* linearcomb) p. ] NB. evaluate Bernstein Polynomial (general)   NB.*getBezierPoints v Returns points for bezier curve given control points (y) NB. eg: ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#JavaScript
JavaScript
  function draw() { var canvas = document.getElementById("container"); context = canvas.getContext("2d");   bezier3(20, 200, 700, 50, -300, 50, 380, 150); // bezier3(160, 10, 10, 40, 30, 160, 150, 110); // bezier3(0,149, 30,50, 120,130, 160,30, 0); }   // http://rosettacode.org/wiki/Cubic_bezier...
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...
#Common_Lisp
Common Lisp
;;;; Common Lisp biorhythms   ;;; Get the days to J2000 ;;; FNday only works between 1901 to 2099 - see Meeus chapter 7   (defun day (y m d) (+ (truncate (* -7 (+ y (truncate (+ m 9) 12))) 4) (truncate (* 275 m) 9) d -730530 (* 367 y)))   ;;; Get the difference in days between two dates   (defun diffday (y...
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...
#Delphi
Delphi
  program Biorhythms;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   var cycles: array[0..2] of string = ('Physical day ', 'Emotional day', 'Mental day '); lengths: array[0..2] of Integer = (23, 28, 33); quadrants: array[0..3] of array[0..1] of string = (('up and rising', 'peak'), ('up but ...
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations def Width=180, Height=135, Color=$123456;   proc WriteImage; \Write screen image to a a PPM file int X, Y, C; [Text(3,"P6 "); IntOut(3,Width); ChOut(3,^ ); IntOut(3,Height); Text(3," 255 "); for Y:= 0 to Height-1 do for X:= 0 to Width-1 ...
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Yabasic
Yabasic
clear screen   wid = 150 : hei = 200 open window wid, hei window origin "cc" color 255, 0, 0 fill circle 0, 0, 50 color 0, 255, 0 fill circle 0, 0, 35 color 0, 0, 255 fill circle 0, 0, 20 window origin "lt"   header$ = "P6\n" + str$(wid) + " " + str$(hei) + "\n255\n"   fn = open("exmaple.PPM", "wb")   print #fn header$...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Assembly
Assembly
.486 IDEAL ;--------------------------------------------- ; case: DeltaY is bigger than DeltaX ; input: p1X p1Y, ; p2X p2Y, ; Color -> variable ; output: line on the screen ;--------------------------------------------- Macro DrawLine2DDY p1X, p1Y, p2...
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...
#Ada
Ada
with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random; with Ada.Text_Io;   procedure Mutations is   Width : constant := 60;   type Nucleotide_Type is (A, C, G, T); type Operation_Type is (Delete, Insert, Swap); type Position_Type is new Natural;   package Position_Io is new Ada.Text_Io.Integer...
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...
#Dart
Dart
import 'package:crypto/crypto.dart';   class Bitcoin { final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";   List<int> bigIntToByteArray(BigInt data) { String str; bool neg = false; if (data < BigInt.zero) { str = (~data).toRadixString(16); neg = true;...
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...
#Delphi
Delphi
  uses DCPsha256;   type TByteArray = array of Byte;   function HashSHA256(const Input: TByteArray): TByteArray; var Hasher: TDCP_sha256; begin Hasher := TDCP_sha256.Create(nil); try Hasher.Init; Hasher.Update(Input[0], Length(Input)); SetLength(Result, Hasher.HashSize div 8); Hasher.Final(Res...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Phix
Phix
without javascript_semantics -- no ripemd160.js as yet include builtins\sha256.e include builtins\ripemd160.e constant b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" function base58(string s) string out = "" if length(s)!=25 then ?9/0 end if for n=1 to 34 do integer c = 0 ...
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...
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Before Flood Fill") ' Set form caption FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 220, 220) CENTER(ME) SHOW(ME)   DIM Breadth AS ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#F.23
F#
type bool = System.Boolean
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Factor
Factor
TRUE . \ -1 FALSE . \ 0
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#VBScript
VBScript
  str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."   Wscript.Echo str Wscript.Echo Rotate(str,5) Wscript.Echo Rotate(Rotate(str,5),-5)   'Rotate (Caesar encrypt/decrypt) test <numpos> positions. ' numpos < 0 - rotate left ' numpos > 0 - rotate right 'Left rotation is converted to equivalent right ...
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...
#D
D
import std.stdio, std.string, std.math, std.array;   struct boxTheCompass { immutable static string[32] points;   pure nothrow static this() { immutable cardinal = ["north", "east", "south", "west"]; immutable desc = ["1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C"...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Tcl
Tcl
package require Tcl 8.5 package require Tk   proc convert_to_blackandwhite {filename} { set img [image create photo] readPPM $img $filename grayscale $img set hist [histogram $img] set median [median $img $hist] blackandwhite $img $median output_ppm $img bw_$filename }   proc histogram {imag...
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 |...
#AutoHotkey
AutoHotkey
bitwise(3, 4) bitwise(a, b) { MsgBox % "a and b: " . a & b MsgBox % "a or b: " . a | b MsgBox % "a xor b: " . a ^ b MsgBox % "not a: " . ~a ; treated as unsigned integer MsgBox % "a << b: " . a << b ; left shift MsgBox % "a >> b: " . a >> b ; arithmetic right shift }
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Bezier(P0, P1, P2); \Draw quadratic Bezier curve real P0, P1, P2; def Segments = 8; int I; real T, A, B, C, X, Y; [Move(fix(P0(0)), fix(P0(1))); for I:= 1 to Segments do [T:= float(I)/float(Segments); A:= sq(1.-T); B:...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#zkl
zkl
fcn qBezier(p0x,p0y, p1x,p1y, p2x,p2y, rgb, numPts=500){ numPts.pump(Void,'wrap(t){ // B(t) t=t.toFloat()/numPts; t1:=(1.0 - t); a:=t1*t1; b:=t*t1*2; c:=t*t; x:=a*p0x + b*p1x + c*p2x + 0.5; y:=a*p0y + b*p1y + c*p2y + 0.5; __sSet(rgb,x,y); }); }
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Action.21
Action!
INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap   RGB black,yellow,violet,blue   PROC DrawImage(RgbImage POINTER img BYTE x,y) RGB c BYTE i,j   FOR j=0 TO img.h-1 DO FOR i=0 TO img.w-1 DO GetRgbPixel(img,i,j,c) IF RgbEqual(c,yellow) THEN Color=1 ELSEIF RgbEqual(c,violet) THEN ...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Nim
Nim
import bitmap   proc setPixel(img: Image; x, y: int; color: Color) {.inline.} = # Set a pixel at a given color. # Ignore if the point is outside of the image. if x in 0..<img.w and y in 0..<img.h: img[x, y] = color     proc drawCircle(img: Image; center: Point; radius: Natural; color: Color) = ## Draw a cir...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Perl
Perl
# 20220301 Perl programming solution   use strict; use warnings;   use Algorithm::Line::Bresenham 'circle';   my @points; my @circle = circle((10) x 3);   for (@circle) { $points[$_->[0]][$_->[1]] = '#' }   print join "\n", map { join '', map { $_ || ' ' } @$_ } @points
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Julia
Julia
using Images   function cubicbezier!(xy::Matrix, img::Matrix = fill(RGB(255.0, 255.0, 255.0), 17, 17), col::ColorTypes.Color = convert(eltype(img), Gray(0.0)), n::Int = 20) t = collect(0:n) ./ n M = hcat((1 .- t) .^ 3, # a 3t .* (1 ....
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Kotlin
Kotlin
// Version 1.2.40   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage import kotlin.math.abs import java.io.File import javax.imageio.ImageIO   class Point(var x: Int, var y: Int)   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, Buffered...
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...
#Emacs_Lisp
Emacs Lisp
(require 'calendar)   (setq biorhythm-birthdate '(3 16 1953))   (defun biorhythm () "Show today's biorhythm." (interactive) (let* ((diff (abs (- (string-to-number (calendar-astro-date-string biorhythm-birthdate)) (string-to-number (calendar-astro-date-string))))) (rhyt '(23 ...
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...
#Factor
Factor
USING: calendar calendar.parser formatting io kernel math math.constants math.functions ;   : days-between ( ymd-str ymd-str -- n ) [ ymd>timestamp ] bi@ time- duration>days abs ;   : trend ( pos len -- str ) / 4 * floor 3 divisor? "↑" "↓" ? ;   : percent ( pos len -- x ) [ 2pi * ] [ / sin 100 * ] bi* ;   : .day ( ...
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#zkl
zkl
// convert Windows BMP (bit map) image to PPM   // Read BMP file bmp:=File.stdin.read().howza(0); // BMP to memory (byte bucket), treat as bytes _assert_(bmp[0]==0x42,"Stdin not a BMP file"); width:=bmp.toLittleEndian(18,2,False); height:=bmp.toLittleEndian(22,2,False); // signed println(width," x ",height); bmp.de...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#AutoHotkey
AutoHotkey
Blue := Color(0,0,255) White := Color(255,255,255) Bitmap := Bitmap(100,100,Blue) ;create a 100*100 blue bitmap Line(Bitmap,White,5,10,60,80) ;draw a white line from (5,10) to (60,80) Bitmap.Write("Line.ppm") ;write the bitmap to file   Line(ByRef Bitmap,ByRef Color,PosX1,PosY1,PosX2,PosY2) { DeltaX := Abs(PosX2 - Pos...
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...
#Arturo
Arturo
bases: ["A" "T" "G" "C"] dna: map 1..200 => [sample bases]   prettyPrint: function [in][ count: #[ A: 0, T: 0, G: 0, C: 0 ]   loop.with:'i split.every:50 in 'line [ prints [pad to :string i*50 3 ":"] print map split.every:10 line => join   loop split line 'ch [ case [ch=] ...
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...
#Erlang
Erlang
  -module( bitcoin_address ).   -export( [task/0, validate/1] ).   task() -> io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"] ), io:fwrite( "~p~n", [validate("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")] ), io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW622"] ), io:fwrite( "~p~n", [validate...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#PicoLisp
PicoLisp
(load "ripemd160.l") (load "sha256.l")   (setq *B58Alpha (chop "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") ) (de hex2L (H) (make (for (L (chop H) L (cddr L)) (link (hex (pack (car L) (cadr L)))) ) ) ) (de b58enc (Lst) (let (P 1 Z 0 A (sum ...
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Python
Python
#!/usr/bin/env python3   import binascii import functools import hashlib   digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'   def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b''   def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(...
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...
#Forth
Forth
: third 2 pick ; : 3dup third third third ; : 4dup 2over 2over ;   : flood ( color x y bmp -- ) 3dup b@ >r ( R: color to fill ) 4dup b! third 0 > if rot 1- -rot 3dup b@ r@ = if recurse then rot 1+ -rot then third 1+ over bwidth < if rot 1+ -rot 3dup b@ r@ = if recurse then rot 1- -r...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#FALSE
FALSE
TRUE . \ -1 FALSE . \ 0
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Fantom
Fantom
TRUE . \ -1 FALSE . \ 0
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Vedit_macro_language
Vedit macro language
#10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)   Goto_Pos(Block_Begin) while(Cur_Pos < Block_End) { #11 = Cur_Char & 0x60 + 1 if (Cur_Char >= 'A') { Ins_Char((Cur_Char - #11 + 26 + #10) % 26 + #11, OVERWRITE) } else { Char(1) } }
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Delphi
Delphi
defmodule Box do defp head do Enum.chunk(~w(north east south west north), 2, 1) |> Enum.flat_map(fn [a,b] -> c = if a=="north" or a=="south", do: "#{a}#{b}", else: "#{b}#{a}" [ a, "#{a} by #{b}", "#{a}-#{c}", "#{c} by #{a}", c, "#{c} by #{b}", "#{b}-#{c}", "#{b} by #{a}" ] ...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Vedit_macro_language
Vedit macro language
:HISTOGRAM: #30 = Buf_Free // #30 = buffer to store histogram data for (#9=0; #9<256; #9++) { Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted Buf_Switch(#15) // switch to image buffer #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values Buf_Switch(#30) ...
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color, ImageData   class ImageHistogram { construct new(filename, filename2) { _image = ImageData.loadFromFile(filename) Window.resize(_image.width, _image.height) Canvas.resize(_image.width, _image.height) Window.title = filena...
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 |...
#AutoIt
AutoIt
bitwise(255, 5) Func bitwise($a, $b) MsgBox(1, '', _ $a & " AND " & $b & ": " & BitAND($a, $b) & @CRLF & _ $a & " OR " & $b & ": " & BitOR($a, $b) & @CRLF & _ $a & " XOR " & $b & ": " & BitXOR($a, $b) & @CRLF & _ "NOT " & $a & ": " & BitNOT($a) & @CRLF & _ $a & " SHL " & $b & ": " & BitShift($a, $...
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...
#ActionScript
ActionScript
  // To import the BitmapData class: import flash.display.BitmapData;   // Creates a new BitmapData object with a width of 500 pixels and a height of 300 pixels. var bitmap:BitmapData = new BitmapData(500, 300);   // Create a BitmapData with transparency disallowed var opaqueBitmap:BitmapData = new BitmapData(500, 300,...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Phix
Phix
-- demo\rosetta\Bitmap_Circle.exw (runnable version) include ppm.e -- red, yellow, new_image(), write_ppm() -- (covers above requirements)   function SetPx(sequence img, atom x, y, integer colour) if x>=1 and x<=length(img) and y>=1 and y<=length(img[x]) then img[x][y] = colour end if return ...
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#PicoLisp
PicoLisp
(de midPtCircle (Img CX CY Rad) (let (F (- 1 Rad) DdFx 0 DdFy (* -2 Rad) X 0 Y Rad) (set (nth Img (+ CY Rad) CX) 1) (set (nth Img (- CY Rad) CX) 1) (set (nth Img CY (+ CX Rad)) 1) (set (nth Img CY (- CX Rad)) 1) (while (> Y X) (when (ge0 F) (dec 'Y) ...
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Lua
Lua
Bitmap.cubicbezier = function(self, x1, y1, x2, y2, x3, y3, x4, y4, nseg) nseg = nseg or 10 local prevx, prevy, currx, curry for i = 0, nseg do local t = i / nseg local a, b, c, d = (1-t)^3, 3*t*(1-t)^2, 3*t^2*(1-t), t^3 prevx, prevy = currx, curry currx = math.floor(a * x1 + b * x2 + c * x3 + d *...
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...
#FOCAL
FOCAL
1.01 T "Enter birthdate (y,m,d)",! 1.02 ASK Y,M,D 1.03 D 2; S BZ=Z 1.04 T "Enter today's date (y,m,d)",! 1.05 ASK Y,M,D 1.06 D 2; S DI=Z - BZ 1.07 T %6,"Age in days", DI,! 1.08 T "Physical cycle: " 1.09 S L=23; D 3 1.10 T "Emotional cycle: " 1.11 S L=28; D 3 1.12 T "Intellectual cycle: " 1.13 S L=33; D 3 1.14 Q ...
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...
#Fortran
Fortran
C ------------------------------------------------------------------ PROGRAM BIORHYTHM C ------------------------------------------------------------------ DOUBLE PRECISION GETJD CHARACTER*3 DOW   DOUBLE PRECISION JD0, JD1, JD2, PI2, DIF   INTEGER BYEAR, BMON, BDAY, TYEAR, TMON, TD...