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
| #LabVIEW | LabVIEW |
{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
| #Lambdatalk | Lambdatalk |
{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... | #zonnon | zonnon |
module Caesar;
const
size = 25;
type
Operation = (code,decode);
procedure C_D(s:string;k:integer;op: Operation): string;
var
i,key: integer;
resp: string;
n,c: char;
begin
resp := "";
if op = Operation.decode then key := k else key := (26 - k) end;
for i := 0 to len(s) - 1 do
c := cap(s[i]);
if (c >= ... |
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... | #Huginn | Huginn | import Algorithms as algo;
import Text as text;
class Compass {
_majors = none;
_quarter1 = none;
_quarter2 = none;
constructor() {
_majors = algo.materialize( text.split( "north east south west", " " ), tuple );
_majors += _majors;
_quarter1 = text.split( "N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E ... |
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.23 | C# | static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Console.WriteLine("a or b is {0}", a | b);
Console.WriteLine("a xor b is {0}", a ^ b);
Console.WriteLine("not a is {0}", ~a);
Console.WriteLine("a lshift b is {0}", a << 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.2B.2B | C++ | #include <iostream>
#include <boost/gil/gil_all.hpp>
int main()
{
using namespace boost::gil;
// create 30x40 image
rgb8_image_t img(30, 40);
// fill with red
rgb8_pixel_t red(255, 0, 0);
fill_pixels(view(img), red);
// set pixel at 10x20 to blue
rgb8_pixel_t blue(0, 0, 255);
vie... |
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).
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Bezier(P0, P1, P2, P3); \Draw cubic Bezier curve
real P0, P1, P2, P3;
def Segments = 8;
int I;
real S1, T, T2, T3, U, U2, U3, B, C, X, Y;
[Move(fix(P0(0)), fix(P0(1)));
S1:= 1./float(Segments);
T:= 0.;
for I:= 1 to Segments-1 do
[T:= T+S... |
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).
| #zkl | zkl | fcn cBezier(p0x,p0y, p1x,p1y, p2x,p2y, p3x,p3y, rgb, numPts=500){
numPts.pump(Void,'wrap(t){ // B(t)
t=t.toFloat()/numPts; t1:=(1.0 - t);
a:=t1*t1*t1; b:=t*t1*t1*3; c:=t1*t*t*3; d:=t*t*t;
x:=a*p0x + b*p1x + c*p2x + d*p3x + 0.5;
y:=a*p0y + b*p1y + c*p2y + d*p3y + 0.5;
__sSet(rgb,x,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... | #VBA | VBA | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
'Jagged Array
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 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... | #Vlang | Vlang | import time
import math
const cycles = ["Physical day ", "Emotional day", "Mental day "]
const lengths = [23, 28, 33]
const quadrants = [
["up and rising", "peak"],
["up but falling", "transition"],
["down and falling", "valley"],
["down but rising", "transition"],
]
// Parameters assumed to be in... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #11l | 11l | F bellTriangle(n)
[[BigInt]] tri
L(i) 0 .< n
tri.append([BigInt(0)] * i)
tri[1][0] = 1
L(i) 2 .< n
tri[i][0] = tri[i - 1][i - 2]
L(j) 1 .< i
tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]
R tri
V bt = bellTriangle(51)
print(‘First fifteen and fiftieth Bell numbers:’)
L(i) 1..1... |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
# string creation
a="123\0 abc ";
b="456\x09";
c="789";
printf("abc=<%s><%s><%s>\n",a,b,c);
# string comparison
printf("(a==b) is %i\n",a==b)
# string copying
A = a;
B = b;
C = c;
printf("ABC=<%s><%s><%s>\n",A,B,C);
# check if string is empty
if (length(a)==0) {
printf... |
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]
... | #C | C | #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {... |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #Go | Go | 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
... | #11l | 11l | L(n) [0, 5, 50, 9000]
print(‘#4 = #.’.format(n, bin(n))) |
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.
| #Common_Lisp | Common Lisp | (defun draw-line (buffer x1 y1 x2 y2 pixel)
(declare (type rgb-pixel-buffer buffer))
(declare (type integer x1 y1 x2 y2))
(declare (type rgb-pixel pixel))
(let* ((dist-x (abs (- x1 x2)))
(dist-y (abs (- y1 y2)))
(steep (> dist-y dist-x)))
(when steep
(psetf x1 y1 y1 x1
x... |
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... | #Phix | Phix | string dna = repeat(' ',200+rand(300))
for i=1 to length(dna) do dna[i] = "ACGT"[rand(4)] end for
procedure show()
sequence acgt = repeat(0,5)
for i=1 to length(dna) do
acgt[find(dna[i],"ACGT")] += 1
end for
acgt[$] = sum(acgt)
sequence s = split(trim(join_by(split(join_by(dna,1,10,""),"\n... |
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... | #Python | Python | from hashlib import sha256
digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def decode_base58(bc, length):
n = 0
for char in bc:
n = n * 58 + digits58.index(char)
return n.to_bytes(length, 'big')
def check_bc(bc):
try:
bcbytes = decode_base58(bc, 25)
re... |
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... | #Racket | Racket |
#lang racket/base
;; Same sha-256 interface as the same-named task
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto)
(define-ffi-definer defcrypto libcrypto)
(defcrypto SHA256_Init (_fun _pointer -> _int))
(defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int))
(defcrypto SHA256_Final (_fun _poin... |
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... | #Perl | Perl | #! /usr/bin/perl
use strict;
use Image::Imlib2;
my $img = Image::Imlib2->load("Unfilledcirc.jpg");
$img->set_color(0, 255, 0, 255);
$img->fill(100,100);
$img->save("filledcirc.jpg");
exit 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... | #Phix | Phix | -- demo\rosetta\Bitmap_FloodFill.exw (runnable version)
include ppm.e -- blue, green, read_ppm(), write_ppm() (covers above requirements)
function ff(sequence img, integer x, y, colour, target)
if x>=1 and x<=length(img)
and y>=1 and y<=length(img[x])
and img[x][y]=target then
img[x][y] = colour... |
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
| #Lasso | Lasso | !true
// => false
not false
// => true
var(x = true)
$x // => true
$x = false
$x // => 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
| #Latitude | Latitude |
> 'true
true
> 'false
false
> (or 'false 'false)
false
> (or 'false 'true)
true
|
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
20 PRINT t$''
30 LET key=RND*25+1
40 LET k=key: GO SUB 1000: PRINT t$''
50 LET k=26-key: GO SUB 1000: PRINT t$
60 STOP
1000 FOR i=1 TO LEN t$
1010 LET c= CODE t$(i)
1020 IF c<65 OR c>90 THEN GO TO 1050
1030 LET c=c+k: IF c>90 THEN LET c=c-90+64
1040 LET t$(i)=CHR$ c
... |
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... | #Icon_and_Unicon | Icon and Unicon | link strings,numbers
procedure main()
every heading := 11.25 * (i := 0 to 32) do {
case i%3 of {
1: heading +:= 5.62
2: heading -:= 5.62
}
write(right(i+1,3)," ",left(direction(heading),20)," ",fix(heading,,7,2))
}
end
procedure direction(d) # compass heading given +/- degrees
static... |
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.2B.2B | C++ | #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than <<
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
//... |
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... | #Clojure | Clojure | (import '[java.awt Color Graphics Image]
'[java.awt.image BufferedImage])
(defn blank-bitmap [width height]
(BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR))
(defn fill [image color]
(doto (.getGraphics image)
(.setColor color)
(.fillRect 0 0 (.getWidth image) (.getHeight image))))
(defn 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... | #Wren | Wren | import "/date" for Date
import "/fmt" for Fmt
var cycles = ["Physical day ", "Emotional day", "Mental day "]
var lengths = [23, 28, 33]
var quadrants = [
["up and rising", "peak"],
["up but falling", "transition"],
["down and falling", "valley"],
["down but rising", "transition"]
]
var bior... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Bell_Triangle is array(Positive range <>, Positive range <>) of Natural;
procedure Print_Rows (Row : in Positive; Triangle : in Bell_Triangle) is
begin
if Row in Triangle'Range(1) then
for I in Triangle'First(1) .. Row loop
Put_Line (Triang... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #11l | 11l | F get_fibs()
V a = 1.0
V b = 1.0
[Float] r
L 1000
r [+]= a
(a, b) = (b, a + b)
R r
F benford(seq)
V freqs = [(0.0, 0.0)] * 9
V seq_len = 0
L(d) seq
I d != 0
freqs[String(d)[0].code - ‘1’.code][1]++
seq_len++
L(&f) freqs
f = (log10(1.0 + 1.0 / (L.i... |
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... | #BASIC | BASIC | REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM)
A$ = "STRING" : REM CREATION
A$ = "" : REM DESTRUCTION
PRINT FRE(0) : REM GARBAGE COLLECTION
REM STRING ASSIGNMENT
A$ = "STRING" : R$ = "DEUX"
REM STRING COMPARISON
PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > 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... | #BBC_BASIC | BBC BASIC | A$ = CHR$(0) + CHR$(1) + CHR$(254) + CHR$(255) : REM assignment
B$ = A$ : REM clone / copy
IF A$ = B$ THEN PRINT "Strings are equal" : REM comparison
IF A$ = "" THEN PRINT "String is empty" : REM Check if empty
A$ += CHR$(128) ... |
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]
... | #C.2B.2B | C++ | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(lim... |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #Haskell | Haskell | import Data.List (group, sort)
import Data.List.Split (chunksOf)
import Text.Printf (printf, IsChar(..), PrintfArg(..), fmtChar, fmtPrecision, formatString)
data DNABase = A | C | G | T deriving (Show, Read, Eq, Ord)
type DNASequence = [DNABase]
instance IsChar DNABase where
toChar = head . show
fromC... |
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
... | #360_Assembly | 360 Assembly | * Binary digits 27/08/2015
BINARY CSECT
USING BINARY,R12
LR R12,R15 set base register
BEGIN LA R10,4
LA R9,N
LOOPN MVC W,0(R9)
MVI FLAG,X'00'
LA R8,32
LA R2,CBIN
LOOP TM W,B'10000000' test... |
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.
| #D | D | module bitmap_bresenhams_line_algorithm;
import std.algorithm, std.math, bitmap;
void drawLine(Color)(Image!Color img,
size_t x1, size_t y1,
in size_t x2, in size_t y2,
in Color color)
pure nothrow @nogc {
immutable int dx = x2 - x1;
immut... |
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... | #PureBasic | PureBasic | #BASE$="ACGT"
#SEQLEN=200
#PROTOCOL=#True
Global dna.s
Define i.i
Procedure pprint()
Define p.i, cnt.i, sum.i
For p=1 To Len(dna) Step 50
Print(RSet(Str(p-1)+": ",5))
PrintN(Mid(dna,p,50))
Next
PrintN("Base counts:")
For p=1 To 4
cnt=CountString(dna,Mid(#BASE$,p,1)) : sum+cnt
Print(Mid... |
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... | #Raku | Raku | sub sha256(blob8 $b) returns blob8 {
given run <openssl dgst -sha256 -binary>, :in, :out, :bin {
.in.write: $b;
.in.close;
return .out.slurp;
}
}
my $bitcoin-address = rx/
<< <+alnum-[0IOl]> ** 26..* >> # an address is at least 26 characters long
<?{
.subbuf(21, 4) eq sha256(sha256 .s... |
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... | #PicoLisp | PicoLisp | (de ppmFloodFill (Ppm X Y Color)
(let Target (get Ppm Y X)
(recur (X Y)
(when (= Target (get Ppm Y X))
(set (nth Ppm Y X) Color)
(recurse (dec X) Y)
(recurse (inc X) Y)
(recurse X (dec Y))
(recurse X (inc Y)) ) ) )
Ppm ) |
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... | #PL.2FI | PL/I | fill: procedure (x, y, fill_color) recursive; /* 12 May 2010 */
declare (x, y) fixed binary;
declare fill_color bit (24) aligned;
if x <= lbound(image, 2) | x >= hbound(image, 2) then return;
if y <= lbound(image, 1) | y >= hbound(image, 1) then return;
pixel_color = image (x,y); /* Obtain the color ... |
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
| #LFE | LFE |
> 'true
true
> 'false
false
> (or 'false 'false)
false
> (or 'false 'true)
true
|
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
| #Lingo | Lingo | put TRUE
-- 1
put FALSE
-- 0
if 23 then put "Hello"
-- "Hello" |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Compass.bas"
110 STRING DR$(1 TO 33)*18
120 FOR I=1 TO 33
130 READ DR$(I)
140 NEXT
150 DO
160 READ IF MISSING EXIT DO:D
170 LET DIR=COMP(D)
180 PRINT D;TAB(12);DIR,DR$(DIR)
190 LOOP
200 DEF COMP(D)=CEIL(MOD((D+360/64),360)*32/360)
210 DATA North,North by east,North-northeast,Northeast by north,N... |
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 |... | #Clojure | Clojure | (bit-and x y)
(bit-or x y)
(bit-xor x y)
(bit-not x)
(bit-shift-left x n)
(bit-shift-right x n)
;;There is no built-in for rotation. |
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... | #Common_Lisp | Common Lisp | (defpackage #:rgb-pixel-buffer
(:use #:common-lisp)
(:export #:rgb-pixel-component #:rgb-pixel #:rgb-pixel-buffer
#:+red+ #:+green+ #:+blue+ #:+black+ #:+white+
#:make-rgb-pixel #:make-rgb-pixel-buffer #:rgb-pixel-buffer-width
#:rgb-pixel-buffer-height #:rgb-pixel-red #:rgb-pixel-gr... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #ALGOL_68 | ALGOL 68 | BEGIN # show some Bell numbers #
PROC show bell = ( INT n, LONG LONG INT bell number )VOID:
print( ( whole( n, -2 ), ": ", whole( bell number, 0 ), newline ) );
INT max bell = 50;
[ 0 : max bell - 2 ]LONG LONG INT a; FOR i TO UPB a DO a[ i ] := 0 OD;
a[ 0 ] := 1;
show bell( 1, a[ 0 ] );
... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #8th | 8th |
: n:log10e ` 1 10 ln / ` ;
with: n
: n:log10 \ n -- n
ln log10e * ;
: benford \ x -- x
1 swap / 1+ log10 ;
: fibs \ xt n
swap >r
0.0 1.0 rot
( dup r@ w:exec tuck + ) swap times
2drop rdrop ;
var counts
: init
a:new ( 0 a:push ) 9 times counts ! ;
: leading \ n -- n
"%g... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
procedure Benford is
subtype Nonzero_Digit is Natural range 1 .. 9;
function First_Digit(S: String) return Nonzero_Digit is
(if S(S'First) in '1' .. '9'
then Nonzero_Digit'Value(S(S'First .. S'First))
else First_Digit(S(S'F... |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #11l | 11l | F binary_search(l, value)
V low = 0
V high = l.len - 1
L low <= high
V mid = (low + high) I/ 2
I l[mid] > value
high = mid - 1
E I l[mid] < value
low = mid + 1
E
R mid
R -1 |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #11l | 11l | F count(w1, wnew)
R sum(zip(w1, wnew).map((c1, c2) -> Int(c1 == c2)))
F best_shuffle(w)
V wnew = Array(w)
V n = w.len
V rangei = Array(0 .< n)
V rangej = Array(0 .< n)
random:shuffle(&rangei)
random:shuffle(&rangej)
L(i) rangei
L(j) rangej
I i != j & wnew[j] != wnew[i] & w[i] !=... |
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... | #BQN | BQN | name ← "" |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct str_t {
size_t len, alloc;
unsigned char *s;
} bstr_t, *bstr;
#define str_len(s) ((s)->len)
bstr str_new(size_t len)
{
bstr s = malloc(sizeof(bstr_t));
if (len < 8) len = 8;
s->alloc = len;
s->s = malloc(len);
s->len = 0;
return s;
}
... |
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]
... | #C.23 | C# | using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.W... |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #J | J | countBases=: (({.;#)/.~)@,
totalBases=: #@,
require 'format/printf'
printSequence=: verb define
'Sequence:' printf ''
'%4d: %s' printf ((- {.)@(+/\)@:(#"1) ,.&<"_1 ]) y
'\n Base Count\n-----------' printf ''
'%5s: %4d' printf countBases y
'-----------\nTotal = %3d' printf totalBases y
) |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #Java | Java | import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACG... |
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
... | #6502_Assembly | 6502 Assembly | tmpx -i dec2bin.s -o dec2bin.prg
|
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.
| #Delphi | Delphi |
procedure drawLine (bitmap : TBitmap; xStart, yStart, xEnd, yEnd : integer; color : TAlphaColor);
// Bresenham's Line Algorithm. Byte, March 1988, pp. 249-253.
// Modified from http://www.efg2.com/Lab/Library/Delphi/Graphics/Bresenham.txt and tested.
var
a, b : integer; // displacements in x and y
... |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o... | #Python | Python | import random
from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASE... |
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... | #Ruby | Ruby |
# Validate Bitcoin address
#
# Nigel_Galloway
# October 13th., 2014
require 'digest/sha2'
def convert g
i,e = '',[]
(0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'}
e.pack(i)
end
N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,... |
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... | #Processing | Processing | import java.awt.Point;
import java.util.Queue;
import java.util.LinkedList;
PImage img;
int tolerance;
color fill_color;
boolean allowed;
void setup() {
size(600, 400);
img = loadImage("image.png");
fill_color = color(250, 0, 0);
fill(0, 0, 100);
tolerance = 15;
image(img, 0, 0, width, height);
text... |
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
| #Little | Little | int a = 0;
int b = 1;
int c;
string str1 = "initialized string";
string str2; // "uninitialized string";
if (a) {puts("first test a is false");} // This should not print
if (b) {puts("second test b is true");} // This should print
if (c) {puts("third test b is false");} // This should not pri... |
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
| #LiveCode | LiveCode | print 1 < 0 ; false
print 1 > 0 ; true
if "true [print "yes] ; yes
if not "false [print "no] ; no |
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... | #J | J | require'strings'
subs=: 'N,north,S,south,E,east,W,west,b, by ,'
dirs=: subs (toupper@{., }.)@rplc~L:1 0&(<;._2) 0 :0 -. ' ',LF
N,NbE,N-NE,NEbN,NE,NEbE,E-NE,EbN,E,EbS,E-SE,SEbE,SE,SEbS,S-SE,SbE,
S,SbW,S-SW,SWbS,SW,SWbW,W-SW,WbS,W,WbN,W-NW,NWbW,NW,NWbN,N-NW,NbW,
)
indice=: 32 | 0.5 <.@+ %&11.25
deg2pnt=: dirs {~ indi... |
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 |... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 a PIC 1(32) USAGE BIT.
01 b PIC 1(32) USAGE BIT.
01 result PIC 1(32) USAGE BIT.
01 result-disp ... |
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... | #Crystal | Crystal |
class RGBColor
getter red, green, blue
def initialize(@red = 0_u8, @green = 0_u8, @blue = 0_u8)
end
RED = new(red: 255_u8)
GREEN = new(green: 255_u8)
BLUE = new(blue: 255_u8)
BLACK = new
WHITE = new(255_u8, 255_u8, 255_u8)
end
class Pixmap
getter width, height
@data : Array(Array(RGBColor... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #ALGOL-M | ALGOL-M | begin
integer function index(row, col);
integer row, col;
index := row * (row-1)/ 2 + col;
integer ROWS; ROWS := 15;
begin
decimal(11) array bell[0:ROWS*(ROWS+1)/2];
integer i, j;
bell[index(1, 0)] := 1.;
for i := 2 step 1 until ROWS do
begin
bell[index(i, 0)] := bell[index(i-1, i-2)];
... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #APL | APL | bell←{
tr←↑(⊢,(⊂⊃∘⌽+0,+\)∘⊃∘⌽)⍣14⊢,⊂,1
⎕←'First 15 Bell numbers:'
⎕←tr[;1]
⎕←'First 10 rows of Bell''s triangle:'
⎕←tr[⍳10;⍳10]
} |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #Aime | Aime | text
sum(text a, text b)
{
data d;
integer e, f, n, r;
e = ~a;
f = ~b;
r = 0;
n = min(e, f);
while (n) {
n -= 1;
e -= 1;
f -= 1;
r += a[e] - '0';
r += b[f] - '0';
b_insert(d, 0, r % 10 + '0');
r /= 10;
}
if (f) {
... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #ALGOL_68 | ALGOL 68 | BEGIN
# set the number of digits for LONG LONG INT values #
PR precision 256 PR
# returns the probability of the first digit of each non-zero number in s #
PROC digit probability = ( []LONG LONG INT s )[]REAL:
BEGIN
[ 1 : 9 ]REAL result;
# count the number of times each ... |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #360_Assembly | 360 Assembly | * Binary search 05/03/2017
BINSEAR CSECT
USING BINSEAR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST... |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #Action.21 | Action! | PROC BestShuffle(CHAR ARRAY orig,res)
BYTE i,j,len
CHAR tmp
len=orig(0)
SCopy(res,orig)
FOR i=1 TO len
DO
FOR j=1 TO len
DO
IF i#j AND orig(i)#res(j) AND orig(j)#res(i) THEN
tmp=res(i) res(i)=res(j) res(j)=tmp
FI
OD
OD
RETURN
PROC Test(CHAR ARRAY orig)
CHAR ARRAY res(... |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #Ada | Ada | with Ada.Text_IO;
with Ada.Strings.Unbounded;
procedure Best_Shuffle is
function Best_Shuffle (S : String) return String;
function Best_Shuffle (S : String) return String is
T : String (S'Range) := S;
Tmp : Character;
begin
for I in S'Range loop
for J in S'Range loop
... |
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... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
using namespace std;
string replaceFirst(string &s, const string &target, const string &replace) {
auto pos = s.find(target);
if (pos == string::npos) return s;
return s.replace(pos, target.length(), replace);
}
int main() {
// string creation
string x ... |
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]
... | #CLU | CLU | % Bin the given data, return an array of counts.
% CLU allows arrays to start at any index; the result array
% will have the same lower bound as the limit array.
% The datatype for the limits and data may be any type
% that allows the < comparator.
bin_count = proc [T: type] (limits, data: array[T]) returns (array[in... |
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]
... | #Factor | Factor | USING: assocs formatting grouping io kernel math math.parser
math.statistics sequences sequences.extras sorting.extras ;
: bin ( data limits -- seq )
dup length 1 + [ 0 ] replicate -rot
[ bisect-right over [ 1 + ] change-nth ] curry each ;
: .bin ( {lo,hi} n i -- )
swap "%3d members in " printf zero? "(... |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #JavaScript | JavaScript | const rowLength = 50;
const bases = ['A', 'C', 'G', 'T'];
// Create the starting sequence
const seq = `CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGC... |
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
... | #8080_Assembly | 8080 Assembly | bdos: equ 5h ; CP/M system call
puts: equ 9h ; Print string
org 100h
lxi h,5 ; Print value for 5
call prbin
lxi h,50 ; Print value for 50
call prbin
lxi h,9000 ; Print value for 9000
prbin: call bindgt ; Make binary representation of HL
mvi c,puts ; Print it
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;... |
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.
| #E | E | def swap(&left, &right) { # From [[Generic swap]]
def t := left
left := right
right := t
}
def drawLine(image, var x0, var y0, var x1, var y1, color) {
def steep := (y1 - y0).abs() > (x1 - x0).abs()
if (steep) {
swap(&x0, &y0)
swap(&x1, &y1)
}
if (x0 > x1) {
swap(&x0, &x1... |
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... | #Quackery | Quackery | [ $ "ACGT" 4 random peek ] is randomgene ( --> c )
[ $ "" swap times
[ randomgene join ] ] is randomsequence ( n --> $ )
[ dup size random
3 random
[ table
[ pluck drop ]
[ randomgene unrot stuff ]
[ randomgene unrot poke ] ]
do ] ... |
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... | #Rust | Rust |
extern crate crypto;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
const DIGITS58: [char; 58] = ['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',... |
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... | #Scala | Scala | import java.security.MessageDigest
import java.util.Arrays.copyOfRange
import scala.annotation.tailrec
import scala.math.BigInt
object BitcoinAddressValidator extends App {
private def bitcoinTestHarness(address: String, expected: Boolean): Unit =
assert(validateBitcoinAddress(=1J26TeMg6uK9GkoCKkHNeDaKwtFWd... |
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... | #PureBasic | PureBasic | FillArea(0,0,-1,$ff)
; Fills an Area in red |
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... | #Python | Python |
import Image
def FloodFill( fileName, initNode, targetColor, replaceColor ):
img = Image.open( fileName )
pix = img.load()
xsize, ysize = img.size
Q = []
if pix[ initNode[0], initNode[1] ] != targetColor:
return img
Q.append( initNode )
while Q != []:
node = Q.pop(0)
if pix[ nod... |
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
| #Logo | Logo | print 1 < 0 ; false
print 1 > 0 ; true
if "true [print "yes] ; yes
if not "false [print "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
| #Lua | Lua | if 0 then print "0" end -- This prints
if "" then print"empty string" end -- This prints
if {} then print"empty table" end -- This prints
if nil then print"this won't print" end
if true then print"true" end
if false then print"false" end -- This does not print |
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... | #Java | Java | public class BoxingTheCompass{
private static String[] points = new String[32];
public static void main(String[] args){
buildPoints();
double heading = 0;
for(int i = 0; i<= 32;i++){
heading = i * 11.25;
switch(i % 3){
case 1:
... |
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 |... | #CoffeeScript | CoffeeScript |
f = (a, b) ->
p "and", a & b
p "or", a | b
p "xor", a ^ b
p "not", ~a
p "<<", a << b
p ">>", a >> b
# no rotation shifts that I know of
p = (label, n) -> console.log label, n
f(10,2)
|
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... | #D | D | module bitmap;
import std.stdio, std.array, std.exception, std.string, std.conv,
std.algorithm, std.ascii;
final class Image(T) {
static if (is(typeof({ auto x = T.black; })))
const static T black = T.black;
else
const static T black = T.init;
static if (is(typeof({ auto x = T.whi... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #Arturo | Arturo | bellTriangle: function[n][
tri: map 0..n-1 'x [ map 0..n 'y -> 0 ]
set get tri 1 0 1
loop 2..n-1 'i [
set get tri i 0 get (get tri i-1) i-2
loop 1..i-1 'j [
set get tri i j (get (get tri i) j-1) + ( get (get tri i-1) j-1)
]
]
return tri
]
bt: bellTriangle 51
lo... |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a... | #AutoHotkey | AutoHotkey | ;-----------------------------------
Bell_triangle(maxRows){
row := 1, col := 1, Arr := []
Arr[row, col] := 1
while (Arr.Count() < maxRows){
row++
max := Arr[row-1].Count()
Loop % max{
if (col := A_Index) =1
Arr[row, col] := Arr[row-1, max]
Arr[row, col+1] := Arr[row, col] + Arr[row-1, col]
}
}
r... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #AutoHotkey | AutoHotkey | SetBatchLines, -1
fib := NStepSequence(1, 1, 2, 1000)
Out := "Digit`tExpected`tObserved`tDeviation`n"
n := []
for k, v in fib
d := SubStr(v, 1, 1)
, n[d] := n[d] ? n[d] + 1 : 1
for k, v in n
Exppected := 100 * Log(1+ (1 / k))
, Observed := (v / fib.MaxIndex()) * 100
, Out .= k "`t" Exppected "`t" Observed "`t" Abs... |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of S... | #Ada | Ada | WITH GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;
USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;
PROCEDURE Main IS
FUNCTION Bernoulli_Number (N : Natural) RETURN Unbounded_Fraction IS
FUNCTION "/" (Left, Right : Natural) RETURN Unbounded_Fra... |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #8080_Assembly | 8080 Assembly | org 100h ; Entry for test code
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary search in array of unsigned 8-bit integers
;; B = value to look for
;; HL = begin of array (low)
;; DE = end of array, inclusive (high)
;; The entry point is 'binsrch'
;; On return, HL = location... |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #ALGOL_68 | ALGOL 68 | BEGIN # shuffle a string so as many as possible characters are moved #
PROC best shuffle = ( STRING orig )STRING:
BEGIN
STRING res := orig;
FOR i FROM LWB orig TO UPB orig DO
FOR j FROM LWB orig TO UPB orig DO
IF i /= j AND orig[ i ] /= res[ j ] AND orig[ j ] /= res[ ... |
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... | #C.23 | C# | using System;
class Program
{
static void Main()
{
//string creation
var x = "hello world";
//# mark string for garbage collection
x = null;
//# string assignment with a null byte
x = "ab\0";
Console.WriteLine(x);
Console.WriteLine(x.Length);... |
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]
... | #FreeBASIC | FreeBASIC | sub binlims( dat() as integer, limits() as integer, bins() as uinteger )
dim as uinteger n = ubound(limits), j, i
for i = 0 to ubound(dat)
if dat(i)<limits(0) then
bins(0) += 1
elseif dat(i) >= limits(n) then
bins(n+1) += 1
else
for j = 1 to n
... |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #jq | jq | def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
# Create a bag of words, i.e. a JSON object with counts of the items in the stream
def bow(stream):
reduce stream as $word ({}; .[($word|tostring)] += 1); |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #Julia | Julia | const sequence =
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" *
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" *
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" *
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" *
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" *
"TCAGTCCCAATGTGCGGGGTTTCTTT... |
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
... | #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data
TestData0 byte 5,255 ;255 is the terminator
TestData1 byte 5,0,255
TestData2 byte 9,0,0,0,255
.code
start:
mov ax,@data
mov ds,ax
cld ;String functions are set to auto-increment
mov ax,2 ;clear screen by setting video mode to 0
in... |
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.
| #Elm | Elm |
-- Brensenham Line Algorithm
type alias Position =
{x: Int, y: Int}
type alias BresenhamStatics =
{ finish : Position
, sx : Int
, sy : Int
, dx : Float
, dy : Float
}
line : Position -> Position -> List Position
line p q =
let
dx = (toFloat << abs) (q.x - p.x)
dy = (toFloat << ... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.