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/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] ...
#Python
Python
from bisect import bisect_right   def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) # adds under/over range bins too for d in data: bins[bisect_right(limits, d)] += 1 return bins   def bin_print(limits: list, bins: list)...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Racket
Racket
#lang racket   (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+))))) ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Raku
Raku
my $dna = join '', lines q:to/END/; CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGT...
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 ...
#ALGOL_W
ALGOL W
begin  % prints an integer in binary - the number must be greater than zero  % procedure printBinaryDigits( integer value n ) ; begin if n not = 0 then begin printBinaryDigits( n div 2 ); writeon( if n rem 2 = 1 then "1" else "0" ) end end binaryDigits ;    %...
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.
#Go
Go
package raster   // Line draws line by Bresenham's algorithm. func (b *Bitmap) Line(x0, y0, x1, y1 int, p Pixel) { // implemented straight from WP pseudocode dx := x1 - x0 if dx < 0 { dx = -dx } dy := y1 - y0 if dy < 0 { dy = -dy } var sx, sy int if x0 < x1 { ...
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
#ooRexx
ooRexx
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Order
Order
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
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...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Locale 1033 'change decimal point char to dot. Form 80,50 ' set console to 80 characters by 50 lines \\ Function heading() get a positive double as degrees and return the compass index (1 for North) Function heading(d) { d1=d div 11.25 if d1 mod 3...
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 |...
#Factor
Factor
"a=" "b=" [ write readln string>number ] bi@ { [ bitand "a AND b: " write . ] [ bitor "a OR b: " write . ] [ bitxor "a XOR b: " write . ] [ drop bitnot "NOT a: " write . ] [ abs shift "a asl b: " write . ] [ neg shift "a asr b: " write . ] } 2cleave
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Fortran
Fortran
Screenres 320, 240, 8 Dim Shared As Integer w, h Screeninfo w, h Const As Ubyte cyan = 3 Const As Ubyte red = 4   Sub rellenar(c As Integer) Line (0,0) - (w/3, h/3), red, BF End Sub   Sub establecePixel(x As Integer, y As Integer, c As Integer) Pset (x,y), cyan End Sub   rellenar(12) establecePixel(10,10...
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...
#Haskell
Haskell
bellTri :: [[Integer]] bellTri = let f xs = (last xs, xs) in map snd (iterate (f . uncurry (scanl (+))) (1, [1]))   bell :: [Integer] bell = map head bellTri   main :: IO () main = do putStrLn "First 10 rows of Bell's Triangle:" mapM_ print (take 10 bellTri) putStrLn "\nFirst 15 Bell numbers:" mapM_ print ...
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...
#J
J
  bell=: ([: +/\ (,~ {:))&.>@:{:   ,. bell^:(<5) <1 +--------------+ |1 | +--------------+ |1 2 | +--------------+ |2 3 5 | +--------------+ |5 7 10 15 | +--------------+ |15 20 27 37 52| +--------------+   {.&> bell^:(<15) <1 1 1 2 5 15 52 203 877 4140 21147 115975 678570 421...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#F.23
F#
open System   let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I) let fibFirstNumbers nth = fibonacci |> Seq.take nth |> Seq.map (fun n -> n.ToString().[0] |> string |> Int32.Parse)   let fibFirstNumbersFrequency nth = let firstNumbers = fibFirstNumbers nth |> Seq.toList let counts = firs...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#EchoLisp
EchoLisp
  (lib 'bigint) ;; lerge numbers (lib 'gloops) ;; classes   (define-class Rational null ((a :initform #0) (b :initform #1))) (define-method tostring (Rational) (lambda (r) (format "%50d / %d" r.a r.b))) (define-method normalize (Rational) (lambda (r) ;; divide a and b by gcd (let ((g (gcd r.a r.b))) (set! r.a (/...
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#AutoHotkey
AutoHotkey
array := "1,2,4,6,8,9" StringSplit, A, array, `, ; creates associative array MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive MsgBox % A%x% MsgBox % x := BinarySearchI(A, A0, 4) ; Iterative MsgBox % A%x%   BinarySearch(A, value, low, high) { ; A0 contains length of array If (high < low) ; A1, A2, ...
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...
#D
D
import std.stdio, std.random, std.algorithm, std.conv, std.range, std.traits, std.typecons;   auto bestShuffle(S)(in S orig) @safe if (isSomeString!S) { static if (isNarrowString!S) immutable o = orig.dtext; else alias o = orig;   auto s = o.dup; s.randomShuffle;   foreach (im...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#J
J
name=: ''
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Java
Java
import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays;   public class MutableByteString {   private byte[] bytes; private int length;   public MutableByteString(byte... bytes) { setInternal(bytes); }   public int length() { return len...
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] ...
#R
R
limits1 <- c(23, 37, 43, 53, 67, 83) data1 <- c(95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55) limits2 <- c(14, 18, 249, 312, 389, 392, 513, 591, 634, 720) data2 <- c(445,814,519,697,700,130,255,889,481,122,932,7...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#REXX
REXX
/*REXX program finds the number of each base in a DNA string (along with a total). */ parse arg dna . if dna=='' | dna=="," then dna= 'cgtaaaaaattacaacgtcctttggctatctcttaaactcctgctaaatg' , 'ctcgtgctttccaattatgtaagcgttccgagacggggtggtcgattctg' , ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Ring
Ring
  dna = "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + ...
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 ...
#AppleScript
AppleScript
---------------------- BINARY STRING -----------------------   -- showBin :: Int -> String on showBin(n) script binaryChar on |λ|(n) text item (n + 1) of "01" end |λ| end script showIntAtBase(2, binaryChar, n, "") end showBin     --------------------------- TEST -----------------...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Haskell
Haskell
module Bitmap.Line(line) where   import Bitmap import Control.Monad import Control.Monad.ST import qualified Data.STRef   var = Data.STRef.newSTRef get = Data.STRef.readSTRef mutate = Data.STRef.modifySTRef   line :: Color c => Image s c -> Pixel -> Pixel -> c -> ST s () line i (Pixel (xa, ya)) (Pixel (xb, yb)) c = do ...
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
#Oz
Oz
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PARI.2FGP
PARI/GP
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Map[List[Part[#,1], dirs[[Part[#,1]]], ToString@Part[#,2]<>"°"]&, Map[{Floor[Mod[ #+5.625 , 360]/11.25]+1,#}&,input] ]//TableForm
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 |...
#FALSE
FALSE
10 3 \$@$@$@$@\ { 3 copies } "a & b = "&." a | b = "|." ~a = "%~." "
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#FreeBASIC
FreeBASIC
Screenres 320, 240, 8 Dim Shared As Integer w, h Screeninfo w, h Const As Ubyte cyan = 3 Const As Ubyte red = 4   Sub rellenar(c As Integer) Line (0,0) - (w/3, h/3), red, BF End Sub   Sub establecePixel(x As Integer, y As Integer, c As Integer) Pset (x,y), cyan End Sub   rellenar(12) establecePixel(10,10...
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...
#Java
Java
import java.util.ArrayList; import java.util.List;   public class Bell { private static class BellTriangle { private List<Integer> arr;   BellTriangle(int n) { int length = n * (n + 1) / 2; arr = new ArrayList<>(length); for (int i = 0; i < length; ++i) { ...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Factor
Factor
USING: assocs compiler.tree.propagation.call-effect formatting kernel math math.functions math.statistics math.text.utils sequences ; IN: rosetta-code.benfords-law   : expected ( n -- x ) recip 1 + log10 ;   : next-fib ( vec -- vec' ) [ last2 ] keep [ + ] dip [ push ] keep ;   : data ( -- seq ) V{ 1 1 } clone 998 [...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Forth
Forth
: 3drop drop 2drop ; : f2drop fdrop fdrop ;   : int-array create cells allot does> swap cells + ;   : 1st-fib 0e 1e ; : next-fib ftuck f+ ;   : 1st-digit ( fp -- n ) pad 6 represent 3drop pad c@ [char] 0 - ;   10 int-array counts   : tally 0 counts 10 cells erase 1st-fib 1000 0 DO 1 fdup...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Elixir
Elixir
defmodule Bernoulli do defmodule Rational do import Kernel, except: [div: 2]   defstruct numerator: 0, denominator: 1   def new(numerator, denominator\\1) do sign = if numerator * denominator < 0, do: -1, else: 1 {numerator, denominator} = {abs(numerator), abs(denominator)} gcd = gcd(num...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#F.23
F#
  open MathNet.Numerics open System open System.Collections.Generic   let calculateBernoulli n = let ℚ(x) = BigRational.FromInt x let A = Array.init<BigRational> (n+1) (fun x -> ℚ(x+1))   for m in [1..n] do A.[m] <- ℚ(1) / (ℚ(m) + ℚ(1)) for j in [m..(-1)..1] do A.[j-1] <- ℚ(j) * ...
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#AWK
AWK
function binary_search(array, value, left, right, middle) { if (right < left) return 0 middle = int((right + left) / 2) if (value == array[middle]) return 1 if (value < array[middle]) return binary_search(array, value, left, middle - 1) return binary_search(array, value, middle + 1, r...
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...
#Delphi
Delphi
  program Best_shuffle;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   type TShuffledString = record private original: string; Shuffled: TStringBuilder; ignoredChars: Integer; procedure DetectIgnores; procedure Shuffle; procedure Swap(pos1, pos2: Integer); ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#JavaScript
JavaScript
//String creation var str=''; //or str2=new String();     //String assignment str="Hello"; //or str2=', Hey there'; //can use " or ' str=str+str2;//concantenates //string deletion delete str2;//this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has bee...
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] ...
#Racket
Racket
#lang racket   (define (find-bin-index limits v) (let inner ((l 0) (r (vector-length limits))) (let ((m (quotient (+ l r) 2))) (if (< v (vector-ref limits m)) (if (= m l) l (inner l m)) (if (= m (sub1 r)) r (inner m r))))))   (define ((bin-given-limits! limits) data (bins (make-vector (a...
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] ...
#Raku
Raku
  sub bin_it ( @limits, @data ) { my @ranges = ( -Inf, |@limits, Inf ).rotor( 2 => -1 ).map: { .[0] ..^ .[1] }; my @binned = @data.classify(-> $d { @ranges.grep(-> $r { $d ~~ $r }) }); my %counts = @binned.map: { .key => .value.elems }; return @ranges.map: { $_ => ( %counts{$_} // 0 ) }; } sub bin_forma...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Ruby
Ruby
dna = <<DNA_STR CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Rust
Rust
  use std::collections::HashMap;   fn main() { let dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG...
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 ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program binarydigit.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data   sMessAffBin: .ascii "The decimal value " sZoneDec: .space 12,' ' .ascii " should produce an output of " sZoneBin: .space 36,' ' ...
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.
#J
J
thru=: <./ + -~ i.@+ _1 ^ > NB. integers from x through y   NB.*getBresenhamLine v Returns points for a line given start and end points NB. y is: y0 x0 ,: y1 x1 getBresenhamLine=: monad define steep=. ([: </ |@-~/) y points=. |."1^:steep y slope=. %~/ -~/ points ypts=. thru/ {."1 points xpts=. ({: + 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
#Pascal
Pascal
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Perl
Perl
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function b = compassbox(d) b = ceil(mod(d+360/64,360)*32/360); 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 |...
#Forth
Forth
: arshift 0 ?do 2/ loop ; \ 2/ is an arithmetic shift right by one bit (2* shifts left one bit) : bitwise ( a b -- ) cr ." a = " over . ." b = " dup . cr ." a and b = " 2dup and . cr ." a or b = " 2dup or . cr ." a xor b = " 2dup xor . cr ." not a = " over invert . cr ." a shl b = " 2dup lshif...
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Go
Go
package main   import ( "bytes" "fmt" "image" "image/color" "image/draw" "image/png" )   func main() { // A rectangle from 0,0 to 300,240. r := image.Rect(0, 0, 300, 240)   // Create an image im := image.NewNRGBA(r)   // set some color variables for convience var ( red = color.RGBA{0xff, 0x00, 0x00, 0xff...
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...
#jq
jq
# nth Bell number def bell: . as $n | if $n < 0 then "non-negative integer expected" elif $n < 2 then 1 else reduce range(1; $n) as $i ([1]; reduce range(1; $i) as $j (.; .[$i - $j] as $x | .[$i - $j - 1] += $x ) | .[$i] = .[0] + .[$i - 1] ) | .[$n - 1] end;   # The...
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...
#Julia
Julia
""" bellnum(n) Compute the ``n``th Bell number. """ function bellnum(n::Integer) if n < 0 throw(DomainError(n)) elseif n < 2 return 1 end list = Vector{BigInt}(undef, n) list[1] = 1 for i = 2:n for j = 1:i - 2 list[i - j - 1] += list[i - j] end ...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Fortran
Fortran
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00   a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.3...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#FreeBASIC
FreeBASIC
' version 27-10-2016 ' compile with: fbc -s console   #Define max 1000 ' total number of Fibonacci numbers #Define max_sieve 15485863 ' should give 1,000,000   #Include Once "gmp.bi" ' uses the GMP libary   Dim As ZString Ptr z_str Dim As ULong n, d ReDim As ULong digit(1 To 9) Dim As Double expect, found   Dim...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Factor
Factor
IN: scratchpad [ 0 1 1 "%2d : %d / %d\n" printf 1 -1 2 "%2d : %d / %d\n" printf 30 iota [ 1 + 2 * dup bernoulli [ numerator ] [ denominator ] bi "%2d : %d / %d\n" printf ] each ] time 0 : 1 / 1 1 : -1 / 2 2 : 1 / 6 4 : -1 / 30 6 : 1 / 42 8 : -1 / 30 10 : 5 / 66 12 ...
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Axe
Axe
Lbl BSEARCH 0→L r₃-1→H While L≤H (L+H)/2→M If {L+M}>r₂ M-1→H ElseIf {L+M}<r₂ M+1→L Else M Return End End -1 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...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   extension op { get Shuffled() { var original := self.toArray(); var shuffled := self.toArray();   for (int i := 0, i < original.Length, i += 1) { for (int j := 0, j < original.Length, j += 1) { ...
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Erlang
Erlang
  -module( best_shuffle ).   -export( [sameness/2, string/1, task/0] ).   sameness( String1, String2 ) -> lists:sum( [1 || {X, X} <- lists:zip(String1, String2)] ).   string( String ) -> {"", String, Acc} = lists:foldl( fun different/2, {lists:reverse(String), String, []}, String ), lists:reverse( Acc ).   task() -> ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#jq
jq
# If the input is a valid representation of a binary string # then pass it along: def check_binary: . as $a | reduce .[] as $x ($a; if $x | (type == "number" and . == floor and 0 <= . and . <= 255) then $a else error("\(.) is an invalid representation of a byte") end );
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Julia
Julia
  # String assignment. Creation and garbage collection are automatic. a = "123\x00 abc " # strings can contain bytes that are not printable in the local font b = "456" * '\x09' c = "789" println(a) println(b) println(c)   # string comparison println("(a == b) is $(a == b)")   # String copying. A = a B = b C = c printl...
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] ...
#REXX
REXX
/*REXX program counts how many numbers of a set that fall in the range of each bin. */ lims= 23 37 43 53 67 83 /* ◄■■■■■■1st set of bin limits & data.*/ 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 ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Swift
Swift
import Foundation   let dna = """ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAA...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Tcl
Tcl
namespace path ::tcl::mathop   proc process {data {width 50}} { set len [string length $data] set addrwidth [string length [* [/ $len $width] $width]] for {set i 0} {$i < $len} {incr i $width} { puts "[format %${addrwidth}u $i] [string range $data $i $i+[- $width 1]]" } puts "\nBase count:" foreach base {A C G ...
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 ...
#Arturo
Arturo
print as.binary 5 print as.binary 50 print as.binary 9000
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.
#Java
Java
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants;   public class Bresenham {   public static void main(String[] args) { SwingUtilities.invokeLater(Bresenham:...
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
#Phix
Phix
with javascript_semantics for i=1 to 3 do integer c = (i==2), -- fine d = (c==1), -- oops e = (c==true), -- fine f = equal(c,1) -- fine, ditto equal(c,true) printf(1,"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n", {i, c, c, d,...
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
#PHP
PHP
go ?=> member(N,1..5), println(N), fail, % or false/0 to get other solutions nl. go => true.
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...
#Modula-2
Modula-2
MODULE BoxTheCompass; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,Write,ReadChar;   PROCEDURE expand(cp : ARRAY OF CHAR); VAR i : INTEGER = 0; BEGIN WHILE cp[i] # 0C DO IF i=0 THEN CASE cp[i] OF 'N': WriteString("...
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 |...
#Fortran
Fortran
integer :: i, j = -1, k = 42 logical :: a   i = bit_size(j) ! returns the number of bits in the given INTEGER variable   ! bitwise boolean operations on integers i = iand(k, j) ! returns bitwise AND of K and J i = ior(k, j) ! returns bitwise OR of K and J i = ieor(k, j) ! returns bitwise EXC...
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Haskell
Haskell
module Bitmap(module Bitmap) where   import Control.Monad import Control.Monad.ST import Data.Array.ST   newtype Pixel = Pixel (Int, Int) deriving Eq   instance Ord Pixel where compare (Pixel (x1, y1)) (Pixel (x2, y2)) = case compare y1 y2 of EQ -> compare x1 x2 v -> v   instance Ix...
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...
#Kotlin
Kotlin
class BellTriangle(n: Int) { private val arr: Array<Int>   init { val length = n * (n + 1) / 2 arr = Array(length) { 0 }   set(1, 0, 1) for (i in 2..n) { set(i, 0, get(i - 1, i - 2)) for (j in 1 until i) { val value = get(i, j - 1) + get(i ...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math" )   func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] }   func main() { show(Fib1000(), "First 1000 Fibonacci numbers") }   func show(c []float64, title string) { var f [9]int...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Fermat
Fermat
Func Bern(m) = Sigma<k=0,m>[Sigma<v=0,k>[(-1)^v*Bin(k,v)*(v+1)^m/(k+1)]].; for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#BASIC
BASIC
FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer DIM middle AS Integer   IF hi < lo THEN binary_search = 0 ELSE middle = (hi + lo) / 2 SELECT CASE value CASE IS < array(middle) binary_search = binary_search(array(), value, lo, middle-1) ...
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#FreeBASIC
FreeBASIC
  Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}   Function bestShuffle(s1 As String) As String Dim As String s2 = s1 Dim As Integer i, j, i1, j1 For i = 1 To Len(s2) For j = 1 To Len(s2) If (i <> j) And (Mid(s2,i,1) <> Mid(s1,j,1)) And (Mid(s2,j,1) <> Mi...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Kotlin
Kotlin
class ByteString(private val bytes: ByteArray) : Comparable<ByteString> { val length get() = bytes.size   fun isEmpty() = bytes.isEmpty()   operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes)   operator fun plus(byte: Byte) = ByteString(bytes + byte)   operator fun get...
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] ...
#Ring
Ring
  limit = [0, 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] data = sort(data) dn = list(len(limit)) see "Example 1:" + nl + nl limits(limit,data,dn) see nl   limit = [0, 14...
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] ...
#Ruby
Ruby
Test = Struct.new(:limits, :data) tests = Test.new( [23, 37, 43, 53, 67, 83], [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]), Test.new( [14, 18, 249, 312, 389, 392, 513, 59...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Vlang
Vlang
fn main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGA...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Wren
Wren
import "/fmt" for Fmt import "/sort" for Sort import "/trait" for Stepped   var dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAAC...
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 ...
#AutoHotkey
AutoHotkey
MsgBox % NumberToBinary(5) ;101 MsgBox % NumberToBinary(50) ;110010 MsgBox % NumberToBinary(9000) ;10001100101000   NumberToBinary(InputNumber) { While, InputNumber Result := (InputNumber & 1) . Result, InputNumber >>= 1 Return, Result }
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.
#JavaScript
JavaScript
function bline(x0, y0, x1, y1) {   var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1; var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1; var err = (dx>dy ? dx : -dy)/2;   while (true) { setPixel(x0,y0); if (x0 === x1 && y0 === y1) break; var e2 = err; if (e2 > -dx) { err -= dy; x0 += sx; } ...
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
#Picat
Picat
go ?=> member(N,1..5), println(N), fail, % or false/0 to get other solutions nl. go => 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
#PicoLisp
PicoLisp
  > 0; (3) Result: 0 > false; (4) Result: 0 > 0; (6) Result: 0 > !true; (7) Result: 0 > true; (8) Result: 1 > 1; (9) Result: 1 >  
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#MUMPS
MUMPS
BOXING(DEGREE)  ;This takes in a degree heading, nominally from 0 to 360, and returns the compass point name. QUIT:((DEGREE<0)||(DEGREE>360)) "land lubber can't read a compass" NEW DIRS,UNP,UNPACK,SEP,DIR,DOS,D,DS,I,F SET DIRS="N^NbE^N-NE^NEbN^NE^NEbE^E-NE^EbN^E^EbS^E-SE^SEbE^SE^SEbS^S-SE^SbE^" SET DIRS=DIRS_"S^SbW...
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 |...
#Free_Pascal
Free Pascal
program Bitwise; {$mode objfpc} var // Pascal uses a native int type as a default literal type // Make sure the operants work on an exact type. x:shortint = 2; y:ShortInt = 3; begin Writeln('2 and 3 = ', x and y); Writeln('2 or 3 = ', x or y); Writeln('2 xor 3 = ', x xor y); Writeln('not 2 = ', not x); ...
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Icon_and_Unicon
Icon and Unicon
procedure makebitmap(width,height) return open("bitmap", "g", "canvas=hidden", "size="||width||","||height) end procedure fillimage(w,color) Fg(w,color) FillRectangle(w) end procedure setpixel(w,x,y,color) Fg(w,color) DrawPixel(x,y) end procedure getpixel(w,x,y) return Pixel(w,x,y) 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...
#Little_Man_Computer
Little Man Computer
  // Little Man Computer, for Rosetta Code. // Calculate Bell numbers, using a 1-dimensional array and addition. // // After the calculation of B_n (n > 0), the array contains n elements, // of which B_n is the first. Example to show calculation of B_(n+1): // After calc. of B_3 = 5, array holds: 5, 3, 2 // Exte...
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...
#Lua
Lua
-- Bell numbers in Lua -- db 6/11/2020 (to replace missing original)   local function bellTriangle(n) local tri = { {1} } for i = 2, n do tri[i] = { tri[i-1][i-1] } for j = 2, i do tri[i][j] = tri[i][j-1] + tri[i-1][j-1] end end return tri end   local N = 25 -- in lieu of 50, practical limit w...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Go
Go
package main   import ( "fmt" "math" )   func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] }   func main() { show(Fib1000(), "First 1000 Fibonacci numbers") }   func show(c []float64, title string) { var f [9]int...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#FreeBASIC
FreeBASIC
' version 08-10-2016 ' compile with: fbc -s console ' uses gmp   #Include Once "gmp.bi"   #Define max 60   Dim As Long n Dim As ZString Ptr gmp_str :gmp_str = Allocate(1000) ' 1000 char Dim Shared As Mpq_ptr tmp, big_j tmp = Allocate(Len(__mpq_struct)) :Mpq_init(tmp) big_j = Allocate(Len(__mpq_struct)) :Mpq_init(big_j)...
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#BASIC256
BASIC256
function binarySearchR(array, valor, lb, ub) if ub < lb then return false else mitad = floor((lb + ub) / 2) if valor < array[mitad] then return binarySearchR(array, valor, lb, mitad-1) if valor > array[mitad] then return binarySearchR(array, valor, mitad+1, ub) if valor =...
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...
#Free_Pascal
Free Pascal
  Program BestShuffle;   Const arr : array[1..6] Of string = ('abracadabra','seesaw','elk','grrrrrr','up','a');   Function Shuffle(inp: String): STRING;   Var x,ReplacementDigit : longint; ch : char; Begin If length(inp) > 1 Then Begin Randomize; For x := 1 To length(inp) Do Begin ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Liberty_BASIC
Liberty BASIC
  'string creation s$ = "Hello, world!"   'string destruction - not needed because of garbage collection s$ = ""   'string comparison s$ = "Hello, world!" If s$ = "Hello, world!" then print "Equal Strings"   'string copying a$ = s$   'check If empty If s$ = "" then print "Empty String"   'append a byte s$ = s$ + Chr$(3...
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] ...
#Rust
Rust
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> { let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1); for _ in 0..=limits.len() {bins.push(Vec::new());}   limits.iter().enumerate().for_each(|(idx, limit)| { data.iter().for_each(|elem| { if i...
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] ...
#Tcl
Tcl
namespace path {::tcl::mathop ::tcl::mathfunc}   # Not necessary but useful helper proc lincr {_list index} { upvar $_list list lset list $index [+ [lindex $list $index] 1] }   proc distribute_bins {binlims data} { set bins [lrepeat [+ [llength $binlims] 1] 0] foreach val $data { lincr bins [+ [lsearch -exact -in...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#XPL0
XPL0
char Bases; int Counts(256), Cnt, I, Ch; [Bases:= " CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTC...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#zkl
zkl
bases:= #<<<" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA ...
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 ...
#AutoIt
AutoIt
  ConsoleWrite(IntToBin(50) & @CRLF)   Func IntToBin($iInt) $Stack = ObjCreate("System.Collections.Stack") Local $b = -1, $r = "" While $iInt <> 0 $b = Mod($iInt, 2) $iInt = INT($iInt/2) $Stack.Push ($b) WEnd For $i = 1 TO $Stack.Count $r &= $Stack.Pop Next Return $r EndFunc ;==>IntToBin  
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.
#Julia
Julia
function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T δx = abs(x1 - x0) δy = abs(y1 - y0) δe = abs(δy / δx) er = 0.0   y = y0 for x in x0:x1 img[x, y] = col er += δe if er > 0.5 y += 1 er -= 1.0 end end...
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
#Pike
Pike
  > 0; (3) Result: 0 > false; (4) Result: 0 > 0; (6) Result: 0 > !true; (7) Result: 0 > true; (8) Result: 1 > 1; (9) Result: 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
#PL.2FI
PL/I
Declare x bit(1); x='1'b; /* True */ x='0'b; /* False */
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary utf8   class RCBoxTheCompass   properties public constant _FULL = '_FULL'   properties indirect headings = Rexx rosepoints = Rexx   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method RCBoxTheC...