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/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 |... | #Modula-3 | Modula-3 | MODULE Bitwise EXPORTS Main;
IMPORT IO, Fmt, Word;
VAR c: Word.T;
PROCEDURE Bitwise(a, b: INTEGER) =
BEGIN
IO.Put("a AND b: " & Fmt.Int(Word.And(a, b)) & "\n");
IO.Put("a OR b: " & Fmt.Int(Word.Or(a, b)) & "\n");
IO.Put("a XOR b: " & Fmt.Int(Word.Xor(a, b)) & "\n");
IO.Put("NOT a: " & Fmt.Int(Wo... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require Tk
namespace path ::tcl::mathfunc ;# for [max] function
proc newImage {width height} {
return [image create photo -width $width -height $height]
}
proc fill {image colour} {
$image put $colour -to 0 0 [$image cget -width] [$image cget -height]
}
proc setPixel {image col... |
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... | #Sidef | Sidef | var (actuals, expected) = ([], [])
var fibonacci = 1000.of {|i| fib(i).digit(0) }
for i (1..9) {
var num = fibonacci.count_by {|j| j == i }
actuals.append(num / 1000)
expected.append(1 + (1/i) -> log10)
}
"%17s%17s\n".printf("Observed","Expected")
for i (1..9) {
"%d : %11s %%%15s %%\n".printf(
... |
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... | #Scheme | Scheme | ; Return the n'th Bernoulli number.
(define bernoulli
(lambda (n)
(let ((a (make-vector (1+ n))))
(do ((m 0 (1+ m)))
((> m n))
(vector-set! a m (/ 1 (1+ m)))
(do ((j m (1- j)))
((< j 1))
(vector-set! a (1- j) (* j (- (vector-ref a (1- j)) (vector-ref a 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... | #Go | Go | func binarySearch(a []float64, value float64, low int, high int) int {
if high < low {
return -1
}
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)
}
return mid
... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: bestShuffle (in string: stri) is func
result
var string: shuffled is "";
local
var char: tmp is ' ';
var integer: i is 0;
var integer: j is 0;
begin
shuffled := stri;
for key i range shuffled do
for key j range shuffled do
if i <... |
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... | #Sidef | Sidef | func best_shuffle(String orig) -> (String, Number) {
var s = orig.chars
var t = s.shuffle
for i (^s) {
for j (^s) {
if (i!=j && t[i]!=s[j] && t[j]!=s[i]) {
t[i, j] = t[j, i]
break
}
}
}
(t.join, s ~Z== t -> count(true))
}
... |
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
... | #Delphi | Delphi |
program BinaryDigit;
{$APPTYPE CONSOLE}
uses
sysutils;
function IntToBinStr(AInt : LongWord) : string;
begin
Result := '';
repeat
Result := Chr(Ord('0')+(AInt and 1))+Result;
AInt := AInt div 2;
until (AInt = 0);
end;
Begin
writeln(' 5: ',IntToBinStr(5));
writeln(' 50: ',IntToBinStr(50));
... |
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.
| #Vedit_macro_language | Vedit macro language | // Daw a line using Bresenham's line algorithm.
// #1=x1, #2=y1; #3=x2, #4=y2
:DRAW_LINE:
Num_Push(31,35)
#31 = abs(#3-#1) // x distance
#32 = abs(#4-#2) // y distance
if (#4-#2 < -#31 || #3-#1 <= -#32) {
#99=#1; #1=#3; #3=#99 // swap start and end points
#99=#2; #2=#4; #4=#99
}
if (#1 < #3) { #34=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... | #uBasic.2F4tH | uBasic/4tH | Push 0, 1687, 1688, 3375, 5062, 5063, 6750, 8437, 8438, 10125, 11812, 11813
Push 13500, 15187, 15188, 16875, 18562, 18563, 20250, 21937, 21938, 23625
Push 25312, 25313, 27000, 28687, 28688, 30375, 32062, 32063, 33750, 35437
Push 35438 ' Use the stack as a DATA statement
For x = 32 To 0 Ste... |
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 |... | #Neko | Neko | /**
<doc>
<h2>bitwise operations</h2>
<p>Tectonics:
<br> nekoc bitwise.neko
<br> neko bitwise</p>
</doc>
*/
// Neko is a signed 31 bit integer VM, full 32 bit requires builtins
var int32_new = $loader.loadprim("std@int32_new", 1);
var int32_and = $loader.loadprim("std@int32_and", 2);
var int32_or ... |
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... | #TI-89_BASIC | TI-89 BASIC | typeset -T RGBColor_t=(
integer r g b
function to_s {
printf "%d %d %d" ${_.r} ${_.g} ${_.b}
}
function white { print "255 255 255"; }
function black { print "0 0 0"; }
function red { print "255 0 0"; }
function green { print "0 255 0"; }
function blue { print "0 0 2... |
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... | #SQL | SQL | -- Create table
CREATE TABLE benford (num INTEGER);
-- Seed table
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (1);
INSERT INTO benford (num) VALUES (2);
-- Populate table
INSERT INTO benford (num)
SELECT
ult + penult
FROM
(SELECT MAX(num) AS ult FROM benford),
(SELECT MAX(... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigrat.s7i";
const func bigRational: bernoulli (in integer: n) is func
result
var bigRational: bernoulli is bigRational.value;
local
var integer: m is 0;
var integer: j is 0;
var array bigRational: a is 0 times bigRational.value;
begin
a := [0 .. n] times... |
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... | #Groovy | Groovy |
def binSearchR
//define binSearchR closure.
binSearchR = { a, key, offset=0 ->
def m = n.intdiv(2)
def n = a.size()
a.empty \
? ["The insertion point is": offset] \
: a[m] > key \
? binSearchR(a[0..<m],key, offset) \
: a[m] < target \
? binSearchR(a[... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require struct::list
# Simple metric function; assumes non-empty lists
proc count {l1 l2} {
foreach a $l1 b $l2 {incr total [string equal $a $b]}
return $total
}
# Find the best shuffling of the string
proc bestshuffle {str} {
set origin [split $str ""]
set best $origin... |
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
... | #Dyalect | Dyalect | func Integer.ToString() {
var s = ""
for x in 31^-1..0 {
if this &&& (1 <<< x) != 0 {
s += "1"
} else if s != "" {
s += "0"
}
}
s
}
print("5 == \(5), 50 = \(50), 1000 = \(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.
| #Wart | Wart | # doesn't handle vertical lines
def (line x0 y0 x1 y1)
let steep ((> abs) y1-y0 x1-x0)
when steep
swap! x0 y0
swap! x1 y1
when (x0 > x1)
swap! x0 x1
swap! y0 y1
withs (deltax x1-x0
deltay (abs y1-y0)
error deltax/2
ystep (if (y0 < y1) 1 -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... | #UNIX_Shell | UNIX Shell | # List of abbreviated compass point labels
compass_points=( 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 )
# List of angles to test
test_angles=( 0.00 16.87 16.88 33.75 50.... |
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 |... | #Nemerle | Nemerle | def i = 255;
def j = 2;
WriteLine($"$i and $j is $(i & j)");
WriteLine($"$i or $j is $(i | j)");
WriteLine($"$i xor $j is $(i ^ j)");
WriteLine($"not $i is $(~i)");
WriteLine($"$i lshift $j is $(i << j)");
WriteLine($"$i arshift $j is $(i >> j)"); // When the left operand of the >> operator is of a signed in... |
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... | #UNIX_Shell | UNIX Shell | typeset -T RGBColor_t=(
integer r g b
function to_s {
printf "%d %d %d" ${_.r} ${_.g} ${_.b}
}
function white { print "255 255 255"; }
function black { print "0 0 0"; }
function red { print "255 0 0"; }
function green { print "0 255 0"; }
function blue { print "0 0 2... |
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... | #Stata | Stata | clear
set obs 1000
scalar phi=(1+sqrt(5))/2
gen fib=(phi^_n-(-1/phi)^_n)/sqrt(5)
gen k=real(substr(string(fib),1,1))
hist k, discrete // show a histogram
qui tabulate k, matcell(f) // compute frequencies
mata
f=st_matrix("f")
p=log10(1:+1:/(1::9))*sum(f)
// print observed vs predicted ... |
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... | #Swift | Swift | import Foundation
/* Reads from a file and returns the content as a String */
func readFromFile(fileName file:String) -> String{
var ret:String = ""
let path = Foundation.URL(string: "file://"+file)
do {
ret = try String(contentsOf: path!, encoding: String.Encoding.utf8)
}
catch {
... |
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... | #Sidef | Sidef | say bernoulli(42).as_frac #=> 1520097643918070802691/1806 |
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... | #SPAD | SPAD |
for n in 0..60 | (b:=bernoulli(n)$INTHEORY; b~=0) repeat print [n,b]
|
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... | #Haskell | Haskell | import Data.Array (Array, Ix, (!), listArray, bounds)
-- BINARY SEARCH --------------------------------------------------------------
bSearch
:: Integral a
=> (a -> Ordering) -> (a, a) -> Maybe a
bSearch p (low, high)
| high < low = Nothing
| otherwise =
let mid = (low + high) `div` 2
in case p mid of... |
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... | #Ursala | Ursala | #import std
#import nat
words = <'abracadabra','seesaw','elk','grrrrrr','up','a'>
shuffle = num; ^H/(*@K24) ^H\~&lS @rK2lSS *+ ^arPfarhPlzPClyPCrtPXPRalPqzyCipSLK24\~&L leql$^NS
#show+
main = ~&LS <.~&l,@r :/` ,' ('--+ --')'+ ~&h+ %nP+ length@plrEF>^(~&,shuffle)* words |
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... | #VBA | VBA |
Option Explicit
Sub Main_Best_shuffle()
Dim S() As Long, W, b As Byte, Anagram$, Count&, myB As Boolean, Limit As Byte, i As Integer
W = Array("a", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "qwerty", "tttt")
For b = 0 To UBound(W)
Count = 0
Select Case Len(W(b))
Case 1: ... |
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
... | #EasyLang | EasyLang | func to2 n . r$ .
if n > 0
call to2 n div 2 r$
if n mod 2 = 0
r$ &= "0"
else
r$ &= "1"
.
else
r$ = ""
.
.
func pr2 n . .
call to2 n r$
if r$ = ""
print "0"
else
print r$
.
.
call pr2 5
call pr2 50
call pr2 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.
| #Wren | Wren | import "graphics" for Canvas, ImageData, Color
import "dome" for Window
class Game {
static bmpCreate(name, w, h) { ImageData.create(name, w, h) }
static bmpFill(name, col) {
var image = ImageData[name]
for (x in 0...image.width) {
for (y in 0...image.height) image.pset(x, y, col... |
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... | #VBA | VBA | Public Sub box_the_compass()
Dim compass_point As Integer
Dim compass_points_all As New Collection
Dim test_points_all As New Collection
Dim compass_points(8) As Variant
Dim test_points(3) As Variant
compass_points(1) = [{ "North", "North by east", "North-northeast", "Northeas... |
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 |... | #Nim | Nim | proc bitwise(a, b) =
echo "a and b: " , a and b
echo "a or b: ", a or b
echo "a xor b: ", a xor b
echo "not a: ", not a
echo "a << b: ", a shl b
echo "a >> b: ", a shr b |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixe... | #Vedit_macro_language | Vedit macro language | #11 = 400 // Width of the image
#12 = 300 // Height of the image
// Create an empty RGB image and fill it with black color
//
File_Open("|(VEDIT_TEMP)\pixel.data", OVERWRITE+NOEVENT)
BOF
Del_Char(ALL)
#10 = Buf_Num
Repeat(#11 * #12) {
Ins_Char(0, COUNT, 3)
}
// Fill the image with dark blue color
//
#5 = 0 ... |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #Tcl | Tcl | proc benfordTest {numbers} {
# Count the leading digits (RE matches first digit in each number,
# even if negative)
set accum {1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0}
foreach n $numbers {
if {[regexp {[1-9]} $n digit]} {
dict incr accum $digit
}
}
# Print the report
puts " digit | meas... |
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... | #Swift | Swift | import BigInt
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> {
guard n != 0 else {
return 1
}
var arr = [Frac<T>]()
for m in 0...n {
arr.append(Frac(numerator: 1, denominator: T(m) + 1))
for j in stride(from: m, through: 1, by: -1) {
arr[j-1] = (arr[j-1] - a... |
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... | #Tcl | Tcl | proc bernoulli {n} {
for {set m 0} {$m <= $n} {incr m} {
lappend A [list 1 [expr {$m + 1}]]
for {set j $m} {[set i $j] >= 1} {} {
lassign [lindex $A [incr j -1]] a1 b1
lassign [lindex $A $i] a2 b2
set x [set p [expr {$i * ($a1*$b2 - $a2*$b1)}]]
set y [set q [expr {$b1 * $b2}]]
while {$q} ... |
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... | #HicEst | HicEst | REAL :: n=10, array(n)
array = NINT( RAN(n) )
SORT(Vector=array, Sorted=array)
x = NINT( RAN(n) )
idx = binarySearch( array, x )
WRITE(ClipBoard) x, "has position ", idx, "in ", array
END
FUNCTION binarySearch(A, value)
REAL :: A(1), value
low = 1
high = LEN(A)
DO i = 1, high
I... |
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... | #VBScript | VBScript | 'Best Shuffle Task
'VBScript Implementation
Function bestshuffle(s)
Dim arr:Redim arr(Len(s)-1)
'The Following Does the toCharArray() Functionality
For i = 0 To Len(s)-1
arr(i) = Mid(s, i + 1, 1)
Next
arr = shuffler(arr) 'Make this line a comment for deterministic solution
For i... |
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
... | #EchoLisp | EchoLisp |
;; primitive : (number->string number [base]) - default base = 10
(number->string 2 2)
→ 10
(for-each (compose writeln (rcurry number->string 2)) '( 5 50 9000)) →
101
110010
10001100101000
|
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
[SetVid($112); \set 640x480 graphics in 24-bit color
Move(10, 20); \set start of line segment
Line(600, 400, $123456);\draw line segment, red=$12, green=$34, blue=$56
if ChIn(1) then []; \wait for keystroke while viewing graphic screen
SetVid... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module BoxingTheCompass
Dim _points(32) As String
Sub Main()
BuildPoints()
Dim heading As Double = 0D
For i As Integer = 0 To 32
heading = i * 11.25
Select Case i Mod 3
Case 1
heading += 5.62
Case 2
... |
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 |... | #NSIS | NSIS | Function Bitwise
Push $0
Push $1
Push $2
StrCpy $0 7
StrCpy $1 2
IntOp $2 $0 & $1
DetailPrint "Bitwise AND: $0 & $1 = $2"
IntOp $2 $0 | $1
DetailPrint "Bitwise OR: $0 | $1 = $2"
IntOp $2 $0 ^ $1
DetailPrint "Bitwise XOR: $0 ^ $1 = $2"
IntOp $2 $0 ~
DetailPrint "Bitwise NOT (negate in NSIS docs): ~$0 = $2... |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixe... | #Visual_Basic_.NET | Visual Basic .NET | ' The StructLayout attribute allows fields to overlap in memory.
<System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)> _
Public Structure Rgb
<FieldOffset(0)> _
Public Rgb As Integer
<FieldOffset(0)> _
Public B As Byte
<FieldOffset(1)> _
Public G As Byte
<FieldOffset(2)>... |
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... | #VBA_.28Visual_Basic_for_Application.29 | VBA (Visual Basic for Application) |
Sub BenfordLaw()
Dim BenResult(1 To 9) As Long
BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"
For Each c In Selection.Cells
If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
For i = 1 To 9
If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
Next
End If
Next
To... |
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... | #Visual_FoxPro | Visual FoxPro |
#DEFINE CTAB CHR(9)
#DEFINE COMMA ","
#DEFINE CRLF CHR(13) + CHR(10)
LOCAL i As Integer, n As Integer, n1 As Integer, rho As Double, c As String
n = 1000
LOCAL ARRAY a[n,2], res[1]
CLOSE DATABASES ALL
CREATE CURSOR fibo(dig C(1))
INDEX ON dig TAG dig COLLATE "Machine"
SET ORDER TO 0
*!* Populate the cursor with the l... |
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... | #Visual_Basic_.NET | Visual Basic .NET | ' Bernoulli numbers - vb.net - 06/03/2017
Imports System.Numerics 'BigInteger
Module Bernoulli_numbers
Function gcd_BigInt(ByVal x As BigInteger, ByVal y As BigInteger) As BigInteger
Dim y2 As BigInteger
x = BigInteger.Abs(x)
Do
y2 = BigInteger.Remainder(x, y)
x =... |
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... | #Hoon | Hoon | |= [arr=(list @ud) x=@ud]
=/ lo=@ud 0
=/ hi=@ud (dec (lent arr))
|-
?> (lte lo hi)
=/ mid (div (add lo hi) 2)
=/ val (snag mid arr)
?: (lth x val) $(hi (dec mid))
?: (gth x val) $(lo +(mid))
mid |
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... | #Wren | Wren | import "random" for Random
class BestShuffle {
static shuffle_(ca) {
var rand = Random.new()
var i = ca.count - 1
while (i >= 1) {
var r = rand.int(i + 1)
var tmp = ca[i]
ca[i] = ca[r]
ca[r] = tmp
i = i - 1
}
}
s... |
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
... | #Elena | Elena | import system'routines;
import extensions;
public program()
{
new int[]{5,50,9000}.forEach:(n)
{
console.printLine(n.toString(2))
}
} |
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.
| #zkl | zkl | ppm:=PPM(200,200,0xFF|FF|FF);
ppm.line(50,100, 100,190, 0);
ppm.line(100,190, 150,100, 0);
ppm.line(150,100, 100,10, 0);
ppm.line(100,10, 50,100, 0);
ppm.writeJPGFile("line.jpg"); |
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... | #Wren | Wren | import "/fmt" for Fmt
// 'cpx' returns integer index from 0 to 31 corresponding to compass point.
// Input heading h is in degrees. Note this index is a zero-based index
// suitable for indexing into the table of printable compass points,
// and is not the same as the index specified to be printed in the output.
var... |
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 |... | #Oberon-2 | Oberon-2 |
MODULE Bitwise;
IMPORT
SYSTEM,
Out;
PROCEDURE Do(a,b: LONGINT);
VAR
x,y: SET;
BEGIN
x := SYSTEM.VAL(SET,a);y := SYSTEM.VAL(SET,b);
Out.String("a and b :> ");Out.Int(SYSTEM.VAL(LONGINT,x * y),0);Out.Ln;
Out.String("a or b :> ");Out.Int(SYSTEM.VAL(LONGINT,x + y),0);Out.Ln;
Out.String("a xor b :> ");Out... |
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... | #Wren | Wren | import "graphics" for Canvas, ImageData, Color
import "dome" for Window
class Game {
static bmpCreate(name, w, h) { ImageData.create(name, w, h) }
static bmpFill(name, col) {
var image = ImageData[name]
for (x in 0...image.width) {
for (y in 0...image.height) image.pset(x, y, col... |
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... | #Vlang | Vlang | import math
fn fib1000() []f64 {
mut a, mut b, mut r := 0.0, 1.0, []f64{len:1000}
for i in 0..r.len {
r[i], a, b = b, b, b+a
}
return r
}
fn main() {
show(fib1000(), "First 1000 Fibonacci numbers")
}
fn show(c []f64, title string) {
mut f := [9]int{}
for v in c {
f["$v"... |
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... | #Wren | Wren | import "/fmt" for Fmt
var fib1000 = Fn.new {
var a = 0
var b = 1
var r = List.filled(1000, 0)
for (i in 0...r.count) {
var oa = a
var ob = b
r[i] = ob
a = ob
b = ob + oa
}
return r
}
var LN10 = 2.3025850929940457
var log10 = Fn.new { |x| x.log / LN10... |
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... | #Wren | Wren | import "/fmt" for Fmt
import "/big" for BigRat
var bernoulli = Fn.new { |n|
if (n < 0) Fiber.abort("Argument must be non-negative")
var a = List.filled(n+1, null)
for (m in 0..n) {
a[m] = BigRat.new(1, m+1)
var j = m
while (j >= 1) {
a[j-1] = (a[j-1] - a[j]) * BigRat.ne... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure binsearch(A, target)
if *A = 0 then fail
mid := *A/2 + 1
if target > A[mid] then {
return mid + binsearch(A[(mid+1):0], target)
}
else if target < A[mid] then {
return binsearch(A[1+:(mid-1)], target)
}
return mid
end |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \'code' declarations
string 0; \use zero-terminated string convention
func StrLen(A); \Return number of characters in an ASCIIZ string
char A;
int I;
for I:= 0 to -1>>1-1 do
if A(I) = 0 then return I;
proc Shuffle(W0); \Display best shuffle of characters ... |
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... | #zkl | zkl | fcn bestShuffle(str){
s:=str.split("").shuffle(); // -->List
if(not s) return(str,str.len()); // can't shuffle "" or "a"
n:=str.len();
foreach i in (n){
foreach j in (n){
if (i!=j and s[i]!=str[j] and s[j]!=str[i]){
s.swap(i,j);
break;
}
}
}
return(s.concat(), s.... |
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
... | #Elixir | Elixir |
IO.puts Integer.to_string(5,2)
|
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... | #Yabasic | Yabasic |
dim point$(32)
for i =1 to 32
read point$(i)
next i
print "Index\tClosest Point\t\tDegrees"
print "=====\t=============\t\t======="
for i = 0 to 32
heading = i *11.25
resto=mod(i,3)
if resto=1 then
heading = heading +5.62
elseif resto=2 then
heading = heading -5.62
end if
... |
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 |... | #Objeck | Objeck | use IO;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
BitWise(3, 4);
}
function : BitWise(a : Int, b : Int) ~ Nil {
Console->GetInstance()->Print("a and b: ")->PrintLine(a and b);
Console->GetInstance()->Print("a or b: ")->PrintLine(a or b);
Console->... |
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... | #Xojo | Xojo | Function CreatePicture(width As Integer, height As Integer) As Picture
Return New Picture(width, height)
End Function
Sub FillPicture(ByRef p As Picture, FillColor As Color)
p.Graphics.ForeColor = FillColor
p.Graphics.FillRect(0, 0, p.Width, p.Height)
End Sub
Function GetPixelColor(p As Picture, x As Integer,... |
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... | #zkl | zkl | show( // use list (fib(1)...fib(1000)) --> (1..4.34666e+208)
(0).pump(1000,List,fcn(ab){ab.append(ab.sum(0.0)).pop(0)}.fp(L(1,1))),
"First 1000 Fibonacci numbers");
fcn show(data,title){
f:=(0).pump(9,List,Ref.fp(0)); // (Ref(0),Ref(0)...
foreach v in (data){ // eg 1.49707e+207 ("g" format) --> "1" (fir... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 RANDOMIZE
20 DIM b(9)
30 LET n=100
40 FOR i=1 TO n
50 GO SUB 1000
60 LET n$=STR$ fiboI
70 LET d=VAL n$(1)
80 LET b(d)=b(d)+1
90 NEXT i
100 PRINT "Digit";TAB 6;"Actual freq";TAB 18;"Expected freq"
110 FOR i=1 TO 9
120 LET pdi=(LN (i+1)/LN 10)-(LN i/LN 10)
130 PRINT i;TAB 6;b(i)/n;TAB 18;pdi
140 NEXT i
150 STOP
1000... |
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... | #zkl | zkl | class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{ "%50d / %d".fmt(a,b) }
fcn normalize{ // divide a and b by gcd
g:= a.gcd(b);
a/=g; b/=g;
if(b<0){ a=-a; b=-b; } // denominator > 0
self
}
fcn __opAdd(n){
... |
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... | #J | J | bs=. i. 'Not Found'"_^:(-.@-:) I. |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR n=1 TO 6
20 READ w$
30 GO SUB 1000
40 LET count=0
50 FOR i=1 TO LEN w$
60 IF w$(i)=b$(i) THEN LET count=count+1
70 NEXT i
80 PRINT w$;" ";b$;" ";count
90 NEXT n
100 STOP
1000 REM Best shuffle
1010 LET b$=w$
1020 FOR i=1 TO LEN b$
1030 FOR j=1 TO LEN b$
1040 IF (i<>j) AND (b$(i)<>w$(j)) AND (b$(j)<>w$(i)) THEN L... |
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
... | #Epoxy | Epoxy | fn bin(a,b:true)
var c:""
while a>0 do
c,a:tostring(a%2)+c,bit.rshift(a,1)
cls
if b then
c:string.repeat("0",16-#c)+c
cls
return c
cls
var List: [5,50,9000]
iter Value of List do
log(Value+": "+bin(Value,false))
cls |
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... | #zkl | zkl | A:=("X N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE " // one based array
"SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW "
"WSW WbS W WbN WNW NWbW NW NWbN NNW NbW").split(" ");
fcn compassBox(d){
return(( ( (d + 360.0 / 64.0) % 360.0) * 32.0 / 360.0).ceil());
}
foreach i in ([0..32]){
heading:=11... |
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 |... | #OCaml | OCaml | let bitwise a b =
Printf.printf "a and b: %d\n" (a land b);
Printf.printf "a or b: %d\n" (a lor b);
Printf.printf "a xor b: %d\n" (a lxor b);
Printf.printf "not a: %d\n" (lnot a);
Printf.printf "a lsl b: %d\n" (a lsl b); (* left shift *)
Printf.printf "a asr b: %d\n" (a asr b); (* arithmetic right 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 pixe... | #XPL0 | XPL0 | include c:\cxpl\codes; \include 'code' declarations
def Width=180, Height=135, Color=$123456;
int X, Y;
[SetVid($112); \set display for 640x480 graphics in 24-bit RGB color
for Y:= 0 to Height-1 do \fill area with Color one pixel at a time
for X:= 0 to Width-1 do \(this takes 4.12 ms on a Duron 850)
Po... |
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... | #zkl | zkl | class PPM{ // (0,0) is logically bottom left
fcn init(width,height){
sz:=width*height*3;
var [const]
data=sz.pump(Data(sz),0), // initialize to Black (RGB=000)
w=width, h=height;
}
fcn fill(rgb){
sz:=data.len()/3;
data.clear(); sz.pump(data,T(Void,rgb.toBigEndian(3)));
}... |
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... | #Java | Java | public class BinarySearchIterative {
public static int binarySearch(int[] nums, int check) {
int hi = nums.length - 1;
int lo = 0;
while (hi >= lo) {
int guess = (lo + hi) >>> 1; // from OpenJDK
if (nums[guess] > check) {
hi = guess - 1;
... |
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
... | #Erlang | Erlang | lists:map( fun(N) -> io:fwrite("~.2B~n", [N]) end, [5, 50, 9000]). |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DATA "North","North by east","North-northeast"
20 DATA "Northeast by north","Northeast","Northeast by east","East-northeast"
30 DATA "East by north","East","East by south","East-southeast"
40 DATA "Southeast by east","Southeast","Southeast by south","South-southeast"
50 DATA "South by east","South","South by west","... |
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 |... | #Octave | Octave | function bitops(a, b)
s = sprintf("%s %%s %s = %%s\n", dec2bin(a), dec2bin(b));
printf(s, "or", dec2bin(bitor(a, b)));
printf(s, "and", dec2bin(bitand(a, b)));
printf(s, "xor", dec2bin(bitxor(a, b)));
printf(s, "left shift", dec2bin(bitshift(a, abs(b))));
printf(s, "right shift", dec2bin(bitshift(a, -abs(b)... |
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... | #JavaScript | JavaScript | function binary_search_recursive(a, value, lo, hi) {
if (hi < lo) { return null; }
var mid = Math.floor((lo + hi) / 2);
if (a[mid] > value) {
return binary_search_recursive(a, value, lo, mid - 1);
}
if (a[mid] < value) {
return binary_search_recursive(a, value, mid + 1, hi);
}
return mid;
} |
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
... | #Euphoria | Euphoria | function toBinary(integer i)
sequence s
s = {}
while i do
s = prepend(s, '0'+and_bits(i,1))
i = floor(i/2)
end while
return s
end function
puts(1, toBinary(5) & '\n')
puts(1, toBinary(50) & '\n')
puts(1, toBinary(9000) & '\n') |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Oforth | Oforth | : bitwise(a, b)
a b bitAnd println
a b bitOr println
a b bitXor println
a bitLeft(b) println
a bitRight(b) println ; |
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... | #jq | jq | def binarySearch(value):
# To avoid copying the array, simply pass in the current low and high offsets
def binarySearch(low; high):
if (high < low) then (-1 - low)
else ( (low + high) / 2 | floor) as $mid
| if (.[$mid] > value) then binarySearch(low; $mid-1)
elif (.[$mid] < value... |
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
... | #F.23 | F# | open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2) |
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 |... | #ooRexx | ooRexx | /* ooRexx *************************************************************
/ Bit Operations work as in Rexx (of course)
* Bit operations are performed up to the length of the shorter string.
* The rest of the longer string is copied to the result.
* ooRexx introduces the possibility to specify a padding character
* to be ... |
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... | #Jsish | Jsish | /**
Binary search, in Jsish, based on Javascript entry
Tectonics: jsish -u -time true -verbose true binarySearch.jsi
*/
function binarySearchIterative(haystack, needle) {
var mid, low = 0, high = haystack.length - 1;
while (low <= high) {
mid = Math.floor((low + high) / 2);
if (haystack[... |
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
... | #Factor | Factor | USING: io kernel math math.parser ;
5 >bin print
50 >bin print
9000 >bin print |
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 |... | #OpenEdge.2FProgress | OpenEdge/Progress | bo(a,b)={
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
print("Not: "bitneg(a));
print("Xor: "bitxor(a,b));
print("Left shift: ",a<<b);
print("Right shift: ",a>>b);
} |
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... | #Julia | Julia | function binarysearch(lst::Vector{T}, val::T) where T
low = 1
high = length(lst)
while low ≤ high
mid = (low + high) ÷ 2
if lst[mid] > val
high = mid - 1
elseif lst[mid] < val
low = mid + 1
else
return mid
end
end
return 0
e... |
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
... | #FALSE | FALSE | [0\10\[$1&'0+\2/$][]#%[$][,]#%]b:
5 b;!
50 b;!
9000 b;! |
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 |... | #PARI.2FGP | PARI/GP | bo(a,b)={
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
print("Not: "bitneg(a));
print("Xor: "bitxor(a,b));
print("Left shift: ",a<<b);
print("Right shift: ",a>>b);
} |
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... | #K | K |
bs:{[a;t]
if[0=#a; :_n];
m:_(#a)%2;
if[t>a@m
tmp:_f[(m+1) _ a;t]
:[_n~tmp; :_n; :1+m+tmp]]
if[t<a@m
:_f[m#a;t]]
:m
}
v:8 30 35 45 49 77 79 82 87 97
{bs[v;x]}' v
0 1 2 3 4 5 6 7 8 9
|
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
... | #FBSL | FBSL | #AppType Console
function Bin(byval n as integer, byval s as string = "") as string
if n > 0 then return Bin(n \ 2, (n mod 2) & s)
if s = "" then return "0"
return s
end function
print Bin(5)
print Bin(50)
print Bin(9000)
pause
|
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 |... | #Pascal | Pascal | var
a, b: integer;
begin
a := 10; { binary 1010 }
b := 12; { binary 1100 }
writeln('a and b = ', a and b); { 8 = 1000 }
writeln('a or b = ', a or b); { 14 = 1110 }
writeln('a xor b = ', a xor b) { 6 = 0110 }
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 p... | #Kotlin | Kotlin | fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
var hi = size - 1
var lo = 0
while (hi >= lo) {
val guess = lo + (hi - lo) / 2
if (this[guess] > target) hi = guess - 1
else if (this[guess] < target) lo = guess + 1
else return guess
}
return -1... |
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
... | #FOCAL | FOCAL | 01.10 S A=5;D 2
01.20 S A=50;D 2
01.30 S A=9000;D 2
01.40 Q
02.10 S BX=0
02.20 S BD(BX)=A-FITR(A/2)*2
02.25 S A=FITR(A/2)
02.30 S BX=BX+1
02.35 I (-A)2.2
02.40 S BX=BX-1
02.45 D 2.6
02.50 I (-BX)2.4;T !;R
02.60 I (-BD(BX))2.7;T "0";R
02.70 T "1" |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Perl | Perl | use integer;
sub bitwise($$) {
($a, $b) = @_;
print 'a and b: '. ($a & $b) ."\n";
print 'a or b: '. ($a | $b) ."\n";
print 'a xor b: '. ($a ^ $b) ."\n";
print 'not a: '. (~$a) ."\n";
print 'a >> b: ', $a >> $b, "\n"; # logical right shift
use integer; # "use integer" enables bitwise oper... |
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... | #Lambdatalk | Lambdatalk |
{def BS
{def BS.r {lambda {:a :v :i0 :i1}
{let { {:a :a} {:v :v} {:i0 :i0} {:i1 :i1}
{:m {floor {* {+ :i0 :i1} 0.5}}} }
{if {< :i1 :i0}
then :v is not found
else {if {> {array.item :a :m} :v}
then {BS.r :a :v :i0 {- :m 1} }
else {if {< {array.item :a :m} :v}
then {BS.r :a :v {+ :m 1} ... |
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
... | #Forth | Forth | \ Forth uses a system variable 'BASE' for number conversion
\ HEX is a standard word to change the value of base to 16
\ DECIMAL is a standard word to change the value of base to 10
\ we can easily compile a word into the system to set 'BASE' to 2
: binary 2 base ! ;
\ interactive console test with conver... |
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 |... | #Phix | Phix | enum SHL, SAR, SHR, ROL, ROR
function bitop(atom a, integer b, integer op)
atom res
#ilASM{
[32]
mov eax,[a]
call :%pLoadMint
mov ecx,[b]
mov edx,[op]
cmp dl,SHL
jne @f
shl eax,cl
jmp :storeres
... |
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... | #Liberty_BASIC | Liberty BASIC |
dim theArray(100)
for i = 1 to 100
theArray(i) = i
next i
print binarySearch(80,30,90)
wait
FUNCTION binarySearch(val, lo, hi)
IF hi < lo THEN
binarySearch = 0
ELSE
middle = int((hi + lo) / 2):print middle
if val < theArray(middle) then binarySearch = binarySearch(val, lo, middle-1)
if val... |
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
... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 23:14:14
!
!a=./F && make $a && $a < unixdict.txt
!f95 -Wall -ffree-form F.F -o F
!101
!110010
!10001100101000
!
!Compilation finished at Sun May 19 23:14:14
!
!
! tobin=: -.&' '@":@#:
! tobin 5
!101
! tobin 50
!110010
! ... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.