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/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Racket | Racket | #lang racket
(define current-S-weight (make-parameter 1))
(define current-D-weight (make-parameter 1))
(define current-I-weight (make-parameter 1))
(define bases '(#\A #\C #\G #\T))
(define (fold-sequence seq kons #:finalise (finalise (λ x (apply values x))) . k0s)
(define (recur seq . ks)
(if (null? seq)
(call-with-values (λ () (apply finalise ks)) (λ vs (apply values vs)))
(call-with-values (λ () (apply kons (car seq) ks)) (λ ks+ (apply recur (cdr seq) ks+)))))
(apply recur (if (string? seq) (string->list (regexp-replace* #px"[^ACGT]" seq "")) seq) k0s))
(define (sequence->pretty-printed-string seq)
(define (fmt idx cs-rev) (format "~a: ~a" (~a idx #:width 3 #:align 'right) (list->string (reverse cs-rev))))
(fold-sequence
seq
(λ (b n start-idx lns-rev cs-rev)
(if (zero? (modulo n 50))
(values (+ n 1) n (if (pair? cs-rev) (cons (fmt start-idx cs-rev) lns-rev) lns-rev) (cons b null))
(values (+ n 1) start-idx lns-rev (cons b cs-rev))))
0 0 null null
#:finalise (λ (n idx lns-rev cs-rev)
(string-join (reverse (if (null? cs-rev) lns-rev (cons (fmt idx cs-rev) lns-rev))) "\n"))))
(define (count-bases b as cs gs ts n)
(values (+ as (if (eq? b #\A) 1 0)) (+ cs (if (eq? b #\C) 1 0)) (+ gs (if (eq? b #\T) 1 0)) (+ ts (if (eq? b #\G) 1 0)) (add1 n)))
(define (report-sequence s)
(define-values (as cs gs ts n) (fold-sequence s count-bases 0 0 0 0 0))
(printf "SEQUENCE:~%~a~%" (sequence->pretty-printed-string s))
(printf "BASE COUNT:~%-----------~%~a~%"
(string-join (map (λ (c n) (format " ~a :~a" c (~a #:width 4 #:align 'right n))) bases (list as ts cs gs)) "\n"))
(printf "TOTAL: ~a~%" n))
(define (make-random-sequence-string l)
(list->string (for/list ((_ l)) (list-ref bases (random 4)))))
(define (weighted-random-call weights-and-functions . args)
(let loop ((r (random)) (wfs weights-and-functions))
(if (<= r (car wfs)) (apply (cadr wfs) args) (loop (- r (car wfs)) (cddr wfs)))))
(define (mutate-S s)
(let ((r (random (string-length s))) (i (string (list-ref bases (random 4)))))
(printf "Mutate at ~a -> ~a~%" r i)
(string-append (substring s 0 r) i (substring s (add1 r)))))
(define (mutate-D s)
(let ((r (random (string-length s))))
(printf "Delete at ~a~%" r)
(string-append (substring s 0 r) (substring s (add1 r)))))
(define (mutate-I s)
(let ((r (random (string-length s))) (i (string (list-ref bases (random 4)))))
(printf "Insert at ~a -> ~a~%" r i)
(string-append (substring s 0 r) i (substring s r))))
(define (mutate s)
(define W (+ (current-S-weight) (current-D-weight) (current-I-weight)))
(weighted-random-call
(list (/ (current-S-weight) W) mutate-S (/ (current-D-weight) W) mutate-D (/ (current-I-weight) W) mutate-I)
s))
(module+
main
(define initial-sequence (make-random-sequence-string 200))
(report-sequence initial-sequence)
(newline)
(define s+ (for/fold ((s initial-sequence)) ((_ 10)) (mutate s)))
(newline)
(report-sequence s+)
(newline)
(define s+d (parameterize ((current-D-weight 5)) (for/fold ((s initial-sequence)) ((_ 10)) (mutate s))))
(newline)
(report-sequence s+d)) |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Raku | Raku | my @bases = <A C G T>;
# The DNA strand
my $dna = @bases.roll(200).join;
# The Task
put "ORIGINAL DNA STRAND:";
put pretty $dna;
put "\nTotal bases: ", +my $bases = $dna.comb.Bag;
put $bases.sort( ~*.key ).join: "\n";
put "\nMUTATED DNA STRAND:";
my $mutate = $dna.&mutate(10);
put pretty diff $dna, $mutate;
put "\nTotal bases: ", +my $mutated = $mutate.comb.Bag;
put $mutated.sort( ~*.key ).join: "\n";
# Helper subs
sub pretty ($string, $wrap = 50) {
$string.comb($wrap).map( { sprintf "%8d: %s", $++ * $wrap, $_ } ).join: "\n"
}
sub mutate ($dna is copy, $count = 1) {
$dna.substr-rw((^$dna.chars).roll, 1) = @bases.roll for ^$count;
$dna
}
sub diff ($orig, $repl) {
($orig.comb Z $repl.comb).map( -> ($o, $r) { $o eq $r ?? $o !! $r.lc }).join
} |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "msgdigest.s7i";
include "encoding.s7i";
const func boolean: validBitcoinAddress (in string: address) is func
result
var boolean: isValid is FALSE;
local
var string: decoded is "";
begin
if succeeds(decoded := fromBase58(address)) and
length(decoded) = 25 and decoded[1] = '\0;' and
sha256(sha256(decoded[.. 21]))[.. 4] = decoded[22 ..] then
isValid := TRUE;
end if;
end func;
const proc: checkValidationFunction (in string: address, in boolean: expected) is func
local
var boolean: isValid is FALSE;
begin
isValid := validBitcoinAddress(address);
writeln((address <& ": ") rpad 37 <& isValid);
if isValid <> expected then
writeln(" *** Expected " <& expected <& " for " <& address <& ", but got " <& isValid <& ".");
end if;
end func;
const proc: main is func
begin
checkValidationFunction("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", TRUE); # okay
checkValidationFunction("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", FALSE); # bad digest
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", TRUE); # okay
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", FALSE); # bad digest
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", FALSE); # bad digest
checkValidationFunction("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", FALSE); # bad digest
checkValidationFunction("oMRDCDfyQhEerkaSmwCfSPqf3MLgBwNvs", FALSE); # not version 0
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", FALSE); # wrong length
checkValidationFunction("1BGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", FALSE); # bad digest
checkValidationFunction("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", FALSE); # bad char
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", FALSE); # bad char
checkValidationFunction("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", FALSE); # bad char
checkValidationFunction("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i", FALSE); # bad digest
checkValidationFunction("1111111111111111111114oLvT2", TRUE); # okay
checkValidationFunction("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j", TRUE); # okay
checkValidationFunction("1badbadbadbadbadbadbadbadbadbadbad", FALSE); # wrong length
checkValidationFunction("BZbvjr", FALSE); # wrong length
checkValidationFunction("i55j", FALSE); # wrong length
checkValidationFunction("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", TRUE); # okay
end func; |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #Tcl | Tcl | package require sha256
# Generate a large and boring piece of code to do the decoding of
# base58-encoded data.
apply {{} {
set chars "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
set i -1
foreach c [split $chars ""] {
lappend map $c "return -level 0 [incr i]"
}
lappend map default {return -code error "bad character \"$c\""}
proc base58decode str [string map [list @BODY@ [list $map]] {
set num 0
set count [expr {ceil(log(58**[string length $str])/log(256))}]
foreach c [split $str {}] {
set num [expr {$num*58+[switch $c @BODY@]}]
}
for {set i 0} {$i < $count} {incr i} {
append result [binary format c [expr {$num & 255}]]
set num [expr {$num >> 8}]
}
return [string reverse $result]
}]
}}
# How to check bitcoin address validity
proc bitcoin_addressValid {address} {
set a [base58decode $address]
set ck [sha2::sha256 -bin [sha2::sha256 -bin [string range $a 0 end-4]]]
if {[string range $a end-3 end] ne [string range $ck 0 3]} {
return -code error "signature does not match"
}
return "$address is ok"
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #R | R |
library(png)
img <- readPNG("Unfilledcirc.png")
M <- img[ , , 1]
M <- ifelse(M < 0.5, 0, 1)
image(M, col = c(1, 0))
# https://en.wikipedia.org/wiki/Flood_fill
floodfill <- function(row, col, tcol, rcol) {
if (tcol == rcol) return()
if (M[row, col] != tcol) return()
M[row, col] <<- rcol
floodfill(row - 1, col , tcol, rcol) # south
floodfill(row + 1, col , tcol, rcol) # north
floodfill(row , col - 1, tcol, rcol) # west
floodfill(row , col + 1, tcol, rcol) # east
return("filling completed")
}
options(expressions = 10000)
startrow <- 100; startcol <- 100
floodfill(startrow, startcol, 0, 2)
image(M, col = c(1, 0, 2))
|
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Racket | Racket |
#lang racket
(require racket/draw)
;; flood-fill: bitmap<%> number number color color -> void
;; An example of flood filling a bitmap.
;;
;; We'll use a raw, byte-oriented interface here for demonstration
;; purposes. Racket does provide get-pixel and set-pixel functions
;; which work on color% structures rather than bytes, but it's useful
;; to see that the byte approach works as well.
(define (flood-fill bm start-x start-y target-color replacement-color)
;; The main loop.
;; http://en.wikipedia.org/wiki/Flood_fill
(define (iter x y)
(when (and (in-bounds? x y) (target-color-at? x y))
(replace-color-at! x y)
(iter (add1 x) y)
(iter (sub1 x) y)
(iter x (add1 y))
(iter x (sub1 y))))
;; With auxillary definitions below:
(define width (send bm get-width))
(define height (send bm get-height))
(define buffer (make-bytes (* width height 4)))
(send bm get-argb-pixels 0 0 width height buffer)
(define-values (target-red target-green target-blue)
(values (send target-color red)
(send target-color green)
(send target-color blue)))
(define-values (replacement-red replacement-green replacement-blue)
(values (send replacement-color red)
(send replacement-color green)
(send replacement-color blue)))
(define (offset-at x y) (* 4 (+ (* y width) x)))
(define (target-color-at? x y)
(define offset (offset-at x y))
(and (= (bytes-ref buffer (+ offset 1)) target-red)
(= (bytes-ref buffer (+ offset 2)) target-green)
(= (bytes-ref buffer (+ offset 3)) target-blue)))
(define (replace-color-at! x y)
(define offset (offset-at x y))
(bytes-set! buffer (+ offset 1) replacement-red)
(bytes-set! buffer (+ offset 2) replacement-green)
(bytes-set! buffer (+ offset 3) replacement-blue))
(define (in-bounds? x y)
(and (<= 0 x) (< x width) (<= 0 y) (< y height)))
;; Finally, let's do the fill, and then store the
;; result back into the bitmap:
(iter start-x start-y)
(send bm set-argb-pixels 0 0 width height buffer))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Example: flood fill a hole shape.
(define bm (make-bitmap 100 100))
(define dc (send bm make-dc))
;; We intentionally set the smoothing of the dc to
;; aligned so that there are no gaps in the shape for the
;; flood to leak through.
(send dc set-smoothing 'aligned)
(send dc draw-rectangle 10 10 80 80)
(send dc draw-rounded-rectangle 20 20 50 50)
;; In DrRacket, we can print the bm to look at it graphically,
;; before the flood fill:
bm
(flood-fill bm 50 50
(send the-color-database find-color "white")
(send the-color-database find-color "DarkSeaGreen"))
;; ... and after:
bm
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckBoolean {
A=True
Print Type$(A)="Double"
B=1=1
Print Type$(B)="Boolean"
Print A=B ' true
Print A, B ' -1 True
Def boolean C=True, D=False
Print C, D , 1>-3 ' True False True
K$=Str$(C)
Print K$="True" ' True
Function ShowBoolean$(&x) {
x=false
Try {
if keypress(32) then x=true : exit
If Keypress(13) then exit
loop
}
=str$(x, locale)
}
Wait 100
Print "C (space for true, enter for false)="; : Print ShowBoolean$(&c)
Print C
}
CheckBoolean
Print str$(True, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"
Print str$(False, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="false"
Print str$(2, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="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
| #Maple | Maple | >> islogical(true)
ans =
1
>> islogical(false)
ans =
1
>> islogical(logical(1))
ans =
1
>> islogical(logical(0))
ans =
1
>> islogical(1)
ans =
0
>> islogical(0)
ans =
0 |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #JavaScript | JavaScript | function createRow(i, point, heading) {
var tr = document.createElement('tr'),
td;
td = document.createElement('td');
td.appendChild(document.createTextNode(i));
tr.appendChild(td);
td = document.createElement('td');
point = point.substr(0, 1).toUpperCase() + point.substr(1);
td.appendChild(document.createTextNode(point));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(heading));
tr.appendChild(td);
return tr;
}
function getPoint(i) {
var j = i % 8,
i = Math.floor(i / 8) % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[i];
str2 = cardinal[(i + 1) % 4];
strC = (str1 === 'north' || str1 === 'south') ? str1 + str2 : str2 + str1;
return pointDesc[j].replace('1', str1).replace('2', str2).replace('C', strC);
}
var i,
heading,
table = document.createElement('table'),
tbody = document.createElement('tbody'),
tr;
for (i = 0; i <= 32; i += 1) {
heading = i * 11.25 + [0, 5.62, -5.62][i % 3];
tr = createRow(i % 32 + 1, getPoint(i), heading + '°');
tbody.appendChild(tr);
}
table.appendChild(tbody);
document.body.appendChild(table);
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Common_Lisp | Common Lisp | (defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
(print (logxor a b)) ; XOR
(print (lognot a)) ; NOT
(print (ash a b)) ; arithmetic left shift (positive 2nd arg)
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg)
; no logical shift
) |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #Delphi | Delphi |
program BitmapTest;
{$APPTYPE CONSOLE}
type
TColor = record
private
function GetColor: Cardinal;
procedure SetColor(const Value: Cardinal);
public
Red, Green, Blue, Alpha: Byte;
property Color: Cardinal read GetColor write SetColor;
end;
TBitmap = class
private
FPixels: array of array of TColor;
FHeight: Integer;
FWidth: Integer;
function GetPixel(X, Y: integer): TColor;
public
procedure Fill(aColor: TColor); overload;
procedure Fill(aColor: Cardinal); overload;
procedure SetSize(w, h: Integer);
constructor Create(); overload;
constructor Create(w, h: Integer); overload;
property Height: Integer read FHeight;
property Width: Integer read FWidth;
property Pixel[X, Y: integer]: TColor read GetPixel;
end;
{ TColor }
function TColor.GetColor: Cardinal;
begin
Result := (alpha shl 24) + (red shl 16) + (green shl 8) + blue;
end;
procedure TColor.SetColor(const Value: Cardinal);
begin
blue := (Value and $FF);
green := ((Value shr 8) and $FF);
red := ((Value shr 16) and $FF);
alpha := ((Value shr 24) and $FF);
end;
{ TBitmap }
constructor TBitmap.Create;
begin
inherited;
FHeight := 0;
FWidth := 0;
end;
constructor TBitmap.Create(w, h: Integer);
begin
Create;
SetSize(w, h);
end;
procedure TBitmap.Fill(aColor: Cardinal);
var
x, y: Integer;
begin
if (Width > 0) and (Height > 0) then
for x := 0 to width - 1 do
for y := 0 to height - 1 do
FPixels[x, y].Color := aColor;
end;
procedure TBitmap.Fill(aColor: TColor);
begin
Fill(aColor.Color);
end;
function TBitmap.GetPixel(X, Y: integer): TColor;
begin
Result := FPixels[X, Y];
end;
procedure TBitmap.SetSize(w, h: Integer);
var
i: Integer;
begin
if (h = 0) or (w = 0) then
begin
h := 0;
w := 0;
end;
FHeight := h;
FWidth := w;
SetLength(FPixels, w);
if w > 0 then
for i := 0 to w - 1 do
SetLength(FPixels[i], h);
end;
var
bmp: TBitmap;
x, y: Integer;
begin
bmp := TBitmap.Create(200, 200);
bmp.Fill($00FF0000);
for y := 0 to bmp.Height - 1 do
for x := 0 to bmp.Width - 1 do
begin
if x mod 2 = 1 then
bmp.Pixel[x, y].Color := $0000FF;
end;
bmp.Free;
end. |
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #C | C | #include <stdio.h>
#include <stdlib.h>
// row starts with 1; col < row
size_t bellIndex(int row, int col) {
return row * (row - 1) / 2 + col;
}
int getBell(int *bellTri, int row, int col) {
size_t index = bellIndex(row, col);
return bellTri[index];
}
void setBell(int *bellTri, int row, int col, int value) {
size_t index = bellIndex(row, col);
bellTri[index] = value;
}
int *bellTriangle(int n) {
size_t length = n * (n + 1) / 2;
int *tri = calloc(length, sizeof(int));
int i, j;
setBell(tri, 1, 0, 1);
for (i = 2; i <= n; ++i) {
setBell(tri, i, 0, getBell(tri, i - 1, i - 2));
for (j = 1; j < i; ++j) {
int value = getBell(tri, i, j - 1) + getBell(tri, i - 1, j - 1);
setBell(tri, i, j, value);
}
}
return tri;
}
int main() {
const int rows = 15;
int *bt = bellTriangle(rows);
int i, j;
printf("First fifteen Bell numbers:\n");
for (i = 1; i <= rows; ++i) {
printf("%2d: %d\n", i, getBell(bt, i, 0));
}
printf("\nThe first ten rows of Bell's triangle:\n");
for (i = 1; i <= 10; ++i) {
printf("%d", getBell(bt, i, 0));
for (j = 1; j < i; ++j) {
printf(", %d", getBell(bt, i, j));
}
printf("\n");
}
free(bt);
return 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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #AWK | AWK |
# syntax: GAWK -f BENFORDS_LAW.AWK
BEGIN {
n = 1000
for (i=1; i<=n; i++) {
arr[substr(fibonacci(i),1,1)]++
}
print("digit expected observed deviation")
for (i=1; i<=9; i++) {
expected = log10(i+1) - log10(i)
actual = arr[i] / n
deviation = expected - actual
printf("%5d %8.4f %8.4f %9.4f\n",i,expected*100,actual*100,abs(deviation*100))
}
exit(0)
}
function fibonacci(n, a,b,c,i) {
a = 0
b = 1
for (i=1; i<=n; i++) {
c = a + b
a = b
b = c
}
return(c)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
function log10(x) { return log(x)/log(10) }
|
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 Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #ALGOL_68 | ALGOL 68 | BEGIN
# Show Bernoulli numbers B0 to B60 as rational numbers #
# Uses code from the Arithmetic/Rational task modified to use #
# LONG LONG INT to allow for the large number of digits requried #
PR precision 100 PR # sets the precision of LONG LONG INT #
# Code from the Arithmetic/Rational task #
# ============================================================== #
MODE FRAC = STRUCT( LONG LONG INT num #erator#, den #ominator#);
PROC gcd = (LONG LONG INT a, b) LONG LONG INT: # greatest common divisor #
(a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));
PROC lcm = (LONG LONG INT a, b)LONG LONG INT: # least common multiple #
a OVER gcd(a, b) * b;
PRIO // = 9; # higher then the ** operator #
OP // = (LONG LONG INT num, den)FRAC: ( # initialise and normalise #
LONG LONG INT common = gcd(num, den);
IF den < 0 THEN
( -num OVER common, -den OVER common)
ELSE
( num OVER common, den OVER common)
FI
);
OP + = (FRAC a, b)FRAC: (
LONG LONG INT common = lcm(den OF a, den OF b);
FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common );
num OF result//den OF result
);
OP - = (FRAC a, b)FRAC: a + -b,
* = (FRAC a, b)FRAC: (
LONG LONG INT num = num OF a * num OF b,
den = den OF a * den OF b;
LONG LONG INT common = gcd(num, den);
(num OVER common) // (den OVER common)
);
OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac);
# ============================================================== #
# end code from the Arithmetic/Rational task #
# Additional FRACrelated operators #
OP * = ( INT a, FRAC b )FRAC: ( num OF b * a ) // den OF b;
OP // = ( INT a, INT b )FRAC: LONG LONG INT( a ) // LONG LONG INT( b );
# returns the nth Bernoulli number, n must be >= 0 #
# Uses the algorithm suggested by the task, so B(1) is +1/2 #
PROC bernoulli = ( INT n )FRAC:
IF n < 0
THEN # n is out of range # 0 // 1
ELSE # n is valid #
[ 0 : n ]FRAC a;
FOR i FROM LWB a TO UPB a DO a[ i ] := 0 // 1 OD;
FOR m FROM 0 TO n DO
a[ m ] := 1 // ( m + 1 );
FOR j FROM m BY -1 TO 1 DO
a[ j - 1 ] := j * ( a[ j - 1 ] - a[ j ] )
OD
OD;
a[ 0 ]
FI # bernoulli # ;
FOR n FROM 0 TO 60 DO
FRAC bn := bernoulli( n );
IF num OF bn /= 0 THEN
# have a non-0 Bn #
print( ( "B(", whole( n, -2 ), ") ", whole( num OF bn, -50 ), " / ", whole( den OF bn, 0 ), newline ) )
FI
OD
END
|
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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binSearch64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Value find at index : @ \n"
szCarriageReturn: .asciz "\n"
sMessRecursif: .asciz "Recursive search : \n"
sMessNotFound: .asciz "Value not found. \n"
TableNumber: .quad 4,6,7,10,11,15,22,30,35
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x0,4 // search first value
ldr x1,qAdrTableNumber // address number table
mov x2,NBELEMENTS // number of élements
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#11 // search median value
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#12 //value not found
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
cmp x0,#-1
bne 2f
ldr x0,qAdrsMessNotFound
bl affichageMess
b 3f
2:
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
3:
mov x0,#35 // search last value
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
/****************************************/
/* recursive */
/****************************************/
ldr x0,qAdrsMessRecursif
bl affichageMess // display message
mov x0,#4 // search first value
ldr x1,qAdrTableNumber
mov x2,#0 // low index of elements
mov x3,#NBELEMENTS - 1 // high index of elements
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#11
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#12
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
cmp x0,#-1
bne 4f
ldr x0,qAdrsMessNotFound
bl affichageMess
b 5f
4:
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
5:
mov x0,#35
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
//qAdrsMessValeur: .quad sMessValeur
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrsMessRecursif: .quad sMessRecursif
qAdrsMessNotFound: .quad sMessNotFound
qAdrTableNumber: .quad TableNumber
/******************************************************************/
/* binary search iterative */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the number of elements */
/* x0 return index or -1 if not find */
bSearch:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // low index
sub x4,x2,#1 // high index = number of elements - 1
1:
cmp x3,x4
bgt 99f
add x2,x3,x4 // compute (low + high) /2
lsr x2,x2,#1
ldr x5,[x1,x2,lsl #3] // load value of table at index x2
cmp x5,x0
beq 98f
bgt 2f
add x3,x2,#1 // lower -> index low = index + 1
b 1b // and loop
2:
sub x4,x2,#1 // bigger -> index high = index - 1
b 1b // and loop
98:
mov x0,x2 // find !!!
b 100f
99:
mov x0,#-1 //not found
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* binary search recursif */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the low index of elements */
/* x3 contains the high index of elements */
/* x0 return index or -1 if not find */
bSearchR:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
stp x5,x6,[sp,-16]! // save registers
cmp x3,x2 // index high < low ?
bge 1f
mov x0,#-1 // yes -> not found
b 100f
1:
add x4,x2,x3 // compute (low + high) /2
lsr x4,x4,#1
ldr x5,[x1,x4,lsl #3] // load value of table at index x4
cmp x5,x0
beq 99f
bgt 2f // bigger ?
add x2,x4,#1 // no new search with low = index + 1
bl bSearchR
b 100f
2: // bigger
sub x3,x4,#1 // new search with high = index - 1
bl bSearchR
b 100f
99:
mov x0,x4 // find !!!
b 100f
100:
ldp x5,x6,[sp],16 // restaur 2 registers
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo |
count: function [s1 s2][
res: 0
loop.with:'i s1 'c [
if c = s2\[i] -> res: res + 1
]
return res
]
shuff: function [str]->
join shuffle split str
bestShuffle: function [s][
shuffled: shuff s
loop 0..dec size shuffled 'i [
if shuffled\[i] <> s\[i] -> continue
loop 0..dec size shuffled 'j [
if all? @[
shuffled\[i] <> shuffled\[j]
shuffled\[i] <> s\[j]
shuffled\[j] <> s\[i]
] [
tmp: shuffled\[i]
shuffled\[i]: shuffled\[j]
shuffled\[j]: tmp
break
]
]
]
return shuffled
]
words: ["abracadabra" "seesaw" "grrrrrr" "pop"
"up" "a" "antidisestablishmentarianism"]
loop words 'w [
sf: bestShuffle w
print [w "->" sf "| count:" count w sf]
] |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Common_Lisp | Common Lisp |
"string"
(coerce '(#\s #\t #\r #\i #\n #\g) 'string)
|
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Component_Pascal | Component Pascal |
MODULE NpctBinaryString;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str: ARRAY 256 OF CHAR;
pStr,pAux: POINTER TO ARRAY OF CHAR;
b: BYTE;
pIni: INTEGER;
BEGIN
(* String creation, on heap *)
NEW(pStr,256); (* Garbage collectable *)
NEW(pAux,256);
(* String assingment *)
pStr^ := "This is a string on a heap";
pAux^ := "This is a string on a heap";
str := "This is other string";
(* String comparision *)
StdLog.String("pStr = str:> ");StdLog.Bool(pStr$ = str$);StdLog.Ln;
StdLog.String("pStr = pAux:> ");StdLog.Bool(pStr$ = pAux$);StdLog.Ln;
(* String cloning and copying *)
NEW(pAux,LEN(pStr$) + 1);pAux^ := pStr$;
(* Check if a string is empty *)
(* version 1 *)
pAux^ := "";
StdLog.String("is empty pAux?(1):> ");StdLog.Bool(pAux$ = "");StdLog.Ln;
(* version 2 *)
pAux[0] := 0X;
StdLog.String("is empty pAux?(2):> ");StdLog.Bool(pAux$ = "");StdLog.Ln;
(* version 3 *)
pAux[0] := 0X;
StdLog.String("is empty pAux?(3):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln;
(* version 4 *)
pAux^ := "";
StdLog.String("is empty pAux?(4):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln;
(* Append a byte to a string *)
NEW(pAux,256);pAux^ := "BBBBBBBBBBBBBBBBBBBBB";
b := 65;pAux[LEN(pAux$)] := CHR(b);
StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln;
(* Extract a substring from a string *)
Strings.Extract(pStr,0,16,pAux);
StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln;
(* Replace a every ocurrence of a string with another string *)
pAux^ := "a"; (* Pattern *)
Strings.Find(pStr,pAux,0,pIni);
WHILE pIni > 0 DO
Strings.Replace(pStr,pIni,LEN(pAux$),"one");
Strings.Find(pStr,pAux,pIni + 1,pIni);
END;
StdLog.String("pStr:> ");StdLog.String(pStr);StdLog.Ln;
(* Join strings *)
pStr^ := "First string";pAux^ := "Second String";
str := pStr$ + "." + pAux$;
StdLog.String("pStr + '.' + pAux:>");StdLog.String(str);StdLog.Ln
END Do;
END NpctBinaryString.
|
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Go | Go | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d) // uses binary search
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
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,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
} |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | fun printSequence(sequence: String, width: Int = 50) {
fun <K, V> printWithLabel(k: K, v: V) {
val label = k.toString().padStart(5)
println("$label: $v")
}
println("SEQUENCE:")
sequence.chunked(width).withIndex().forEach { (i, line) ->
printWithLabel(i*width + line.length, line)
}
println("BASE:")
sequence.groupingBy { it }.eachCount().forEach { (k, v) ->
printWithLabel(k, v)
}
printWithLabel("TOTALS", sequence.length)
}
const val BASE_SEQUENCE = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fun main() {
printSequence(BASE_SEQUENCE)
} |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lambdatalk | Lambdatalk |
{def DNA CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT}
-> DNA
{def base_count
{def base_count.r
{lambda {:dna :b :n :i :count}
{if {> :i :n}
then :count
else {base_count.r :dna :b :n {+ :i 1}
{if {W.equal? {W.get :i :dna} :b}
then {+ :count 1}
else :count}} }}}
{lambda {:dna :b}
{base_count.r :dna :b {- {W.length :dna} 1} 0 0} }}
-> base_count
{def S {S.map {base_count {DNA}}} A C G T}}
-> S
[A C G T] = (129 97 119 155)
A+C+G+T = {+ {S}}
-> A+C+G+T = 500
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #8th | 8th |
2 base drop
#50 . cr
|
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.
| #Erlang | Erlang |
build_path({Sx, Sy}, {Tx, Ty}) ->
if
Tx < Sx -> StepX = -1;
true -> StepX = 1
end,
if
Ty < Sy -> StepY = -1;
true -> StepY = 1
end,
Dx = abs((Tx-Sx)*2),
Dy = abs((Ty-Sy)*2),
if
Dy > Dx -> Path = through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dx*2-Dy, []);
true -> Path = through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dy*2-Dx, [])
end,
lists:reverse(Path).
through_x({Tx, _}, {Tx, _}, _, _, _, P) -> P;
through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 >= 0 ->
Ny = Sy + StepY,
F1 = F0 - Dx,
Nx = Sx + StepX,
F2 = F1 + Dy,
through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]);
through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 < 0 ->
Ny = Sy,
Nx = Sx + StepX,
F2 = F0 + Dy,
through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]).
through_y({_, Ty}, {_, Ty}, _, _, _, P) -> P;
through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 >= 0 ->
Nx = Sx + StepX,
F1 = F0 - Dy,
Ny = Sy + StepY,
F2 = F1 + Dx,
through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]);
through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 < 0 ->
Nx = Sx,
Ny = Sy + StepY,
F2 = F0 + Dx,
through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]).
|
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Ring | Ring |
row = 0
dnaList = []
base = ["A","C","G","T"]
long = 20
see "Initial sequence:" + nl
see " 12345678901234567890" + nl
see " " + long + ": "
for nr = 1 to 200
row = row + 1
rnd = random(3)+1
baseStr = base[rnd]
see baseStr # + " "
if (row%20) = 0 and long < 200
long = long + 20
see nl
if long < 100
see " " + long + ": "
else
see "" + long + ": "
ok
ok
add(dnaList,baseStr)
next
see nl+ " 12345678901234567890" + nl
baseCount(dnaList)
for n = 1 to 10
rnd = random(2)+1
switch rnd
on 1
baseSwap(dnaList)
on 2
baseDelete(dnaList)
on 3
baseInsert(dnaList)
off
next
showDna(dnaList)
baseCount(dnaList)
func baseInsert(dnaList)
rnd1 = random(len(dnaList)-1)+1
rnd2 = random(len(base)-1)+1
insert(dnaList,rnd1,base[rnd2])
see "Insert base " + base[rnd2] + " at position " + rnd1 + nl
return dnaList
func baseDelete(dnaList)
rnd = random(len(dnaList)-1)+1
del(dnaList,rnd)
see "Erase base " + dnaList[rnd] + " at position " + rnd + nl
return dnaList
func baseSwap(dnaList)
rnd1 = random(len(dnaList))
rnd2 = random(3)+1
see "Change base at position " + rnd1 + " from " + dnaList[rnd1] + " to " + base[rnd2] + nl
dnaList[rnd1] = base[rnd2]
func showDna(dnaList)
long = 20
see nl + "After 10 mutations:" + nl
see " 12345678901234567890" + nl
see " " + long + ": "
for nr = 1 to len(dnaList)
row = row + 1
see dnaList[nr]
if (row%20) = 0 and long < 200
long = long + 20
see nl
if long < 100
see " " + long + ": "
else
see "" + long + ": "
ok
ok
next
see nl+ " 12345678901234567890" + nl
func baseCount(dnaList)
dnaBase = [:A=0, :C=0, :G=0, :T=0]
lenDna = len(dnaList)
for n = 1 to lenDna
dnaStr = dnaList[n]
switch dnaStr
on "A"
strA = dnaBase["A"]
strA++
dnaBase["A"] = strA
on "C"
strC = dnaBase["C"]
strC++
dnaBase["C"] = strC
on "G"
strG = dnaBase["G"]
strG++
dnaBase["G"] = strG
on "T"
strT = dnaBase["T"]
strT++
dnaBase["T"] = strT
off
next
see nl
see "A: " + dnaBase["A"] + ", "
see "T: " + dnaBase["T"] + ", "
see "C: " + dnaBase["C"] + ", "
see "G: " + dnaBase["G"] + ", "
total = dnaBase["A"] + dnaBase["T"] + dnaBase["C"] + dnaBase["G"]
see "Total: " + total+ nl + nl
|
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Ruby | Ruby | class DNA_Seq
attr_accessor :seq
def initialize(bases: %i[A C G T] , size: 0)
@bases = bases
@seq = Array.new(size){ bases.sample }
end
def mutate(n = 10)
n.times{|n| method([:s, :d, :i].sample).call}
end
def to_s(n = 50)
just_size = @seq.size / n
([email protected]).step(n).map{|from| "#{from.to_s.rjust(just_size)} " + @seq[from, n].join}.join("\n") +
"\nTotal #{seq.size}: #{@seq.tally.sort.to_h.inspect}\n\n"
end
def s = @seq[rand_index]= @bases.sample
def d = @seq.delete_at(rand_index)
def i = @seq.insert(rand_index, @bases.sample )
alias :swap :s
alias :delete :d
alias :insert :i
private
def rand_index = rand( @seq.size )
end
puts test = DNA_Seq.new(size: 200)
test.mutate
puts test
test.delete
puts test
|
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #UNIX_Shell | UNIX Shell | base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z})
bitcoinregex="^[$(printf "%s" "${base58[@]}")]{34}$"
decodeBase58() {
local s=$1
for i in {0..57}
do s="${s//${base58[i]}/ $i}"
done
dc <<< "16o0d${s// /+58*}+f"
}
checksum() {
xxd -p -r <<<"$1" |
openssl dgst -sha256 -binary |
openssl dgst -sha256 -binary |
xxd -p -c 80 |
head -c 8
}
checkBitcoinAddress() {
if [[ "$1" =~ $bitcoinregex ]]
then
h=$(decodeBase58 "$1")
checksum "00${h::${#h}-8}" |
grep -qi "^${h: -8}$"
else return 2
fi
} |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #Wren | Wren | import "/crypto" for Sha256
import "/str" for Str
import "/fmt" for Conv, Fmt
class Bitcoin {
static alphabet_ { "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }
static contentEquals_(ba1, ba2) {
if (ba1.count != ba2.count) return false
return !(0...ba1.count).any { |i| ba1[i] != ba2[i] }
}
static decodeBase58_(input) {
var output = List.filled(25, 0)
for (c in input) {
var p = alphabet_.indexOf(c)
if (p == -1) return null
for (j in 24..1) {
p = p + 58 * output[j]
output[j] = p % 256
p = p >> 8
}
if (p != 0) return null
}
return output
}
static sha256_(data, start, len, recursion) {
if (recursion == 0) return data
var md = Sha256.digest(data[start...start+len])
md = Str.chunks(md, 2).map { |x| Conv.atoi(x, 16) }.toList
return sha256_(md, 0, 32, recursion-1)
}
static validateAddress(address) {
var len = address.count
if (len < 26 || len > 35) return false
var decoded = decodeBase58_(address)
if (!decoded) return false
var hash = sha256_(decoded, 0, 21, 2)
return contentEquals_(hash[0..3], decoded[21..24])
}
}
var addresses = [
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j",
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X",
"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"BZbvjr",
"i55j",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz",
"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"
]
for (address in addresses) {
Fmt.print("$-36s -> $s", address, Bitcoin.validateAddress(address) ? "valid" : "invalid")
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Raku | Raku | class Pixel { has Int ($.R, $.G, $.B) }
class Bitmap {
has Int ($.width, $.height);
has Pixel @.data;
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i + $j * $!width] }
}
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
sub load-ppm ( $ppm ) {
my $fh = $ppm.IO.open( :enc('ISO-8859-1') );
my $type = $fh.get;
my ($width, $height) = $fh.get.split: ' ';
my $depth = $fh.get;
Bitmap.new( width => $width.Int, height => $height.Int,
data => ( $fh.slurp.ords.rotor(3).map:
{ Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } )
)
}
sub color-distance (Pixel $c1, Pixel $c2) {
sqrt( ( ($c1.R - $c2.R)² + ($c1.G - $c2.G)² + ($c1.B - $c2.B)² ) / ( 255 * sqrt(3) ) );
}
sub flood ($img, $x, $y, $c1) {
my $c2 = $img.pixel($x, $y);
my $max-distance = 10;
my @queue;
my %checked;
check($x, $y);
for @queue -> [$x, $y] {
$img.pixel($x, $y) = $c1.clone;
}
sub check ($x, $y) {
my $c3 = $img.pixel($x, $y);
if color-distance($c2, $c3) < $max-distance {
@queue.push: [$x,$y];
@queue.elems;
%checked{"$x,$y"} = 1;
check($x - 1, $y) if $x > 0 and %checked{"{$x - 1},$y"}:!exists;
check($x + 1, $y) if $x < $img.width - 1 and %checked{"{$x + 1},$y"}:!exists;
check($x, $y - 1) if $y > 0 and %checked{"$x,{$y - 1}"}:!exists;
check($x, $y + 1) if $y < $img.height - 1 and %checked{"$x,{$y + 1}"}:!exists;
}
}
}
my $infile = './Unfilled-Circle.ppm';
my Bitmap $b = load-ppm( $infile ) but PPM;
flood($b, 5, 5, Pixel.new(:255R, :0G, :0B));
flood($b, 5, 125, Pixel.new(:255R, :0G, :0B));
flood($b, 125, 5, Pixel.new(:255R, :0G, :0B));
flood($b, 125, 125, Pixel.new(:255R, :0G, :0B));
flood($b, 50, 50, Pixel.new(:0R, :0G, :255B));
my $outfile = open('./Bitmap-flood-perl6.ppm', :w, :bin);
$outfile.write: $b.P6;
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | >> islogical(true)
ans =
1
>> islogical(false)
ans =
1
>> islogical(logical(1))
ans =
1
>> islogical(logical(0))
ans =
1
>> islogical(1)
ans =
0
>> islogical(0)
ans =
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
| #MATLAB | MATLAB | >> islogical(true)
ans =
1
>> islogical(false)
ans =
1
>> islogical(logical(1))
ans =
1
>> islogical(logical(0))
ans =
1
>> islogical(1)
ans =
0
>> islogical(0)
ans =
0 |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #Julia | Julia | using Printf
function degree2compasspoint(d::Float64)
majors = ("north", "east", "south", "west", "north", "east", "south", "west")
quarter1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N")
quarter2 = map(p -> replace(p, "NE" => "EN"), quarter1)
d = d % 360 + 360 / 64
imajor, minor = divrem(d, 90)
iminor = div(minor * 4, 45)
imajor += 1
iminor += 1
p1, p2 = majors[imajor:imajor+1]
q = p1 in ("north", "south") ? quarter1 : quarter2
titlecase(replace(replace(q[iminor], 'N' => p1), 'E' => p2))
end
for i in 0:32
d = i * 11.25
i % 3 == 1 && (d += 5.62)
i % 3 == 2 && (d -= 5.62)
@printf("%2i %-17s %10.2f°\n", i % 32 + 1, degree2compasspoint(d), d)
end |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #D | D | T rot(T)(in T x, in int shift) pure nothrow @nogc {
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
void testBit(in int a, in int b) {
import std.stdio;
writefln("Input: a = %d, b = %d", a, b);
writefln("AND : %8b & %08b = %032b (%4d)", a, b, a & b, a & b);
writefln(" OR : %8b | %08b = %032b (%4d)", a, b, a | b, a | b);
writefln("XOR : %8b ^ %08b = %032b (%4d)", a, b, a ^ b, a ^ b);
writefln("LSH : %8b << %08b = %032b (%4d)", a, b, a << b, a << b);
writefln("RSH : %8b >> %08b = %032b (%4d)", a, b, a >> b, a >> b);
writefln("NOT : %8s ~ %08b = %032b (%4d)", "", a, ~a, ~a);
writefln("ROT : rot(%8b, %d) = %032b (%4d)",
a, b, rot(a, b), rot(a, b));
}
void main() {
immutable int a = 0b_1111_1111; // bit literal 255
immutable int b = 0b_0000_0010; // bit literal 2
testBit(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 pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #E | E | def makeFlexList := <elib:tables.makeFlexList>
def format := <import:java.lang.makeString>.format
def CHANNELS := 3
def UByte := 0..255
def makeColor {
to fromFloat(r, g, b) {
return makeColor.fromByte((r * 255).round(),
(g * 255).round(),
(b * 255).round())
}
to fromByte(r :UByte, g :UByte, b :UByte) {
def color {
to __printOn(out) {
out.print(format("%02x%02x%02x", [color.rb(), color.gb(), color.bb()]))
}
to rf() { return r / 255 }
to gf() { return g / 255 }
to bf() { return b / 255 }
to rb() { return r }
to gb() { return g }
to bb() { return b }
}
return color
}
}
/** Convert 0..255 into 0..127 -128..-1 */
def sign(v) {
return v %% 256 - 2*(v & 128)
}
def makeImage(width, height) {
# NOTE: The primary E implementation is in Java and Java's fixed-size integers only
# come in signed varieties. Therefore, there is a little bit of extra arithmetic.
#
# In an ideal E implementation we would specify the type 0..255, but this is not
# currently possible everywhere, or efficient.
def storage := makeFlexList.fromType(<type:java.lang.Byte>, width * height * CHANNELS)
storage.setSize(width * height * CHANNELS)
def X := 0..!width
def Y := 0..!height
def flexImage {
to __printOn(out) {
for y in Y {
out.print("[")
for x in X {
out.print(flexImage[x, y], " ")
}
out.println("]")
}
}
to width() { return width }
to height() { return height }
to fill(color) {
for x in X {
for y in Y {
flexImage[x, y] := color
}
}
}
to get(x :X, y :Y) {
def base := (y * width + x) * CHANNELS
return makeColor.fromByte(storage[base + 0] %% 256,
storage[base + 1] %% 256,
storage[base + 2] %% 256)
}
/** Provided to make [[Flood fill]] slightly less insanely slow. */
to test(x :X, y :Y, c) {
def base := (y * width + x) * CHANNELS
return storage[base + 0] <=> sign(c.rb()) &&
storage[base + 1] <=> sign(c.gb()) &&
storage[base + 2] <=> sign(c.bb())
}
to put(x :X, y :Y, c) {
def base := (y * width + x) * CHANNELS
storage[base + 0] := sign(c.rb())
storage[base + 1] := sign(c.gb())
storage[base + 2] := sign(c.bb())
}
to writePPM(outputStream) {
outputStream.write(`P6$\n$width $height$\n255$\n`.getBytes("US-ASCII"))
outputStream.write(storage.getArray())
}
/** Used for [[Read ppm file]] */
to replace(list :List) {
require(list.size() == width * height * CHANNELS)
storage(0) := list
}
}
return flexImage
} |
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #C.23 | C# | using System;
using System.Numerics;
namespace BellNumbers {
public static class Utility {
public static void Init<T>(this T[] array, T value) {
if (null == array) return;
for (int i = 0; i < array.Length; ++i) {
array[i] = value;
}
}
}
class Program {
static BigInteger[][] BellTriangle(int n) {
BigInteger[][] tri = new BigInteger[n][];
for (int i = 0; i < n; ++i) {
tri[i] = new BigInteger[i];
tri[i].Init(BigInteger.Zero);
}
tri[1][0] = 1;
for (int i = 2; i < n; ++i) {
tri[i][0] = tri[i - 1][i - 2];
for (int j = 1; j < i; ++j) {
tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1];
}
}
return tri;
}
static void Main(string[] args) {
var bt = BellTriangle(51);
Console.WriteLine("First fifteen and fiftieth Bell numbers:");
for (int i = 1; i < 16; ++i) {
Console.WriteLine("{0,2}: {1}", i, bt[i][0]);
}
Console.WriteLine("50: {0}", bt[50][0]);
Console.WriteLine();
Console.WriteLine("The first ten rows of Bell's triangle:");
for (int i = 1; i < 11; ++i) {
//Console.WriteLine(bt[i]);
var it = bt[i].GetEnumerator();
Console.Write("[");
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", ");
Console.Write(it.Current);
}
Console.WriteLine("]");
}
}
}
} |
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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #BCPL | BCPL |
GET "libhdr"
MANIFEST {
fib_sz = 1_000_000_000 // keep 9 significant digits for computing F(n)
}
LET msd(n) = VALOF {
UNTIL n < 10 DO
n /:= 10
RESULTIS n
}
LET fibonacci(n, tally) BE {
LET a, b, c, e = 0, 1, ?, 0
FOR i = 1 TO n {
TEST e = 0
THEN tally[msd(b)] +:= 1
ELSE tally[b / (fib_sz / 10)] +:= 1
c := a + b
IF c > fib_sz {
a := a / 10 - (a MOD 10 >= 5) // subtract, since condition evalutes to
b := b / 10 - (b MOD 10 >= 5) // eithr 0 or -1.
c := a + b
e +:= 1 // keep track of exponent, just 'cuz
}
a, b := b, c
}
}
LET start() = VALOF {
// expected value of benford: log10(d + 1/d)
LET expected = TABLE 0, 301, 176, 125, 97, 79, 67, 58, 51, 46
LET actual = VEC 9
FOR i = 0 TO 9 DO actual!i := 0
fibonacci(1000, actual)
writes("*nLeading digital distribution of the first 1,000 Fibonacci numbers*n")
writes("Digit*tActual*tExpected*n")
FOR i = 1 TO 9
writef("%i *t%0.3d *t%0.3d *n", i, actual!i, expected!i)
RESULTIS 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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
float *benford_distribution(void)
{
static float prob[9];
for (int i = 1; i < 10; i++)
prob[i - 1] = log10f(1 + 1.0 / i);
return prob;
}
float *get_actual_distribution(char *fn)
{
FILE *input = fopen(fn, "r");
if (!input)
{
perror("Can't open file");
exit(EXIT_FAILURE);
}
int tally[9] = { 0 };
char c;
int total = 0;
while ((c = getc(input)) != EOF)
{
/* get the first nonzero digit on the current line */
while (c < '1' || c > '9')
c = getc(input);
tally[c - '1']++;
total++;
/* discard rest of line */
while ((c = getc(input)) != '\n' && c != EOF)
;
}
fclose(input);
static float freq[9];
for (int i = 0; i < 9; i++)
freq[i] = tally[i] / (float) total;
return freq;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: benford <file>\n");
return EXIT_FAILURE;
}
float *actual = get_actual_distribution(argv[1]);
float *expected = benford_distribution();
puts("digit\tactual\texpected");
for (int i = 0; i < 9; i++)
printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);
return EXIT_SUCCESS;
} |
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 Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #Bracmat | Bracmat | ( BernoulliList
= B Bs answer indLn indexLen indexPadding
, n numberPadding p solPos solidusPos sp
. ( B
= m A a j b
. -1:?m
& :?A
& whl
' ( 1+!m:~>!arg:?m
& ((!m+1:?j)^-1:?a)
map
$ ( (
= .(-1+!j:?j)*(!arg+-1*!a):?a
)
. !A
)
: ?A
)
& !A:? @?b
& !b
)
& -1:?n
& :?Bs
& whl
' ( 1+!n:~>!arg:?n
& B$!n !Bs:?Bs
)
& @(!arg:? [?indexLen)
& 1+!indexLen:?indexLen
& !Bs:%@(?:? "/" [?solidusPos ?) ?
& 1+!solidusPos:?solidusPos:?p
& :?sp
& whl
' (!p+-1:~<0:?p&" " !sp:?sp)
& :?answer
& whl
' ( !Bs:%?B ?Bs
& ( !B:0
| (!B:/|str$(!B "/1"):?B)
& @(!B:? "/" [?solPos ?)
& @(!arg:? [?indLn)
& !sp
: ? [(-1*!indexLen+!indLn) ?indexPadding
: ? [(-1*!solidusPos+!solPos) ?numberPadding
& "B("
!arg
")="
!indexPadding
!numberPadding
(!B:>0&" "|)
!B
\n
!answer
: ?answer
)
& -1+!arg:?arg
)
& str$!answer
)
& BernoulliList$60; |
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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #ACL2 | ACL2 | (defun defarray (name size initial-element)
(cons name
(compress1 name
(cons (list :HEADER
:DIMENSIONS (list size)
:MAXIMUM-LENGTH (1+ size)
:DEFAULT initial-element
:NAME name)
nil))))
(defconst *dim* 100000)
(defun array-name (array)
(first array))
(defun set-at (array i val)
(cons (array-name array)
(aset1 (array-name array)
(cdr array)
i
val)))
(defun populate-array-ordered (array n)
(if (zp n)
array
(populate-array-ordered (set-at array
(- *dim* n)
(- *dim* n))
(1- n))))
(include-book "arithmetic-3/top" :dir :system)
(defun binary-search-r (needle haystack low high)
(declare (xargs :measure (nfix (1+ (- high low)))))
(let* ((mid (floor (+ low high) 2))
(current (aref1 (array-name haystack)
(cdr haystack)
mid)))
(cond ((not (and (natp low) (natp high))) nil)
((= current needle)
mid)
((zp (1+ (- high low))) nil)
((> current needle)
(binary-search-r needle
haystack
low
(1- mid)))
(t (binary-search-r needle
haystack
(1+ mid)
high)))))
(defun binary-search (needle haystack)
(binary-search-r needle haystack 0
(maximum-length (array-name haystack)
(cdr haystack))))
(defun test-bsearch (needle)
(binary-search needle
(populate-array-ordered
(defarray 'haystack *dim* 0)
*dim*))) |
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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | words := "abracadabra,seesaw,elk,grrrrrr,up,a"
Loop Parse, Words,`,
out .= Score(A_LoopField, Shuffle(A_LoopField))
MsgBox % clipboard := out
Shuffle(String)
{
Cord := String
Length := StrLen(String)
CharType := A_IsUnicode ? "UShort" : "UChar"
Loop, Parse, String ; For each old character in String...
{
Char1 := SubStr(Cord, A_Index, 1)
If (Char1 <> A_LoopField) ; If new character already differs,
Continue ; do nothing.
Index1 := A_Index
OldChar1 := A_LoopField
Random, Index2, 1, Length ; Starting at some random index,
Loop, %Length% ; for each index...
{
If (Index1 <> Index2) ; Swap requires two different indexes.
{
Char2 := SubStr(Cord, Index2, 1)
OldChar2 := SubStr(String, Index2, 1)
; If after the swap, the two new characters would differ from
; the two old characters, then do the swap.
If (Char1 <> OldChar2) and (Char2 <> OldChar1)
{
; Swap Char1 and Char2 inside Cord.
NumPut(Asc(Char1), Cord, (Index2 - 1) << !!A_IsUnicode, CharType)
NumPut(Asc(Char2), Cord, (Index1 - 1) << !!A_IsUnicode, CharType)
Break
}
}
Index2 += 1 ; Get next index.
If (Index2 > Length) ; If after last index,
Index2 := 1 ; use first index.
}
}
Return Cord
}
Score(a, b){
r := 0
Loop Parse, a
If (A_LoopField = SubStr(b, A_Index, 1))
r++
return a ", " b ", (" r ")`n"
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #D | D | void main() /*@safe*/ {
import std.array: empty, replace;
import std.string: representation, assumeUTF;
// String creation (destruction is usually handled by
// the garbage collector).
ubyte[] str1;
// String assignments.
str1 = "blah".dup.representation;
// Hex string, same as "\x00\xFB\xCD\x32\xFD\x0A"
// whitespace and newlines are ignored.
str1 = cast(ubyte[])x"00 FBCD 32FD 0A";
// String comparison.
ubyte[] str2;
if (str1 == str2) {} // Strings equal.
// String cloning and copying.
str2 = str1.dup; // Copy entire string or array.
// Check if a string is empty
if (str1.empty) {} // String empty.
if (str1.length) {} // String not empty.
if (!str1.length) {} // String empty.
// Append a ubyte to a string.
str1 ~= x"0A";
str1 ~= 'a';
// Extract a substring from a string.
str1 = "blork".dup.representation;
// This takes off the first and last bytes and
// assigns them to the new ubyte string.
// This is just a light slice, no string data copied.
ubyte[] substr = str1[1 .. $ - 1];
// Replace every occurrence of a ubyte (or a string)
// in a string with another string.
str1 = "blah".dup.representation;
replace(str1.assumeUTF, "la", "al");
// Join two strings.
ubyte[] str3 = str1 ~ str2;
} |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Haskell | Haskell | import Control.Monad (foldM)
import Data.List (partition)
binSplit :: Ord a => [a] -> [a] -> [[a]]
binSplit lims ns = counts ++ [rest]
where
(counts, rest) = foldM split ns lims
split l i = let (a, b) = partition (< i) l in ([a], b)
binCounts :: Ord a => [a] -> [a] -> [Int]
binCounts b = fmap length . binSplit b |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | function prettyprint(seq) -- approx DDBJ format
seq = seq:gsub("%A",""):lower()
local sums, n = { a=0, c=0, g=0, t=0 }, 1
seq:gsub("(%a)", function(c) sums[c]=sums[c]+1 end)
local function printf(s,...) io.write(s:format(...)) end
printf("LOCUS AB000000 %12d bp mRNA linear HUM 01-JAN-2001\n", #seq)
printf(" BASE COUNT %12d a %12d c %12d g %12d t\n", sums.a, sums.c, sums.g, sums.t)
printf("ORIGIN\n")
while n < #seq do
local sub60 = seq:sub(n,n+59)
printf("%9d %s\n", n, sub60:gsub("(..........)","%1 "))
n = n + #sub60
end
end
prettyprint[[
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
]] |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binarydigit.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
sMessAffBindeb: .asciz "The decimal value "
sMessAffBin: .asciz " should produce an output of "
szRetourLigne: .asciz "\n"
/*******************************************/
/* Uninitialized data */
/*******************************************/
.bss
sZoneConv: .skip 100
sZoneBin: .skip 100
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: /* entry of program */
mov x5,5
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,50
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,-1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
/* other number */
mov x5,1
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5
ldr x1,qAdrsZoneBin
bl conversion2 // binary conversion and display résult
ldr x0,qAdrsZoneBin
ldr x0,qAdrsMessAffBindeb
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrsMessAffBin
bl affichageMess
ldr x0,qAdrsZoneBin
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
100: // standard end of the program */
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneBin: .quad sZoneBin
qAdrsMessAffBin: .quad sMessAffBin
qAdrsMessAffBindeb: .quad sMessAffBindeb
qAdrszRetourLigne: .quad szRetourLigne
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* x0 contains the register */
/* x1 contains the address of receipt area */
conversion2:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
clz x2,x0 // number of left zeros bits
mov x3,64
sub x2,x3,x2 // number of significant bits
strb wzr,[x1,x2] // store 0 final
sub x3,x2,1 // position counter of the written character
2: // loop
tst x0,1 // test first bit
lsr x0,x0,#1 // shift right one bit
bne 3f
mov x4,#48 // bit = 0 => character '0'
b 4f
3:
mov x4,#49 // bit = 1 => character '1'
4:
strb w4,[x1,x3] // character in reception area at position counter
sub x3,x3,#1
subs x2,x2,#1 // 0 bits ?
bgt 2b // no! loop
100:
ldp x3,x4,[sp],16 // restaur 2 registres
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #ERRE | ERRE |
PROGRAM BRESENHAM
!$INCLUDE="PC.LIB"
PROCEDURE BRESENHAM
! === Draw a line using graphic coordinates
! Inputs are X1, Y1, X2, Y2: Destroys value of X1, Y1
dx=ABS(x2-x1) sx=-1
IF x1<x2 THEN sx=1
dy=ABS(y2-y1) sy=-1
IF y1<y2 THEN sy=1
er=-dy
IF dx>dy THEN er=dx
er=INT(er/2)
LOOP
PSET(x1,y1,1)
EXIT IF x1=x2 AND y1=y2
e2=er
IF e2>-dx THEN er=er-dy x1=x1+sx
IF e2<dy THEN er=er+dx y1=y1+sy
END LOOP
END PROCEDURE
BEGIN
SCREEN(2)
INPUT(x1,y1,x2,y2)
BRESENHAM
GET(A$)
SCREEN(0)
END PROGRAM
|
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Swift | Swift | let bases: [Character] = ["A", "C", "G", "T"]
enum Action: CaseIterable {
case swap, delete, insert
}
@discardableResult
func mutate(dna: inout String) -> Action {
guard let i = dna.indices.shuffled().first(where: { $0 != dna.endIndex }) else {
fatalError()
}
let action = Action.allCases.randomElement()!
switch action {
case .swap:
dna.replaceSubrange(i..<i, with: [bases.randomElement()!])
case .delete:
dna.remove(at: i)
case .insert:
dna.insert(bases.randomElement()!, at: i)
}
return action
}
var d = ""
for _ in 0..<200 {
d.append(bases.randomElement()!)
}
func printSeq(_ dna: String) {
for startI in stride(from: 0, to: dna.count, by: 50) {
print("\(startI): \(dna.dropFirst(startI).prefix(50))")
}
print()
print("Size: \(dna.count)")
print()
let counts = dna.reduce(into: [:], { $0[$1, default: 0] += 1 })
for (char, count) in counts.sorted(by: { $0.key < $1.key }) {
print("\(char): \(count)")
}
}
printSeq(d)
print()
for _ in 0..<20 {
mutate(dna: &d)
}
printSeq(d) |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Vlang | Vlang | import rand
import rand.seed
const bases = "ACGT"
// 'w' contains the weights out of 300 for each
// of swap, delete or insert in that order.
fn mutate(dna string, w [3]int) string {
le := dna.len
// get a random position in the dna to mutate
p := rand.intn(le) or {0}
// get a random number between 0 and 299 inclusive
r := rand.intn(300) or {0}
mut bytes := dna.bytes()
match true {
r < w[0] { // swap
base := bases[rand.intn(4) or {0}]
println(" Change @${p:3} ${[bytes[p]].bytestr()} to ${[base].bytestr()}")
bytes[p] = base
}
r < w[0]+w[1] { // delete
println(" Delete @${p:3} ${bytes[p]}")
bytes.delete(p)
//copy(bytes[p:], bytes[p+1:])
bytes = bytes[0..le-1]
}
else { // insert
base := bases[rand.intn(4) or {0}]
bytes << 0
bytes.insert(p,bytes[p])
//copy(bytes[p+1:], bytes[p:])
println(" Insert @${p:3} $base")
bytes[p] = base
}
}
return bytes.bytestr()
}
// Generate a random dna sequence of given length.
fn generate(le int) string {
mut bytes := []u8{len:le}
for i := 0; i < le; i++ {
bytes[i] = bases[rand.intn(4) or {0}]
}
return bytes.bytestr()
}
// Pretty print dna and stats.
fn pretty_print(dna string, rowLen int) {
println("SEQUENCE:")
le := dna.len
for i := 0; i < le; i += rowLen {
mut k := i + rowLen
if k > le {
k = le
}
println("${i:5}: ${dna[i..k]}")
}
mut base_map := map[byte]int{} // allows for 'any' base
for i in 0..le {
base_map[dna[i]]++
}
mut bb := base_map.keys()
bb.sort()
println("\nBASE COUNT:")
for base in bb {
println(" $base: ${base_map[base]:3}")
}
println(" ------")
println(" Σ: $le")
println(" ======\n")
}
// Express weights as a string.
fn wstring(w [3]int) string {
return " Change: ${w[0]}\n Delete: ${w[1]}\n Insert: ${w[2]}\n"
}
fn main() {
rand.seed(seed.time_seed_array(2))
mut dna := generate(250)
pretty_print(dna, 50)
muts := 10
w := [100, 100, 100]! // use e.g. {0, 300, 0} to choose only deletions
println("WEIGHTS (ex 300):\n${wstring(w)}")
println("MUTATIONS ($muts):")
for _ in 0..muts {
dna = mutate(dna, w)
}
println('')
pretty_print(dna, 50)
} |
http://rosettacode.org/wiki/Bitcoin/address_validation | Bitcoin/address validation | Bitcoin/address validation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
0 zero
O uppercase oh
I uppercase eye
l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
the first byte is the version number, which will be zero for this task ;
the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for SHA-256.
Example of a bitcoin address
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| #zkl | zkl | var [const] MsgHash=Import("zklMsgHash"); // SHA-256, etc
const symbols="123456789" // 58 characters: no cap i,o; ell, zero
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
fcn unbase58(str){ // --> Data (byte bucket)
out:=Data().fill(0,25);
str.pump(Void,symbols.index,'wrap(n){ // throws on out of range
[24..0,-1].reduce('wrap(c,idx){
c+=58*out[idx]; // throws if not enough data
out[idx]=c;
c/256; // should be zero when done
},n) : if(_) throw(Exception.ValueError("address too long"));
});
out;
}
fcn coinValide(addr){
reg dec,chkSum;
try{ dec=unbase58(addr) }catch{ return(False) }
chkSum=dec[-4,*]; dec.del(21,*);
// hash then hash the hash --> binary hash (instead of hex string)
(2).reduce(MsgHash.SHA256.fp1(1,dec),dec); // dec is i/o buffer
dec[0,4]==chkSum;
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #REXX | REXX | /*REXX program demonstrates a method to perform a flood fill of an area. */
black= '000000000000000000000000'b /*define the black color (using bits).*/
red = '000000000000000011111111'b /* " " red " " " */
green= '000000001111111100000000'b /* " " green " " " */
white= '111111111111111111111111'b /* " " white " " " */
/*image is defined to the test image. */
hx= 125; hy= 125 /*define limits (X,Y) for the image. */
area= white; call fill 125, 25, red /*fill the white area in red. */
area= black; call fill 125, 125, green /*fill the center orb in green. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fill: procedure expose image. hx hy area; parse arg x,y,fill_color /*obtain the args.*/
if x<1 | x>hx | y<1 | y>hy then return /*X or Y are outside of the image area*/
pixel= image.x.y /*obtain the color of the X,Y pixel. */
if pixel \== area then return /*the pixel has already been filled */
/*with the fill_color, or we are not */
/*within the area to be filled. */
image.x.y= fill_color /*color desired area with fill_color. */
pixel= @(x , y-1); if pixel==area then call fill x , y-1, fill_color /*north*/
pixel= @(x-1, y ); if pixel==area then call fill x-1, y , fill_color /*west */
pixel= @(x+1, y ); if pixel==area then call fill x+1, y , fill_color /*east */
pixel= @(x , y+1); if pixel==area then call fill x , y+1, fill_color /*south*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg $x,$y; return image.$x.$y /*return with color of the X,Y pixel.*/ |
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
| #Maxima | Maxima | is(1 < 2);
/* true */
is(2 < 1);
/* false */
not true;
/* false */
not false;
/* 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
| #Metafont | Metafont | boolTrue = true
boolFalse = false
if boolTrue then print "boolTrue is true, and its value is: " + boolTrue
if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse
mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue) |
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
| #min | min | boolTrue = true
boolFalse = false
if boolTrue then print "boolTrue is true, and its value is: " + boolTrue
if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse
mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue) |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #K | K | d:("N;Nbe;N-ne;Nebn;Ne;Nebe;E-ne;Ebn;")
d,:("E;Ebs;E-se;Sebe;Se;Sebs;S-se;Sbe;")
d,:("S;Sbw;S-sw;Swbs;Sw;Swbw;W-sw;Wbs;")
d,:("W;Wbn;W-nw;Nwbw;Nw;Nwbn;N-nw;Nbw;N")
split:{1_'(&x=y)_ x:y,x}
dd:split[d;";"]
/ lookup table
s1:"NEWSnewsb-"
s2:("North";"East";"West";"South";"north";"east";"west";"south";" by ";"-")
c:.({`$x}'s1),'{`$x}'s2 / create the dictionary
cc:{,/{$c[`$$x]}'x} / lookup function
/ calculate the degrees
f:{m:x!3;(11.25*x)+:[1=m;+5.62;2=m;-5.62;0]} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Delphi | Delphi | program Bitwise;
{$APPTYPE CONSOLE}
begin
Writeln('2 and 3 = ', 2 and 3);
Writeln('2 or 3 = ', 2 or 3);
Writeln('2 xor 3 = ', 2 xor 3);
Writeln('not 2 = ', not 2);
Writeln('2 shl 3 = ', 2 shl 3);
Writeln('2 shr 3 = ', 2 shr 3);
// there are no built-in rotation operators in Delphi
Readln;
end. |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #EchoLisp | EchoLisp |
(lib 'plot)
(define width 600)
(define height 400)
(plot-size width height) ;; set image size
(define (blue x y) (rgb 0.0 0.0 1.0)) ;; a constant function
(plot-rgb blue 1 1) ;; blue everywhere
(lib 'types) ;; uint32 and uint8 vector types
;; bit-map pixel access
(define bitmap (pixels->uint32-vector)) ;; screen to vector of int32
→ 240000
(define (pix-at x y) (vector-ref bitmap (+ x (* y width))))
(rgb->list (pix-at 100 200)) → (0 0 255 255) ;; rgb blue
;; writing to bitmap
(define (set-color-xy x y col) (vector-set! bitmap (+ x (* y width)) col))
(for* ((x 100)(y 200)) (set-color-xy x y (rgb 1 1 0))) ;; to bitmap
(vector->pixels bitmap) ;; bitmap to screen
;; bit-map color components (r g b a) = index (0 1 2 3) access
(define bitmap (pixels->uint8-clamped-vector)) ;; screen to vector of uint8
(vector-length bitmap)
→ 960000
(define (blue-at-xy x y) (vector-ref bitmap (+ x 3 (* y width)))) ;; 3 = blue component
(blue-at-xy 100 200)
→ 255
|
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#ifdef HAVE_BOOST
#include <boost/multiprecision/cpp_int.hpp>
typedef boost::multiprecision::cpp_int integer;
#else
typedef unsigned int integer;
#endif
auto make_bell_triangle(int n) {
std::vector<std::vector<integer>> bell(n);
for (int i = 0; i < n; ++i)
bell[i].assign(i + 1, 0);
bell[0][0] = 1;
for (int i = 1; i < n; ++i) {
std::vector<integer>& row = bell[i];
std::vector<integer>& prev_row = bell[i - 1];
row[0] = prev_row[i - 1];
for (int j = 1; j <= i; ++j)
row[j] = row[j - 1] + prev_row[j - 1];
}
return bell;
}
int main() {
#ifdef HAVE_BOOST
const int size = 50;
#else
const int size = 15;
#endif
auto bell(make_bell_triangle(size));
const int limit = 15;
std::cout << "First " << limit << " Bell numbers:\n";
for (int i = 0; i < limit; ++i)
std::cout << bell[i][0] << '\n';
#ifdef HAVE_BOOST
std::cout << "\n50th Bell number is " << bell[49][0] << "\n\n";
#endif
std::cout << "First 10 rows of the Bell triangle:\n";
for (int i = 0; i < 10; ++i) {
std::cout << bell[i][0];
for (int j = 1; j <= i; ++j)
std::cout << ' ' << bell[i][j];
std::cout << '\n';
}
return 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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #C.2B.2B | C++ | //to cope with the big numbers , I used the Class Library for Numbers( CLN )
//if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram"
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
//since a and b are passed as references to the generator's constructor
//they are constantly changed !
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
|
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 Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #C | C |
#include <stdlib.h>
#include <gmp.h>
#define mpq_for(buf, op, n)\
do {\
size_t i;\
for (i = 0; i < (n); ++i)\
mpq_##op(buf[i]);\
} while (0)
void bernoulli(mpq_t rop, unsigned int n)
{
unsigned int m, j;
mpq_t *a = malloc(sizeof(mpq_t) * (n + 1));
mpq_for(a, init, n + 1);
for (m = 0; m <= n; ++m) {
mpq_set_ui(a[m], 1, m + 1);
for (j = m; j > 0; --j) {
mpq_sub(a[j-1], a[j], a[j-1]);
mpq_set_ui(rop, j, 1);
mpq_mul(a[j-1], a[j-1], rop);
}
}
mpq_set(rop, a[0]);
mpq_for(a, clear, n + 1);
free(a);
}
int main(void)
{
mpq_t rop;
mpz_t n, d;
mpq_init(rop);
mpz_inits(n, d, NULL);
unsigned int i;
for (i = 0; i <= 60; ++i) {
bernoulli(rop, i);
if (mpq_cmp_ui(rop, 0, 1)) {
mpq_get_num(n, rop);
mpq_get_den(d, rop);
gmp_printf("B(%-2u) = %44Zd / %Zd\n", i, n, d);
}
}
mpz_clears(n, d, NULL);
mpq_clear(rop);
return 0;
}
|
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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Action.21 | Action! | INT FUNC BinarySearch(INT ARRAY a INT len,value)
INT low,high,mid
low=0 high=len-1
WHILE low<=high
DO
mid=low+(high-low) RSH 1
IF a(mid)>value THEN
high=mid-1
ELSEIF a(mid)<value THEN
low=mid+1
ELSE
RETURN (mid)
FI
OD
RETURN (-1)
PROC Test(INT ARRAY a INT len,value)
INT i
Put('[)
FOR i=0 TO len-1
DO
PrintI(a(i))
IF i<len-1 THEN Put(32) FI
OD
i=BinarySearch(a,len,value)
Print("] ") PrintI(value)
IF i<0 THEN
PrintE(" not found")
ELSE
Print(" found at index ")
PrintIE(i)
FI
RETURN
PROC Main()
INT ARRAY a=[65530 0 1 2 5 6 8 9]
Test(a,8,6)
Test(a,8,-6)
Test(a,8,9)
Test(a,8,-10)
Test(a,8,10)
Test(a,8,7)
RETURN |
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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK | {
scram = best_shuffle($0)
print $0 " -> " scram " (" unchanged($0, scram) ")"
}
function best_shuffle(s, c, i, j, len, r, t) {
len = split(s, t, "")
# Swap elements of t[] to get a best shuffle.
for (i = 1; i <= len; i++) {
for (j = 1; j <= len; j++) {
# Swap t[i] and t[j] if they will not match
# the original characters from s.
if (i != j &&
t[i] != substr(s, j, 1) &&
substr(s, i, 1) != t[j]) {
c = t[i]
t[i] = t[j]
t[j] = c
break
}
}
}
# Join t[] into one string.
r = ""
for (i = 1; i <= len; i++)
r = r t[i]
return r
}
function unchanged(s1, s2, count, len) {
count = 0
len = length(s1)
for (i = 1; i <= len; i++) {
if (substr(s1, i, 1) == substr(s2, i, 1))
count++
}
return count
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :b make-blob 10 #ten bytes of initial size
set-to b 0 255
!. get-from b 0 #prints 255
!. b #prints (blob:ff000000000000000000)
local :b2 make-blob 3
set-to b2 0 97
set-to b2 1 98
set-to b2 2 99
!. b #prints (blob:"abc")
!. !encode!utf-8 b #prints "abc"
|
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Delphi | Delphi |
program Binary_strings;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
x : string;
c : TArray<Byte>;
objecty,
y : string;
empty : string;
nullString : string;
whitespace,
slice,
greeting,
join : string;
begin
//string creation
x:= String.create(['1','2','3']);
x:= String.create('*',8);
x := 'hello world';
//# string assignment with a hex byte
x := 'ab'#10;
writeln(x);
writeln(x.Length); // 3
//# string comparison
if x = 'hello' then
writeln('equal')
else
writeln('not equal');
if x.CompareTo('bc') = -1 then
writeln('x is lexicographically less than "bc"');
//# string cloning
y := x; // string is not object is delphi (are imutables)
writeln(x = y); //same as string.equals
writeln(x.Equals(y)); //it overrides object.Equals
//# check if empty
// Strings can't be null (nil), just Pchar can be
// IsNullOrEmpty and IsNullOrWhiteSpace, check only for
// Empty and Whitespace respectively.
empty := '';
whitespace := ' ';
if (empty = string.Empty) and
string.IsNullOrEmpty(empty) and
string.IsNullOrWhiteSpace(empty) and
string.IsNullOrWhiteSpace(whitespace) then
writeln('Strings are empty or whitespace');
//# append a byte
x := 'helloworld';
x := x + Chr(83);
// x := x + #83; // the same of above line
writeln(x);
//# substring
slice := x.Substring(5, 5);
writeln(slice);
//# replace bytes
greeting := x.Replace('worldS', '');
writeln(greeting);
//# join strings
join := greeting + ' ' + slice;
writeln(join);
Readln;
end. |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #J | J | Idotr=: |.@[ (#@[ - I.) ] NB. reverses order of limits to obtain intervals closed on left, open on right (>= y <)
binnedData=: adverb define
bidx=. i.@>:@# x NB. indicies of bins
x (Idotr (u@}./.)&(bidx&,) ]) y NB. apply u to data in each bin after dropping first value
)
require 'format/printf'
printBinCounts=: verb define
counts =. y
'%2d in [ -∞, %3d)' printf ({. counts) , {. x
'%2d in [%3d, %3d)' printf (}.}: counts) ,. 2 ]\ x
'%2d in [%3d, ∞]' printf ({: counts) , {: 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]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Java | Java | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
// n == limits[i]; we put it in right-side bin (i+1)
i = i+1;
} else {
// n is not in limits and i is ~(insertion point)
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
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);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
} |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | seq = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCA\
ATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGC\
AATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGA\
TTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTC\
TTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTT\
AGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAA\
TGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGT\
TAAACTACGAACGTAAT";
size = 70;
parts = StringPartition[seq, UpTo[size]];
begins = Most[Accumulate[Prepend[StringLength /@ parts, 1]]];
ends = Rest[Accumulate[Prepend[StringLength /@ parts, 0]]];
StringRiffle[MapThread[ToString[#1] <> "-" <> ToString[#2] <> ": " <> #3 &, {begins, ends, parts}], "\n"]
StringRiffle[#1 <> ": " <> ToString[#2] & @@@ Tally[Characters[seq]], "\n"] |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB_.2F_Octave | MATLAB / Octave |
function r = base_count(f)
fid = fopen(f,'r');
nn=[0,0,0,0];
while ~feof(fid)
s = fgetl(fid);
fprintf(1,'%5d :%s\n', sum(nn), s(s=='A'|s=='C'|s=='G'|s=='T'));
nn = nn+[sum(s=='A'),sum(s=='C'),sum(s=='G'),sum(s=='T')];
end
fclose(fid);
fprintf(1, '\nBases:\n\n A : %d\n C : %d\n G : %d\n T : %d\n', nn);
fprintf(1, '\nTotal: %d\n\n', sum(nn));
end;
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #ACL2 | ACL2 | (include-book "arithmetic-3/top" :dir :system)
(defun bin-string-r (x)
(if (zp x)
""
(string-append
(bin-string-r (floor x 2))
(if (= 1 (mod x 2))
"1"
"0"))))
(defun bin-string (x)
(if (zp x)
"0"
(bin-string-r x))) |
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.
| #Euphoria | Euphoria | include std/console.e
include std/graphics.e
include std/math.e
-- the new_image function and related code in the 25 or so
-- lines below are from http://rosettacode.org/wiki/Basic_bitmap_storage#Euphoria
-- as of friday, march 2, 2012
-- Some color constants:
constant
black = #000000,
white = #FFFFFF,
red = #FF0000,
green = #00FF00,
blue = #0000FF
-- Create new image filled with some color
function new_image(integer width, integer height, atom fill_color)
return repeat(repeat(fill_color,height),width)
end function
--grid used for drawing lines in this program
sequence screenData = new_image(16,16,black)
--the line algorithm
function bresLine(sequence screenData, integer x0, integer y0, integer x1, integer y1, integer color)
integer deltaX = abs(x1 - x0), deltaY = abs(y1 - y0)
integer stepX, stepY, lineError, error2
if x0 < x1 then
stepX = 1
else
stepX = -1
end if
if y0 < y1 then
stepY = 1
else
stepY = -1
end if
if deltaX > deltaY then
lineError = deltaX
else
lineError = -deltaY
end if
lineError = round(lineError / 2, 1)
while 1 do
screenData[x0][y0] = color
if (x0 = x1 and y0 = y1) then
exit
end if
error2 = lineError
if error2 > -deltaX then
lineError -= deltaY
x0 += stepX
end if
if error2 < deltaY then
lineError += deltaX
y0 += stepY
end if
end while
return screenData -- return modified version of the screenData sequence
end function
--prevents console output wrapping to next line if it is too big for the screen
wrap(0)
--outer diamond
screenData = bresLine(screenData,8,1,16,8,white)
screenData = bresLine(screenData,16,8,8,16,white)
screenData = bresLine(screenData,8,16,1,8,white)
screenData = bresLine(screenData,1,8,8,1,white)
--inner diamond
screenData = bresLine(screenData,8,4,12,8,white)
screenData = bresLine(screenData,12,8,8,12,white)
screenData = bresLine(screenData,8,12,4,8,white)
screenData = bresLine(screenData,4,8,8,4,white)
-- center lines drawing from left to right, and the next from right to left.
screenData = bresLine(screenData,7,7,9,7,white)
screenData = bresLine(screenData,9,9,7,9,white)
--center dot
screenData = bresLine(screenData,8,8,8,8,white)
--print to the standard console output
for i = 1 to 16 do
puts(1,"\n")
for j = 1 to 16 do
if screenData[j][i] = black then
printf(1, "%s", ".")
else
printf(1, "%s", "#")
end if
end for
end for
puts(1,"\n\n")
any_key()
--/*
--output was edited to replace the color's hex digits for clearer output graphics.
--to output all the hex digits, use printf(1,"%06x", screenData[j][i])
--to output 'shortened' hex digits, use :
--printf(1, "%x", ( abs( ( (screenData[j][i] / #FFFFF) - 1 ) ) - 1 ) )
--and
--printf(1,"%x", abs( ( (screenData[j][i] / #FFFFF) - 1 ) ) )
--
--,respectively in the last if check.
--*/ |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
import "/sort" for Sort
var rand = Random.new()
var bases = "ACGT"
// 'w' contains the weights out of 300 for each
// of swap, delete or insert in that order.
var mutate = Fn.new { |dna, w|
var le = dna.count
// get a random position in the dna to mutate
var p = rand.int(le)
// get a random number between 0 and 299 inclusive
var r = rand.int(300)
var chars = dna.toList
if (r < w[0]) { // swap
var base = bases[rand.int(4)]
Fmt.print(" Change @$3d $q to $q", p, chars[p], base)
chars[p] = base
} else if (r < w[0] + w[1]) { // delete
Fmt.print(" Delete @$3d $q", p, chars[p])
chars.removeAt(p)
} else { // insert
var base = bases[rand.int(4)]
Fmt.print(" Insert @$3d $q", p, base)
chars.insert(p, base)
}
return chars.join()
}
// Generate a random dna sequence of given length.
var generate = Fn.new { |le|
var chars = [""] * le
for (i in 0...le) chars[i] = bases[rand.int(4)]
return chars.join()
}
// Pretty print dna and stats.
var prettyPrint = Fn.new { |dna, rowLen|
System.print("SEQUENCE:")
var le = dna.count
var i = 0
while (i < le) {
var k = i + rowLen
if (k > le) k = le
Fmt.print("$5d: $s", i, dna[i...k])
i = i + rowLen
}
var baseMap = {}
for (i in 0...le) {
var v = baseMap[dna[i]]
baseMap[dna[i]] = (v) ? v + 1 : 1
}
var bases = []
for (k in baseMap.keys) bases.add(k)
Sort.insertion(bases) // get bases into alphabetic order
System.print("\nBASE COUNT:")
for (base in bases) Fmt.print(" $s: $3d", base, baseMap[base])
System.print(" ------")
System.print(" Σ: %(le)")
System.print(" ======\n")
}
// Express weights as a string.
var wstring = Fn.new { |w|
return Fmt.swrite(" Change: $d\n Delete: $d\n Insert: $d\n", w[0], w[1], w[2])
}
var dna = generate.call(250)
prettyPrint.call(dna, 50)
var muts = 10
var w = [100, 100, 100] // use e.g. {0, 300, 0} to choose only deletions
Fmt.print("WEIGHTS (ex 300):\n$s", wstring.call(w))
Fmt.print("MUTATIONS ($d):", muts)
for (i in 0...muts) dna = mutate.call(dna, w)
System.print()
prettyPrint.call(dna, 50) |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Ruby | Ruby | # frozen_string_literal: true
require_relative 'raster_graphics'
class RGBColour
def ==(other)
values == other.values
end
end
class Pixmap
def flood_fill(pixel, new_colour)
current_colour = self[pixel.x, pixel.y]
queue = Queue.new
queue.enq(pixel)
until queue.empty?
p = queue.pop
next unless self[p.x, p.y] == current_colour
west = find_border(p, current_colour, :west)
east = find_border(p, current_colour, :east)
draw_line(west, east, new_colour)
q = west
while q.x <= east.x
%i[north south].each do |direction|
n = neighbour(q, direction)
queue.enq(n) if self[n.x, n.y] == current_colour
end
q = neighbour(q, :east)
end
end
end
def neighbour(pixel, direction)
case direction
when :north then Pixel[pixel.x, pixel.y - 1]
when :south then Pixel[pixel.x, pixel.y + 1]
when :east then Pixel[pixel.x + 1, pixel.y]
when :west then Pixel[pixel.x - 1, pixel.y]
end
end
def find_border(pixel, colour, direction)
nextp = neighbour(pixel, direction)
while self[nextp.x, nextp.y] == colour
pixel = nextp
nextp = neighbour(pixel, direction)
end
pixel
end
end
bitmap = Pixmap.new(300, 300)
bitmap.draw_circle(Pixel[149, 149], 120, RGBColour::BLACK)
bitmap.draw_circle(Pixel[200, 100], 40, RGBColour::BLACK)
bitmap.flood_fill(Pixel[140, 160], RGBColour::BLUE)
bitmap.save_as_png('flood_fill.png') |
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
| #MiniScript | MiniScript | boolTrue = true
boolFalse = false
if boolTrue then print "boolTrue is true, and its value is: " + boolTrue
if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse
mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue) |
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
| #Mirah | Mirah | import java.util.ArrayList
import java.util.HashMap
# booleans
puts 'true is true' if true
puts 'false is false' if (!false)
# lists treated as booleans
x = ArrayList.new
puts "empty array is true" if x
x.add("an element")
puts "full array is true" if x
puts "isEmpty() is false" if !x.isEmpty()
# maps treated as booleans
map = HashMap.new
puts "empty map is true" if map
map.put('a', '1')
puts "full map is true" if map
puts "size() is 0 is false" if !(map.size() == 0)
# these things do not compile
# value = nil # ==> cannot assign nil to Boolean value
# puts 'nil is false' if false == nil # ==> cannot compare boolean to nil
# puts '0 is false' if (0 == false) # ==> cannot compare int to false
#puts 'TRUE is true' if TRUE # ==> TRUE does not exist
#puts 'FALSE is false' if !FALSE # ==> FALSE does not exist
|
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
| #Modula-2 | Modula-2 | MODULE boo;
IMPORT InOut;
VAR result, done : BOOLEAN;
A, B : INTEGER;
BEGIN
result := (1 = 2);
result := NOT result;
done := FALSE;
REPEAT
InOut.ReadInt (A);
InOut.ReadInt (B);
done := A > B
UNTIL done
END boo. |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #Kotlin | Kotlin | // version 1.1.2
fun expand(cp: String): String {
val sb = StringBuilder()
for (c in cp) {
sb.append(when (c) {
'N' -> "north"
'E' -> "east"
'S' -> "south"
'W' -> "west"
'b' -> " by "
else -> "-"
})
}
return sb.toString().capitalize()
}
fun main(args: Array<String>) {
val cp = arrayOf(
"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"
)
println("Index Degrees Compass point")
println("----- ------- -------------")
val f = "%2d %6.2f %s"
for (i in 0..32) {
val index = i % 32
var heading = i * 11.25
when (i % 3) {
1 -> heading += 5.62
2 -> heading -= 5.62
}
println(f.format(index + 1, heading, expand(cp[index])))
}
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #DWScript | DWScript | PrintLn('2 and 3 = '+IntToStr(2 and 3));
PrintLn('2 or 3 = '+IntToStr(2 or 3));
PrintLn('2 xor 3 = '+IntToStr(2 xor 3));
PrintLn('not 2 = '+IntToStr(not 2));
PrintLn('2 shl 3 = '+IntToStr(2 shl 3));
PrintLn('2 shr 3 = '+IntToStr(2 shr 3)); |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #Elixir | Elixir |
defmodule RosBitmap do
defrecord Bitmap, pixels: nil, shape: {0, 0}
defp new(width, height, {:rgb, r, g, b}) do
Bitmap[
pixels: :array.new(width * height,
{:default, <<r::size(8), g::size(8), b::size(8)>>}),
shape: {width, height}]
end
def new(width, height), do: new(width, height, {:rgb, 0, 0, 0})
def fill(Bitmap[shape: {width, height}], {:rgb, _r, _g, _b}=color) do
new(width, height, color)
end
def set_pixel(Bitmap[pixels: pixels, shape: {width, _height}]=bitmap,
{:at, x, y}, {:rgb, r, g, b}) do
index = x + y * width
bitmap.pixels(:array.set(index, <<r::size(8), g::size(8), b::size(8)>>, pixels))
end
def get_pixel(Bitmap[pixels: pixels, shape: {width, _height}], {:at, x, y}) do
index = x + y * width
<<r::size(8), g::size(8), b::size(8)>> = :array.get(index, pixels)
{:rgb, r, g, b}
end
end
|
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #CLU | CLU | bell = cluster is make, get
rep = array[int]
idx = proc (row, col: int) returns (int)
return (row * (row - 1) / 2 + col)
end idx
get = proc (tri: cvt, row, col: int) returns (int)
return (tri[idx(row, col)])
end get
make = proc (rows: int) returns (cvt)
length: int := rows * (rows+1) / 2
arr: rep := rep$fill(0, length, 0)
arr[idx(1,0)] := 1
for i: int in int$from_to(2, rows) do
arr[idx(i,0)] := arr[idx(i-1, i-2)]
for j: int in int$from_to(1, i-1) do
arr[idx(i,j)] := arr[idx(i,j-1)] + arr[idx(i-1,j-1)]
end
end
return(arr)
end make
end bell
start_up = proc ()
rows = 15
po: stream := stream$primary_output()
belltri: bell := bell$make(rows)
stream$putl(po, "The first 15 Bell numbers are:")
for i: int in int$from_to(1, rows) do
stream$putl(po, int$unparse(i)
|| ": " || int$unparse(bell$get(belltri, i, 0)))
end
stream$putl(po, "\nThe first 10 rows of the Bell triangle:")
for row: int in int$from_to(1, 10) do
for col: int in int$from_to(0, row-1) do
stream$putright(po, int$unparse(bell$get(belltri, row, col)), 7)
end
stream$putc(po, '\n')
end
end start_up |
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Common_Lisp | Common Lisp | ;; The triangle is a list of arrays; each array is a
;; triangle's row; the last row is at the head of the list.
(defun grow-triangle (triangle)
(if (null triangle)
'(#(1))
(let* ((last-array (car triangle))
(last-length (length last-array))
(new-array (make-array (1+ last-length)
:element-type 'integer)))
;; copy over the last element of the last array
(setf (aref new-array 0) (aref last-array (1- last-length)))
;; fill in the rest of the array
(loop for i from 0
;; the last index of the new array is the length
;; of the last array, which is 1 unit shorter
for j from 1 upto last-length
for sum = (+ (aref last-array i) (aref new-array i))
do (setf (aref new-array j) sum))
;; return the grown list
(cons new-array triangle))))
(defun make-triangle (num)
(if (<= num 1)
(grow-triangle nil)
(grow-triangle (make-triangle (1- num)))))
(defun bell (num)
(cond ((< num 0) nil)
((= num 0) 1)
(t (aref (first (make-triangle num)) (1- num)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Printing section
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter *numbers-to-print*
(append
(loop for i upto 19 collect i)
'(49 50)))
(defun array->list (array)
(loop for i upto (1- (length array))
collect (aref array i)))
(defun print-bell-number (index bell-number)
(format t "B_~d (~:r Bell number) = ~:d~%"
index (1+ index) bell-number))
(defun print-bell-triangle (triangle)
(loop for row in (reverse triangle)
do (format t "~{~d~^, ~}~%" (array->list row))))
;; Final invocation
(loop for n in *numbers-to-print* do
(print-bell-number n (bell n)))
(princ #\newline)
(format t "The first 10 rows of Bell triangle:~%")
(print-bell-triangle (make-triangle 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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #Clojure | Clojure | (ns example
(:gen-class))
(defn abs [x]
(if (> x 0)
x
(- x)))
(defn calc-benford-stats [digits]
" Frequencies of digits in data "
(let [y (frequencies digits)
tot (reduce + (vals y))]
[y tot]))
(defn show-benford-stats [v]
" Prints in percent the actual, Benford expected, and difference"
(let [fd (map (comp first str) v)] ; first digit of each record
(doseq [q (range 1 10)
:let [[y tot] (calc-benford-stats fd)
d (first (str q)) ; reference digit
f (/ (get y d 0) tot 0.01) ; percent of occurence of digit
p (* (Math/log10 (/ (inc q) q)) 100) ; Benford expected percent
e (abs (- f p))]] ; error (difference)
(println (format "%3d %10.2f %10.2f %10.2f"
q
f
p
e)))))
; Generate fibonacci results
(def fib (lazy-cat [0N 1N] (map + fib (rest fib))))
;(def fib-digits (map (comp first str) (take 10000 fib)))
(def fib-digits (take 10000 fib))
(def header " found-% expected-% diff")
(println "Fibonacci Results")
(println header)
(show-benford-stats fib-digits)
;
; Universal Constants from Physics (using first column of data)
(println "Universal Constants from Physics")
(println header)
(let [
data-parser (fn [s]
(let [x (re-find #"\s{10}-?[0|/\.]*([1-9])" s)]
(if (not (nil? x)) ; Skips records without number
(second x)
x)))
input (slurp "http://physics.nist.gov/cuu/Constants/Table/allascii.txt")
y (for [line (line-seq (java.io.BufferedReader.
(java.io.StringReader. input)))]
(data-parser line))
z (filter identity y)]
(show-benford-stats z))
; Sunspots
(println "Sunspots average count per month since 1749")
(println header)
(let [
data-parser (fn [s]
(nth (re-find #"(.+?\s){3}([1-9])" s) 2))
; Sunspot data loaded from file (saved from ;https://solarscience.msfc.nasa.gov/greenwch/SN_m_tot_V2.0.txt")
; (note: attempting to load directly from url causes https Trust issues, so saved to file after loading to Browser)
input (slurp "SN_m_tot_V2.0.txt")
y (for [line (line-seq (java.io.BufferedReader.
(java.io.StringReader. input)))]
(data-parser line))]
(show-benford-stats y))
|
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 Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #C.23 | C# |
using Mpir.NET;
using System;
namespace Bernoulli
{
class Program
{
private static void bernoulli(mpq_t rop, uint n)
{
mpq_t[] a = new mpq_t[n + 1];
for (uint i = 0; i < n + 1; i++)
{
a[i] = new mpq_t();
}
for (uint m = 0; m <= n; ++m)
{
mpir.mpq_set_ui(a[m], 1, m + 1);
for (uint j = m; j > 0; --j)
{
mpir.mpq_sub(a[j - 1], a[j], a[j - 1]);
mpir.mpq_set_ui(rop, j, 1);
mpir.mpq_mul(a[j - 1], a[j - 1], rop);
}
mpir.mpq_set(rop, a[0]);
}
}
static void Main(string[] args)
{
mpq_t rop = new mpq_t();
mpz_t n = new mpz_t();
mpz_t d = new mpz_t();
for (uint i = 0; i <= 60; ++i)
{
bernoulli(rop, i);
if (mpir.mpq_cmp_ui(rop, 0, 1) != 0)
{
mpir.mpq_get_num(n, rop);
mpir.mpq_get_den(d, rop);
Console.WriteLine(string.Format("B({0, 2}) = {1, 44} / {2}", i, n, d));
}
}
Console.ReadKey();
}
}
}
|
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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Recursive_Binary_Search is
Not_Found : exception;
generic
type Index is range <>;
type Element is private;
type Array_Of_Elements is array (Index range <>) of Element;
with function "<" (L, R : Element) return Boolean is <>;
function Search (Container : Array_Of_Elements; Value : Element) return Index;
function Search (Container : Array_Of_Elements; Value : Element) return Index is
Mid : Index;
begin
if Container'Length > 0 then
Mid := (Container'First + Container'Last) / 2;
if Value < Container (Mid) then
if Container'First /= Mid then
return Search (Container (Container'First..Mid - 1), Value);
end if;
elsif Container (Mid) < Value then
if Container'Last /= Mid then
return Search (Container (Mid + 1..Container'Last), Value);
end if;
else
return Mid;
end if;
end if;
raise Not_Found;
end Search;
type Integer_Array is array (Positive range <>) of Integer;
function Find is new Search (Positive, Integer, Integer_Array);
procedure Test (X : Integer_Array; E : Integer) is
begin
New_Line;
for I in X'Range loop
Put (Integer'Image (X (I)));
end loop;
Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E)));
exception
when Not_Found =>
Put (" does not contain" & Integer'Image (E));
end Test;
begin
Test ((2, 4, 6, 8, 9), 2);
Test ((2, 4, 6, 8, 9), 1);
Test ((2, 4, 6, 8, 9), 8);
Test ((2, 4, 6, 8, 9), 10);
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 5);
end Test_Recursive_Binary_Search; |
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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BaCon | BaCon | DECLARE case$[] = { "tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }
FOR z = 0 TO UBOUND(case$)-1
result$ = EXPLODE$(case$[z], 1)
FOR y = 1 TO AMOUNT(result$)
FOR x = 1 TO LEN(case$[z])
IF TOKEN$(result$, y) <> MID$(case$[z], x, 1) AND TOKEN$(result$, x) = MID$(case$[z], x, 1) THEN result$ = EXCHANGE$(result$, x, y)
NEXT
NEXT
total = 0
FOR x = 1 TO AMOUNT(result$)
INCR total, IIF(MID$(case$[z], x, 1) = TOKEN$(result$, x), 1, 0)
NEXT
PRINT MERGE$(result$), ":", total
NEXT |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #E | E | ? def int8 := <type:java.lang.Byte>
# value: int8 |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Elixir | Elixir | # String creation
x = "hello world"
# String destruction
x = nil
# String assignment with a null byte
x = "a\0b"
IO.inspect x #=> <<97, 0, 98>>
IO.puts String.length(x) #=> 3
# string comparison
if x == "hello" do
IO.puts "equal"
else
IO.puts "not equal" #=> not equal
end
y = "bc"
if x < y do
IO.puts "#{x} is lexicographically less than #{y}" #=> a b is lexicographically less than bc
end
# string cloning
xx = x
IO.puts x == xx #=> true (same length and content)
# check if empty
if x=="" do
IO.puts "is empty"
end
if String.length(x)==0 do
IO.puts "is empty"
end
# append a byte
IO.puts x <> "\07" #=> a b 7
IO.inspect x <> "\07" #=> <<97, 0, 98, 0, 55>>
# substring
IO.puts String.slice("elixir", 1..3) #=> lix
IO.puts String.slice("elixir", 2, 3) #=> ixi
# replace bytes
IO.puts String.replace("a,b,c", ",", "-") #=> a-b-c
# string interpolation
a = "abc"
n = 100
IO.puts "#{a} : #{n}" #=> abc : 100
# join strings
a = "hel"
b = "lo w"
c = "orld"
IO.puts a <> b <> c #=> hello world |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #jq | jq | # input and output: {limits, count} where
# .limits holds an array defining the limits, and
# .count[$i] holds the count of bin $i, where bin[0] is the left-most bin
def bin($x):
(.limits | bsearch($x)) as $ix
| (if $ix > -1 then $ix + 1 else -1 - $ix end) as $i
| .count[$i] += 1;
# pretty-print for the structure defined at bin/1
def pp:
(.limits|length) as $length
| (range(0;$length) as $i
| "< \(.limits[$i]) => \(.count[$i] // 0)" ),
">= \(.limits[$length-1] ) => \(.count[$length] // 0)" ;
# Main program
reduce inputs as $x ({$limits, count: []}; bin($x))
| pp |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Julia | Julia | """Add the function Python has in its bisect library"""
function bisect_right(array, x, low = 1, high = length(array) + 1)
while low < high
middle = (low + high) ÷ 2
x < array[middle] ? (high = middle) : (low = middle + 1)
end
return low
end
""" Bin data according to (ascending) limits """
function bin_it(limits, data)
bins = zeros(Int, length(limits) + 1) # adds under/over range bins too
for d in data
bins[bisect_right(limits, d)] += 1
end
return bins
end
""" Pretty print the resulting bins and counts """
function bin_print(limits, bins)
println(" < $(lpad(limits[1], 3)) := $(lpad(bins[1], 3))")
for (lo, hi, count) in zip(limits, limits[2:end], bins[2:end])
println(">= $(lpad(lo, 3)) .. < $(lpad(hi, 3)) := $(lpad(count, 3))")
end
println(">= $(lpad(limits[end], 3)) := $(lpad(bins[end], 3))")
end
""" Test on data provided """
function testbins()
println("RC FIRST EXAMPLE:")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
println("\nRC SECOND EXAMPLE:")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
end
testbins()
|
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import strformat
import strutils
const Source = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
# Enumeration type for bases.
type Base* {.pure.} = enum A, C, G, T, Other = "other"
proc display*(dnaSeq: string) =
## Display a DNA sequence using EMBL format.
var counts: array[Base, Natural] # Count of bases.
for c in dnaSeq:
inc counts[parseEnum[Base]($c, Other)] # Use Other as default value.
# Display the SQ line.
var sqline = fmt"SQ {dnaSeq.len} BP; "
for (base, count) in counts.pairs:
sqline &= fmt"{count} {base}; "
echo sqline
# Display the sequence.
var idx = 0
var row = newStringOfCap(80)
var remaining = dnaSeq.len
while remaining > 0:
row.setLen(0)
row.add(" ")
# Add groups of 10 bases.
for group in 1..6:
let nextIdx = idx + min(10, remaining)
row.add(dnaSeq[idx..<nextIdx] & ' ')
dec remaining, nextIdx - idx
idx = nextIdx
if remaining == 0:
break
# Append the number of the last base in the row.
row.add(spaces(72 - row.len))
row.add(fmt"{idx:>8}")
echo row
# Add termination.
echo "//"
when isMainModule:
Source.display() |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
Task
"Pretty print" the sequence followed by a summary of the counts of each of the bases: (A, C, G, and T) in the sequence
print the total count of each base in the string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pascal | Pascal | program DNA_Base_Count;
{$IFDEF FPC}
{$MODE DELPHI}//String = AnsiString
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
const
dna =
'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG' +
'CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' +
'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT' +
'GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT' +
'CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG' +
'TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA' +
'TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT' +
'CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG' +
'TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC' +
'GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT';
var
CntIdx : array of NativeUint;
DNABases : String;
SumBaseTotal : NativeInt;
procedure OutFormatBase(var DNA: String;colWidth:NativeInt);
var
j: NativeInt;
Begin
j := 0;
Writeln(' DNA base sequence');
While j<Length(DNA) do
Begin
writeln(j:5,copy(DNA,j+1,colWidth):colWidth+2);
inc(j,colWidth);
end;
writeln;
end;
procedure Cnt(const DNA: String);
var
i,p :NativeInt;
Begin
SetLength(CntIdx,Length(DNABases));
i := 1;
while i <= Length(DNA) do
Begin
p := Pos(DNA[i],DNABases);
//found new base so extend list
if p = 0 then
Begin
DNABases := DNABases+DNA[i];
p := length(DNABases);
Setlength(CntIdx,p+1);
end;
inc(CntIdx[p]);
inc(i);
end;
Writeln('Base Count');
SumBaseTotal := 0;
For i := 1 to Length(DNABases) do
Begin
p := CntIdx[i];
inc(SumBaseTotal,p);
writeln(DNABases[i]:4,p:10);
end;
Writeln('Total base count ',SumBaseTotal);
writeln;
end;
var
TestDNA: String;
Begin
DNABases :='ACGT';// predefined
TestDNA := DNA;
OutFormatBase(TestDNA,50);
Cnt(TestDNA);
end. |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Action.21 | Action! | PROC PrintBinary(CARD v)
CHAR ARRAY a(16)
BYTE i=[0]
DO
a(i)=(v&1)+'0
i==+1
v=v RSH 1
UNTIL v=0
OD
DO
i==-1
Put(a(i))
UNTIL i=0
OD
RETURN
PROC Main()
CARD ARRAY data=[0 5 50 9000]
BYTE i
CARD v
FOR i=0 TO 3
DO
v=data(i)
PrintF("Output for %I is ",v)
PrintBinary(v)
PutE()
OD
RETURN |
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.
| #F.23 | F# | let inline bresenham fill (x0, y0) (x1, y1) =
let steep = abs(y1 - y0) > abs(x1 - x0)
let x0, y0, x1, y1 =
if steep then y0, x0, y1, x1 else x0, y0, x1, y1
let x0, y0, x1, y1 =
if x0 > x1 then x1, y1, x0, y0 else x0, y0, x1, y1
let dx, dy = x1 - x0, abs(y1 - y0)
let s = if y0 < y1 then 1 else -1
let rec loop e x y =
if x <= x1 then
if steep then fill y x else fill x y
if e < dy then
loop (e-dy+dx) (x+1) (y+s)
else
loop (e-dy) (x+1) y
loop (dx/2) x0 y0 |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #zkl | zkl | var [const] bases="ACGT", lbases=bases.toLower();
dna:=(190).pump(Data().howza(3),(0).random.fp(0,4),bases.get); // bucket of bytes
foreach s,m in (T("Original","Mutated").zip(T(True,False))){
println("\n",s," DNA strand:"); dnaPP(dna);
println("Base Counts: ", dna.len()," : ",
dna.text.toUpper().counts() // ("A",5, "C",10, ...)
.pump(String,Void.Read,"%s(%d) ".fmt));
if(m) mutate(dna,10,True);
}
fcn mutate(dna,count=1,verbose=False){
if(verbose) println("Mutating:");
do(count){
n,rb := (0).random(dna.len()), lbases[(0).random(4)];
switch( (0).random(3) ){
case(0){ if(verbose) println("Change[%d] '%s' to '%s'".fmt(n,dna.charAt(n),rb));
dna[n]=rb;
}
case(1){ if(verbose) println("Delete[%d] '%s'".fmt(n,dna.charAt(n)));
dna.del(n);
}
else{ if(verbose) println("Insert[%d] '%s'".fmt(n,rb));
dna.insert(n,rb);
}
}
}
}
fcn dnaPP(dna,N=50){
[0..*,50].zipWith(fcn(n,bases){ println("%6d: %s".fmt(n,bases.concat())) },
dna.walker().walk.fp(50)).pump(Void); // .pump forces the iterator
} |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
Delete the chosen base at the position.
Insert another base randomly chosen from A,C, G, or T into the sequence at that position.
Randomly generate a test DNA sequence of at least 200 bases
"Pretty print" the sequence and a count of its size, and the count of each base in the sequence
Mutate the sequence ten times.
"Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
Extra credit
Give more information on the individual mutations applied.
Allow mutations to be weighted and/or chosen. | #Rust | Rust |
use rand::prelude::*;
use std::collections::HashMap;
use std::fmt::{Display, Formatter, Error};
pub struct Seq<'a> {
alphabet: Vec<&'a str>,
distr: rand::distributions::Uniform<usize>,
pos_distr: rand::distributions::Uniform<usize>,
seq: Vec<&'a str>,
}
impl Display for Seq<'_> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let pretty: String = self.seq
.iter()
.enumerate()
.map(|(i, nt)| if (i + 1) % 60 == 0 { format!("{}\n", nt) } else { nt.to_string() })
.collect();
let counts_hm = self.seq
.iter()
.fold(HashMap::<&str, usize>::new(), |mut m, nt| {
*m.entry(nt).or_default() += 1;
m
});
let mut counts_vec: Vec<(&str, usize)> = counts_hm.into_iter().collect();
counts_vec.sort_by(|a, b| a.0.cmp(&b.0));
let counts_string = counts_vec
.iter()
.fold(String::new(), |mut counts_string, (nt, count)| {
counts_string += &format!("{} = {}\n", nt, count);
counts_string
});
write!(f, "Seq:\n{}\n\nLength: {}\n\nCounts:\n{}", pretty, self.seq.len(), counts_string)
}
}
impl Seq<'_> {
pub fn new(alphabet: Vec<&str>, len: usize) -> Seq {
let distr = rand::distributions::Uniform::new_inclusive(0, alphabet.len() - 1);
let pos_distr = rand::distributions::Uniform::new_inclusive(0, len - 1);
let seq: Vec<&str> = (0..len)
.map(|_| {
alphabet[thread_rng().sample(distr)]
})
.collect();
Seq { alphabet, distr, pos_distr, seq }
}
pub fn insert(&mut self) {
let pos = thread_rng().sample(self.pos_distr);
let nt = self.alphabet[thread_rng().sample(self.distr)];
println!("Inserting {} at position {}", nt, pos);
self.seq.insert(pos, nt);
}
pub fn delete(&mut self) {
let pos = thread_rng().sample(self.pos_distr);
println!("Deleting {} at position {}", self.seq[pos], pos);
self.seq.remove(pos);
}
pub fn swap(&mut self) {
let pos = thread_rng().sample(self.pos_distr);
let cur_nt = self.seq[pos];
let new_nt = self.alphabet[thread_rng().sample(self.distr)];
println!("Replacing {} at position {} with {}", cur_nt, pos, new_nt);
self.seq[pos] = new_nt;
}
}
fn main() {
let mut seq = Seq::new(vec!["A", "C", "T", "G"], 200);
println!("Initial sequnce:\n{}", seq);
let mut_distr = rand::distributions::Uniform::new_inclusive(0, 2);
for _ in 0..10 {
let mutation = thread_rng().sample(mut_distr);
if mutation == 0 {
seq.insert()
} else if mutation == 1 {
seq.delete()
} else {
seq.swap()
}
}
println!("\nMutated sequence:\n{}", seq);
}
|
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Rust | Rust |
/* Naive Rust implementation of RosettaCode's Bitmap/Flood fill excercise.
*
* For the sake of simplicity this code reads PPM files (format specification can be found here: http://netpbm.sourceforge.net/doc/ppm.html ).
* The program assumes that the image has been created by GIMP in PPM ASCII mode and panics at any error.
*
* Also this program expects the input file to be in the same directory as the executable and named
* "input.ppm" and outputs a file in the same directory under the name "output.ppm".
*
*/
use std::fs::File; // Used for creating/opening files.
use std::io::{BufReader, BufRead, Write}; // Used for reading/writing files.
fn read_image(filename: String) -> Vec<Vec<(u8,u8,u8)>> {
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut lines = reader.lines();
let _ = lines.next().unwrap(); // Skip P3 signature.
let _ = lines.next().unwrap(); // Skip GIMP comment.
let dimensions: (usize, usize) = {
let line = lines.next().unwrap().unwrap();
let values = line.split_whitespace().collect::<Vec<&str>>();
// We turn the &str vector that holds the width & height of the image into an usize tuplet.
(values[0].parse::<usize>().unwrap(),values[1].parse::<usize>().unwrap())
};
let _ = lines.next().unwrap(); // Skip maximum color value (we assume 255).
let mut image_data = Vec::with_capacity(dimensions.1);
for y in 0..dimensions.1 {
image_data.push(Vec::new());
for _ in 0..dimensions.0 {
// We read the R, G and B components and put them in the image_data vector.
image_data[y].push((lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
lines.next().unwrap().unwrap().parse::<u8>().unwrap(),
lines.next().unwrap().unwrap().parse::<u8>().unwrap()));
}
}
image_data
}
fn write_image(image_data: Vec<Vec<(u8,u8,u8)>>) {
let mut file = File::create(format!("./output.ppm")).unwrap();
// Signature, then width and height, then 255 as max color value.
write!(file, "P3\n{} {}\n255\n", image_data.len(), image_data[0].len()).unwrap();
for row in &image_data {
// For performance reasons, we reserve a String with the necessary length for a line and
// fill that up before writing it to the file.
let mut line = String::with_capacity(row.len()*6); // 6 = r(space)g(space)b(space)
for (r,g,b) in row {
// &* is used to turn a String into a &str as needed by push_str.
line.push_str(&*format!("{} {} {} ", r,g,b));
}
write!(file, "{}", line).unwrap();
}
}
fn flood_fill(x: usize, y: usize, target: &(u8,u8,u8), replacement: &(u8,u8,u8), image_data: &mut Vec<Vec<(u8,u8,u8)>>) {
if &image_data[y][x] == target {
image_data[y][x] = *replacement;
if y > 0 {flood_fill(x,y-1, &target, &replacement, image_data);}
if x > 0 {flood_fill(x-1,y, &target, &replacement, image_data);}
if y < image_data.len()-1 {flood_fill(x,y+1, &target, &replacement, image_data);}
if x < image_data[0].len()-1 {flood_fill(x+1,y, &target, &replacement, image_data);}
}
}
fn main() {
let mut data = read_image(String::from("./input.ppm"));
flood_fill(1,50, &(255,255,255), &(0,255,0), &mut data); // Fill the big white circle with green.
flood_fill(40,35, &(0,0,0), &(255,0,0), &mut data); // Fill the small black circle with red.
write_image(data);
} |
http://rosettacode.org/wiki/Bitmap/Flood_fill | Bitmap/Flood fill | Implement a flood fill.
A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color).
Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
| #Scala | Scala | import java.awt.Color
import scala.collection.mutable
object Flood {
def floodFillStack(bm:RgbBitmap, x: Int, y: Int, targetColor: Color): Unit = {
// validate
if (bm.getPixel(x,y) == targetColor) return
// vars
val oldColor = bm.getPixel(x,y)
val pixels = new mutable.Stack[(Int,Int)]
// candy coating methods
def paint(fx: Int, fy:Int) = bm.setPixel(fx,fy,targetColor)
def old(cx: Int, cy: Int): Boolean = bm.getPixel(cx,cy) == oldColor
def push(px: Int, py: Int) = pixels.push((px,py))
// starting point
push(x,y)
// work
while (pixels.nonEmpty) {
val (x, y) = pixels.pop()
var y1 = y
while (y1 >= 0 && old(x, y1)) y1 -= 1
y1 += 1
var spanLeft = false
var spanRight = false
while (y1 < bm.height && old(x, y1)) {
paint(x,y1)
if (x > 0 && spanLeft != old(x-1,y1)) {
if (old(x - 1, y1)) push(x - 1, y1)
spanLeft = !spanLeft
}
if (x < bm.width - 1 && spanRight != old(x+1,y1)) {
if (old(x + 1, y1)) push(x + 1, y1)
spanRight = !spanRight
}
y1 += 1
}
}
}
} |
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
| #Modula-3 | Modula-3 | TYPE BOOLEAN = {FALSE, 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
| #Monte | Monte |
def example(input :boolean):
if input:
return "Input was true!"
return "Input was 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
| #MUMPS | MUMPS | a = true
b = false
if a
println "a is true"
else if b
println "b is true"
end |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #langur | langur | val .box = ["North", "North by east", "North-northeast", "Northeast by north",
"Northeast", "Northeast by east", "East-northeast", "East by north",
"East", "East by south", "East-southeast", "Southeast by east",
"Southeast", "Southeast by south", "South-southeast", "South by east",
"South", "South by west", "South-southwest", "Southwest by south",
"Southwest", "Southwest by west", "West-southwest", "West by south",
"West", "West by north", "West-northwest", "Northwest by west",
"Northwest", "Northwest by north", "North-northwest", "North by west"]
val .angles = [
0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38,
101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62,
185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0,
286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]
writeln "index degrees compass point"
writeln "----- ------- -------------"
for .phi in .angles {
val .i = truncate(.phi x 32 / 360 + 0.5) rem 32 + 1
writeln $"\.i:5; \.phi:r2:6; \.box[.i];"
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #E | E | def bitwise(a :int, b :int) {
println(`Bitwise operations:
a AND b: ${a & b}
a OR b: ${a | b}
a XOR b: ${a ^ b}
NOT a: " + ${~a}
a left shift b: ${a << b}
a right shift b: ${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 pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #Erlang | Erlang |
-module(ros_bitmap).
-export([new/2, fill/2, set_pixel/3, get_pixel/2]).
-record(bitmap, {
pixels = nil,
shape = {0, 0}
}).
new(Width, Height) ->
#bitmap{pixels=array:new(Width * Height, {default, <<0:8, 0:8, 0:8>>}), shape={Width, Height}}.
fill(#bitmap{shape={Width, Height}}, {rgb, R, G, B}) ->
#bitmap{
pixels=array:new(Width * Height, {default, <<R:8, G:8, B:8>>}),
shape={Width, Height}}.
set_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}}=Bitmap, {at, X, Y}, {rgb, R, G, B}) ->
Index = X + Y * Width,
Bitmap#bitmap{pixels=array:set(Index, <<R:8, G:8, B:8>>, Pixels)}.
get_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}}, {at, X, Y}) ->
Index = X + Y * Width,
<<R:8, G:8, B:8>> = array:get(Index, Pixels),
{rgb, R, G, B}.
|
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} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Cowgol | Cowgol | include "cowgol.coh";
typedef B is uint32;
typedef I is intptr;
sub bellIndex(row: I, col: I): (addr: I) is
addr := (row * (row - 1) / 2 + col) * @bytesof B;
end sub;
sub getBell(row: I, col: I): (bell: B) is
bell := [LOMEM as [B] + bellIndex(row, col)];
end sub;
sub setBell(row: I, col: I, bell: B) is
[LOMEM as [B] + bellIndex(row, col)] := bell;
end sub;
sub bellTriangle(n: I) is
var length := n * (n + 1) / 2;
var bytes := length * @bytesof B;
if HIMEM - LOMEM < bytes then
print("not enough memory\n");
ExitWithError();
end if;
MemZero(LOMEM, bytes);
setBell(1, 0, 1);
var i: I := 2;
while i <= n loop
setBell(i, 0, getBell(i-1, i-2));
var j: I := 1;
while j < i loop
var value := getBell(i, j-1) + getBell(i-1, j-1);
setBell(i, j, value);
j := j + 1;
end loop;
i := i + 1;
end loop;
end sub;
const ROWS := 15;
bellTriangle(ROWS);
print("First fifteen Bell numbers:\n");
var i: I := 1;
while i <= ROWS loop
print_i32(i as uint32);
print(": ");
print_i32(getBell(i, 0) as uint32);
print_nl();
i := i + 1;
end loop;
print("\nThe first ten rows of Bell's triangle:\n");
i := 1;
while i <= 10 loop
var j: I := 0;
loop
print_i32(getBell(i, j) as uint32);
j := j + 1;
if j == i then break;
else print(", ");
end if;
end loop;
i := i + 1;
print_nl();
end loop; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.