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/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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
'string creation
Dim x = "hello world"
' mark string for garbage collection
x = Nothing
' string assignment with a null byte
x = "ab" + Chr(0)
Console.WriteLine(x)
Console.WriteLine(x.Length)
'string comparison... |
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
... | #CLU | CLU | binary = proc (n: int) returns (string)
bin: string := ""
while n > 0 do
bin := string$c2s(char$i2c(48 + n // 2)) || bin
n := n / 2
end
return(bin)
end binary
start_up = proc ()
po: stream := stream$primary_output()
tests: array[int] := array[int]$[5, 50, 9000]
for 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.
| #RapidQ | RapidQ | SUB draw_line(x1, y1, x2, y2, colour)
x_dist = abs(x2-x1)
y_dist = abs(y2-y1)
IF y2-y1 < -x_dist OR x2-x1 <= -y_dist THEN
SWAP x1, x2 ' Swap start and end points
SWAP y1, y2
END IF
IF x1 < x2 THEN x_step = 1 ELSE x_step = -1
IF y1 < y2 THEN y_step = 1 ELSE y_step = -1
IF y_... |
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... | #Ring | Ring |
# Project : Box the compass
names = ["North", "North by east", "North-northeast",
"Northeast by north", "Northeast", "Northeast by east", "East-northeast",
"East by north", "East", "East by south", "East-southeast",
"Southeast by east", "Southeast", "Southeast by sout... |
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 |... | #Logo | Logo | to bitwise :a :b
(print [a and b:] BitAnd :a :b)
(print [a or b:] BitOr :a :b)
(print [a xor b:] BitXor :a :b)
(print [not a:] BitNot :a)
; shifts are to the left if positive, to the right if negative
(print [a lshift b:] LShift :a :b)
(print [a lshift -b:] LShift :a minus :b)
(print [-a ashift -b:] ASh... |
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... | #PureBasic | PureBasic | w=800 : h=600
CreateImage(1,w,h)
;1 is internal id of image
StartDrawing(ImageOutput(1))
; fill with color red
Box(0,0,w,h,$ff)
; or using another (but slower) way in green
FillArea(0,0,-1,$ff00)
; a green Dot
Plot(10,10,$ff0000)
; check if we set it right (should be 255)
Debug Blue(Point(10,10))
|
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the freque... | #PureBasic | PureBasic | #MAX_N=1000
NewMap d1.i()
Dim fi.s(#MAX_N)
fi(0)="0" : fi(1)="1"
Declare.s Sigma(sx.s,sy.s)
For I=2 To #MAX_N
fi(I)=Sigma(fi(I-2),fi(I-1))
Next
For I=1 To #MAX_N
d1(Left(fi(I),1))+1
Next
Procedure.s Sigma(sx.s, sy.s)
Define i.i, v1.i, v2.i, r.i
Define s.s, sa.s
sy=ReverseString(sy) : s=ReverseString(s... |
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... | #PL.2FI | PL/I | Bern: procedure options (main); /* 4 July 2014 */
declare i fixed binary;
declare B complex fixed (31);
Bernoulli: procedure (n) returns (complex fixed (31));
declare n fixed binary;
declare anum(0:n) fixed (31), aden(0:n) fixed (31);
declare (j, m) fixed;
declare F fixed (31);
do m = 0 to... |
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... | #Erlang | Erlang | %% Task: Binary Search algorithm
%% Author: Abhay Jain
-module(searching_algorithm).
-export([start/0]).
start() ->
List = [1,2,3],
binary_search(List, 5, 1, length(List)).
binary_search(List, Value, Low, High) ->
if Low > High ->
io:format("Number ~p not found~n", [Value]),
not_foun... |
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... | #Prolog | Prolog | :- dynamic score/2.
best_shuffle :-
maplist(best_shuffle, ["abracadabra", "eesaw", "elk", "grrrrrr",
"up", "a"]).
best_shuffle(Str) :-
retractall(score(_,_)),
length(Str, Len),
assert(score(Str, Len)),
calcule_min(Str, Len, Min),
repeat,
shuffle(Str, Shuffled),
maplist(comp, Str, Shuffled, ... |
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... | #Wren | Wren | // create string
var s = "abc"
// destroy string (not really see notes above)
s = null
// (re)assignment
s = "def"
// comparison (only == && != supported directly)
var b = (s == "abc") // false
// cloning/copying
var t = s
// check if empty
s = ""
b = (s != "") // false
b = s.isEmpty // true
// append a ... |
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
... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 binary_number pic X(21).
01 str pic X(21).
01 binary_digit pic X.
01 digit pic 9.
01 n pic 9(7).
01 nstr ... |
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.
| #REXX | REXX | /*REXX program plots/draws line segments using the Bresenham's line (2D) algorithm. */
parse arg data /*obtain optional arguments from the CL*/
if data='' then data= "(1,8) (8,16) (16,8) (8,1) (1,8)" /* ◄──── a rhombus.*/
data= translate(data, , '()[]{}/,:;') ... |
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... | #Ruby | Ruby | Headings = %w(north east south west north).each_cons(2).flat_map do |a, b|
[a,
"#{a} by #{b}",
"#{a}-#{a}#{b}",
"#{a}#{b} by #{a}",
"#{a}#{b}",
"#{a}#{b} by #{b}",
"#{b}-#{a}#{b}",
"#{b} by #{a}"]
end
Headings.prepend nil
def heading(degrees)
i = degrees.quo(360).*(32).round.%(32).+(1)
[i, Headin... |
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 |... | #LSE64 | LSE64 | over : 2 pick
2dup : over over
bitwise : \
" A=" ,t over ,h sp " B=" ,t dup ,h nl \
" A and B=" ,t 2dup & ,h nl \
" A or B=" ,t 2dup | ,h nl \
" A xor B=" ,t over ^ ,h nl \
" not A=" ,t ~ ,h nl
\ a \ 7 bitwise # hex literals |
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... | #Python | Python | # See the class definitions and constructors with, e.g.
getClass("pixmapIndexed", package=pixmap)
pixmapIndexed
# Image with all one colour
plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col="red"))
# Image with one pixel specified
cols <- rep("blue", 12); cols[7] <- "red"
plot(p2 <- pixmapIndexed(matrix(1:1... |
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... | #R | R | # See the class definitions and constructors with, e.g.
getClass("pixmapIndexed", package=pixmap)
pixmapIndexed
# Image with all one colour
plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col="red"))
# Image with one pixel specified
cols <- rep("blue", 12); cols[7] <- "red"
plot(p2 <- pixmapIndexed(matrix(1:1... |
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... | #Python | Python | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
# powers of 3 as a test sequence
def pow... |
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... | #Python | Python | from fractions import Fraction as Fr
def bernoulli(n):
A = [0] * (n+1)
for m in range(n+1):
A[m] = Fr(1, m+1)
for j in range(m, 0, -1):
A[j-1] = j*(A[j-1] - A[j])
return A[0] # (which is Bn)
bn = [(i, bernoulli(i)) for i in range(61)]
bn = [(i, b) for i,b in bn if b]
width = ma... |
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... | #Euphoria | Euphoria | function binary_search(sequence s, object val, integer low, integer high)
integer mid, cmp
if high < low then
return 0 -- not found
else
mid = floor( (low + high) / 2 )
cmp = compare(s[mid], val)
if cmp > 0 then
return binary_search(s, val, low, mid-1)
el... |
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... | #PureBasic | PureBasic | Structure charInfo
Char.s
List Position.i()
count.i ;number of occurrences of Char
EndStructure
Structure cycleInfo
Char.s
Position.i
EndStructure
Structure cycle
List cycle.cycleInfo()
EndStructure
Procedure.s shuffleWordLetters(word.s)
Protected i
Dim originalLetters.s(len(word) - 1)
... |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la... | #zkl | zkl | Data(0,.Int,1,2,3) // bytes
Data(0,String,1,2,3) // same
Data(0,Int,"foo","bar") //-->foobar\0
d:=Data(0,String,"foo","bar") //-->foo\0bar\0\0
d==d // -->True: byte by byte comparison
d.copy() //-->clone
d.len() //-->8, 0 if empty
d.append("1").len(); //-->10 // or d+"1"
Data(0,Int,"foo","bar").len() //-->6
Data(0... |
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
... | #CoffeeScript | CoffeeScript | binary = (n) ->
new Number(n).toString(2)
console.log binary n for n in [5, 50, 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.
| #Ring | Ring |
load "guilib.ring"
load "stdlib.ring"
new qapp
{
win1 = new qwidget() {
setwindowtitle("drawing using qpainter")
setwinicon(self,"c:\ring\bin\image\browser.png")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
set... |
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... | #Run_BASIC | Run BASIC | global direct$
dim direct$(22)
direct$(1) = "y" 'by
direct$(4) = "ast" 'East
direct$(13) = "orth" 'North
direct$(18) = "outh" 'Soutn
direct$(22) = "est" 'West
dim point$(32)
for i =1 to 32: read point$(i) :next i
html "<table border=1>"
for i = 0 to 32
hdng = i * 11.25
if (i mod 3) = 1 the... |
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 |... | #Lua | Lua | local bit = require"bit"
local vb = {
0, 1, -1, 2, -2, 0x12345678, 0x87654321,
0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55,
0x7fffffff, 0x80000000, 0xffffffff
}
local function cksum(name, s, r)
local z = 0
for i=1,#s do z = (z + string.byte(s, i)*i) % 2147483629 end
if z ~= r then
error("bit."..n... |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixe... | #Racket | Racket |
#lang racket
;; The racket/draw libraries provide imperative drawing functions.
;; http://docs.racket-lang.org/draw/index.html
(require racket/draw)
;; To create an image with width and height, use the make-bitmap
;; function.
;; For example, let's make a small image here:
(define bm (make-bitmap 640 480))
;;... |
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... | #Raku | Raku | class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i + $j * $!width] }
method ... |
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... | #R | R |
pbenford <- function(d){
return(log10(1+(1/d)))
}
get_lead_digit <- function(number){
return(as.numeric(substr(number,1,1)))
}
fib_iter <- function(n){
first <- 1
second <- 0
for(i in 1:n){
sum <- first + second
first <- second
second <- sum
}
return(sum)
}
fib_sequence <- mapply(fib_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... | #Racket | Racket | #lang racket
(define (log10 n) (/ (log n) (log 10)))
(define (first-digit n)
(quotient n (expt 10 (inexact->exact (floor (log10 n))))))
(define N 10000)
(define fibs
(let loop ([n N] [a 0] [b 1])
(if (zero? n) '() (cons b (loop (sub1 n) b (+ a b))))))
(define v (make-vector 10 0))
(for ([n fibs])
(d... |
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... | #Quackery | Quackery | $ "bigrat.qky" loadfile
[ 1+
' [ [] ] over of swap
times
[ i^ 1+ n->v 1/v
join swap i^ poke
i^ times
[ dup i 1+ peek do
dip over swap i peek do
v- i 1+ n->v v*
join swap i poke ] ]
1 split drop do ] is bernoulli ( n --... |
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... | #R | R |
library(pracma)
for (idx in c(1,2*0:30)) {
b <- bernoulli(idx)
d <- as.character(denominator(b))
n <- as.character(numerator(b))
cat("B(",idx,") = ",n,"/",d,"\n", sep = "")
}
|
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... | #F.23 | F# | let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =
if (high < low) then
null
else
let mid = (low + high) / 2
if (myArray.[mid] > value) then
binarySearch (myArray, low, mid-1, value)
else if (myArray.[mid] < value) then
... |
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... | #Python | Python | import random
def count(w1,wnew):
return sum(c1==c2 for c1,c2 in zip(w1, wnew))
def best_shuffle(w):
wnew = list(w)
n = len(w)
rangelists = (list(range(n)), list(range(n)))
for r in rangelists:
random.shuffle(r)
rangei, rangej = rangelists
for i in rangei:
for j in rangej... |
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
... | #Common_Lisp | Common Lisp | (format t "~b" 5)
; or
(write 5 :base 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.
| #Ruby | Ruby | Pixel = Struct.new(:x, :y)
class Pixmap
def draw_line(p1, p2, colour)
validate_pixel(p1.x, p2.y)
validate_pixel(p2.x, p2.y)
x1, y1 = p1.x, p1.y
x2, y2 = p2.x, p2.y
steep = (y2 - y1).abs > (x2 - x1).abs
if steep
x1, y1 = y1, x1
x2, y2 = y2, x2
end
if x1 > x2
... |
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... | #Rust | Rust | fn expand(cp: &str) -> String {
let mut out = String::new();
for c in cp.chars() {
out.push_str(match c {
'N' => "north",
'E' => "east",
'S' => "south",
'W' => "west",
'b' => " by ",
_ => "-",
});
}
out
}
fn main()... |
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 |... | #Maple | Maple |
with(Bits):
bit:=proc(A,B)
local a,b,c,d,e,f,g,h,i,x,bitpow;
bitpow := 2^B:
a:=And(A,B);
b:=Not(A);
c:=Or(A,B);
d:=Xor(A,B);
#Left Shift
e:= irem(2*A,bitpow);
#Right Shift
f := iquo(A,2);
#Left Rotate
g:= irem(2*A,bitpow,'x')+x;
#Rightarithshift
i:= iquo(A,2)+bitpow/2*irem(A,bitpow/2);
return a,b,c,d,e,f,g,i;
end pro... |
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... | #RapidQ | RapidQ | DECLARE SUB PaintCanvas
CREATE form AS QForm
Width = 640
Height = 480
CREATE canvas AS QCanvas
Height = form.ClientHeight
Width = form.ClientWidth
OnPaint = PaintCanvas
END CREATE
END CREATE
SUB PaintCanvas
' Fill background
canvas.FillRect(0, 0, canvas.Width, canvas.Height, &H... |
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... | #REXX | REXX | /*REXX program demonstrates how to process/display a simple RGB raster graphics image.*/
red = 'ff 00 00'x /*a method to define a red value. */
blue = '00 00 ff'x /*" " " " " blue " */
@. = ... |
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... | #Raku | Raku | sub benford(@a) { bag +« @a».substr(0,1) }
sub show(%distribution) {
printf "%9s %9s %s\n", <Actual Expected Deviation>;
for 1 .. 9 -> $digit {
my $actual = %distribution{$digit} * 100 / [+] %distribution.values;
my $expected = (1 + 1 / $digit).log(10) * 100;
printf "%d: %5.2f%% | %5.... |
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... | #Racket | Racket | #lang racket
;; For: http://rosettacode.org/wiki/Bernoulli_numbers
;; As described in task...
(define (bernoulli.1 n)
(define A (make-vector (add1 n)))
(for ((m (in-range 0 (add1 n))))
(vector-set! A m (/ (add1 m)))
(for ((j (in-range m (sub1 1) -1)))
(define new-A_j-1 (* j (- (vector-ref A (sub1 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... | #Factor | Factor | USING: binary-search kernel math.order ;
: binary-search ( seq elt -- index/f )
[ [ <=> ] curry search ] keep = [ drop f ] unless ; |
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... | #Racket | Racket |
#lang racket
(define (best-shuffle s)
(define len (string-length s))
(define @ string-ref)
(define r (list->string (shuffle (string->list s))))
(for* ([i (in-range len)] [j (in-range len)])
(when (not (or (= i j) (eq? (@ s i) (@ r j)) (eq? (@ s j) (@ r i))))
(define t (@ r i))
(string-set! 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... | #Raku | Raku | sub best-shuffle(Str $orig) {
my @s = $orig.comb;
my @t = @s.pick(*);
for ^@s -> $i {
for ^@s -> $j {
if $i != $j and @t[$i] ne @s[$j] and @t[$j] ne @s[$i] {
@t[$i, $j] = @t[$j, $i];
last;
}
}
}
my $count = 0;
for @t.k... |
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
... | #Component_Pascal | Component Pascal |
MODULE BinaryDigits;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
str : ARRAY 33 OF CHAR;
BEGIN
Strings.IntToStringForm(5,2, 1,'0',FALSE,str);
StdLog.Int(5);StdLog.String(":> " + str);StdLog.Ln;
Strings.IntToStringForm(50,2, 1,'0',FALSE,str);
StdLog.Int(50);StdLog.String(":> " + str);StdLog.Ln;
Strings.IntToStri... |
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.
| #Rust | Rust |
struct Point {
x: i32,
y: i32
}
fn main() {
let mut points: Vec<Point> = Vec::new();
points.append(&mut get_coordinates(1, 20, 20, 28));
points.append(&mut get_coordinates(20, 28, 69, 0));
draw_line(points, 70, 30);
}
fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> {
... |
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... | #Scala | Scala | object BoxingTheCompass extends App {
val cardinal = List("north", "east", "south", "west")
val pointDesc = List("1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1")
val pointDeg: Int => Double = i => {
val fswitch: Int => Int = i => i match {case 1 => 1; case 2 => -1; case _ => 0}
i*11.25+fswitch(... |
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 |... | #Mathematica.2F_Wolfram_Language | Mathematica/ Wolfram Language | (*and xor and or*)
BitAnd[integer1, integer2]
BitXor[integer1, integer2]
BitOr[integer1, integer2]
(*logical not*)
BitNot[integer1]
(*left and right shift*)
BitShiftLeft[integer1]
BitShiftRight[integer1]
(*rotate digits left and right*)
FromDigits[RotateLeft[IntegerDigits[integer1, 2]], 2]
FromDigits[RotateRight[... |
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... | #Ruby | Ruby | class RGBColour
def initialize(red, green, blue)
unless red.between?(0,255) and green.between?(0,255) and blue.between?(0,255)
raise ArgumentError, "invalid RGB parameters: #{[red, green, blue].inspect}"
end
@red, @green, @blue = red, green, blue
end
attr_reader :red, :green, :blue
alias_metho... |
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... | #REXX | REXX | /*REXX pgm demonstrates Benford's law applied to 2 common functions (30 dec. digs used).*/
numeric digits length( e() ) - length(.) /*width of (e) for LN & LOG precision.*/
parse arg N .; if N=='' | N=="," then N= 1000 /*allow sample size to be specified. */
pad= " " ... |
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... | #Raku | Raku | sub bernoulli($n) {
my @a;
for 0..$n -> $m {
@a[$m] = FatRat.new(1, $m + 1);
for reverse 1..$m -> $j {
@a[$j - 1] = $j * (@a[$j - 1] - @a[$j]);
}
}
return @a[0];
}
constant @bpairs = grep *.value.so, ($_ => bernoulli($_) for 0..60);
my $width = max @bpairs.map: *.va... |
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... | #FBSL | FBSL | #APPTYPE CONSOLE
DIM va[], sign = {1, -1}, toggle
PRINT "Loading ... ";
DIM gtc = GetTickCount()
FOR DIM i = 0 TO 1000000
va[] = sign[toggle] * PI * i
toggle = NOT toggle ' randomize the array
NEXT
PRINT "done in ", GetTickCount() - gtc, " milliseconds"
PRINT "Sorting ... ";
gtc = GetTickCount()
QUICKSORT(va) ... |
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... | #Rascal | Rascal | import Prelude;
public tuple[str, str, int] bestShuffle(str s){
characters = chars(s);
ranking = {<p, countSame(p, characters)> | p <- permutations(characters)};
best = {<s, stringChars(p), n> | <p, n> <- ranking, n == min(range(ranking))};
return takeOneFrom(best)[0];
}
public int countSame(l... |
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... | #REXX | REXX | /*REXX program determines and displays the best shuffle for any list of words or tokens.*/
parse arg $ /*get some words from the command line.*/
if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/
w=0; #=words($) ... |
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
... | #Cowgol | Cowgol | include "cowgol.coh";
sub print_binary(n: uint32) is
var buffer: uint8[33];
var p := &buffer[32];
[p] := 0;
while n != 0 loop
p := @prev p;
[p] := ((n as uint8) & 1) + '0';
n := n >> 1;
end loop;
print(p);
print_nl();
end sub;
print_binary(5);
print_binary(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.
| #Scala | Scala | object BitmapOps {
def bresenham(bm:RgbBitmap, x0:Int, y0:Int, x1:Int, y1:Int, c:Color)={
val dx=math.abs(x1-x0)
val sx=if (x0<x1) 1 else -1
val dy=math.abs(y1-y0)
val sy=if (y0<y1) 1 else -1
def it=new Iterator[Tuple2[Int,Int]]{
var x=x0; var y=y0
var err=(if (dx>dy... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const array string: names is [] ("North", "North by east", "North-northeast", "Northeast by north",
"Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south",
"East-southeast", "Southeast by east", "Southeast", "Southeast by sou... |
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 |... | #MATLAB_.2F_Octave | MATLAB / Octave | function bitwiseOps(a,b)
disp(sprintf('%d and %d = %d', [a b bitand(a,b)]));
disp(sprintf('%d or %d = %d', [a b bitor(a,b)]));
disp(sprintf('%d xor %d = %d', [a b bitxor(a,b)]));
disp(sprintf('%d << %d = %d', [a b bitshift(a,b)]));
disp(sprintf('%d >> %d = %d', [a b bitshift(a,-b)]));
end |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixe... | #Rust | Rust | #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub fn new(r: u8, g: u8, b: u8) -> Self {
Rgb { r, g, b }
}
pub const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 };
pub const RED: Rgb = Rgb { r: 255, g: 0, b: 0 };
pub const ... |
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... | #Scala | Scala | import java.awt.image.BufferedImage
import java.awt.Color
class RgbBitmap(val width:Int, val height:Int) {
val image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def fill(c:Color)={
val g=image.getGraphics()
g.setColor(c)
g.fillRect(0, 0, width, height)
}
def setPix... |
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... | #Ring | Ring |
# Project : Benford's law
decimals(3)
n= 1000
actual = list(n)
for x = 1 to len(actual)
actual[x] = 0
next
for nr = 1 to n
n1 = string(fibonacci(nr))
j = number(left(n1,1))
actual[j] = actual[j] + 1
next
see "Digit " + "Actual " + "Expected" + nl
for m = 1 to 9
fr = frequency(m)*100... |
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... | #Ruby | Ruby | EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}
def fib(n)
a,b = 0,1
n.times.map{ret, a, b = a, b, a+b; ret}
end
# powers of 3 as a test sequence
def power_of_threes(n)
n.times.map{|k| 3**k}
end
def heads(s)
s.map{|a| a.to_s[0].to_i}
end
def show_dist(title, s)
s = heads(s)
c = Array.new(10, 0)
s.e... |
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... | #REXX | REXX | /*REXX program calculates N number of Bernoulli numbers expressed as vulgar fractions.*/
parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/
numeric digits max(9, n*2) /*increase the decimal digits if needed*/
w= max(length(N), 4); Nw= N + w + N % 4... |
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... | #Forth | Forth | defer (compare)
' - is (compare) \ default to numbers
: cstr-compare ( cstr1 cstr2 -- <=> ) \ counted strings
swap count rot count compare ;
: mid ( u l -- mid ) tuck - 2/ -cell and + ;
: bsearch ( item upper lower -- where found? )
rot >r
begin 2dup >
while 2dup mid
dup @ r@ (compare)
... |
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... | #Ring | Ring |
# Project : Best shuffle
test = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]
for n = 1 to len(test)
bs = bestshuffle(test[n])
count = 0
for p = 1 to len(test[n])
if substr(test[n],p,1) = substr(bs,p,1)
count = count + 1
ok
next
see test[n] ... |
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... | #Ruby | Ruby | def best_shuffle(s)
# Fill _pos_ with positions in the order
# that we want to fill them.
pos = []
# g["a"] = [2, 4] implies that s[2] == s[4] == "a"
g = s.length.times.group_by { |i| s[i] }
# k sorts letters from low to high count
k = g.sort_by { |k, v| v.length }.map { |k, v| k }
until g.empty?
... |
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
... | #Crystal | Crystal | [5,50,9000].each do |n|
puts "%b" % n
end |
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.
| #Sidef | Sidef | func my_draw_line(img, x0, y0, x1, y1) {
var steep = (abs(y1 - y0) > abs(x1 - x0))
if (steep) {
(y0, x0) = (x0, y0)
(y1, x1) = (x1, y1)
}
if (x0 > x1) {
(x1, x0) = (x0, x1)
(y1, y0) = (y0, y1)
}
var deltax = (x1 - x0)
var deltay = abs(y1 - y0)
var er... |
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... | #Sidef | Sidef | func point (index) {
var ix = (index % 32);
if (ix & 1) { "#{point((ix + 1) & 28)} by #{point(((2 - (ix & 2)) * 4) + ix & 24)}" }
elsif (ix & 2) { "#{point((ix + 2) & 24)}-#{point((ix | 4) & 28)}" }
elsif (ix & 4) { "#{point((ix + 8) & 16)}#{point((ix | 8) & 24)}" }
else { <north east s... |
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 |... | #Maxima | Maxima | load(functs)$
a: 3661$
b: 2541$
logor(a, b);
/* 4077 */
logand(a, b);
/* 2125 */
logxor(a, b);
/* 1952 */
/* NOT(x) is simply -x - 1
-a - 1;
/* -3662 */
logor(a, -a - 1);
/* -1 */
logand(a, -a - 1);
/* 0 */ |
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... | #Scheme | Scheme | (define (make-list length object)
(if (= length 0)
(list)
(cons object (make-list (- length 1) object))))
(define (list-fill! list object)
(if (not (null? list))
(begin (set-car! list object) (list-fill! (cdr list) object))))
(define (list-set! list element object)
(if (= element 1)
(s... |
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... | #Run_BASIC | Run BASIC |
N = 1000
for i = 0 to N - 1
n$ = str$(fibonacci(i))
j = val(left$(n$,1))
actual(j) = actual(j) +1
next
print
html "<table border=1><TR bgcolor=wheat><TD>Digit<td>Actual<td>Expected</td><tr>"
for i = 1 to 9
html "<tr align=right><td>";i;"</td><td>";using("##.###",actual(i)/10);"</td><td>";using("##.###"... |
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... | #Rust | Rust |
extern crate num_traits;
extern crate num;
use num::bigint::{BigInt, ToBigInt};
use num_traits::{Zero, One};
use std::collections::HashMap;
// Return a vector of all fibonacci results from fib(1) to fib(n)
fn fib(n: usize) -> Vec<BigInt> {
let mut result = Vec::with_capacity(n);
let mut a = BigInt::zero()... |
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... | #Ruby | Ruby | bernoulli = Enumerator.new do |y|
ar = []
0.step do |m|
ar << Rational(1, m+1)
m.downto(1){|j| ar[j-1] = j*(ar[j-1] - ar[j]) }
y << ar.first # yield
end
end
b_nums = bernoulli.take(61)
width = b_nums.map{|b| b.numerator.to_s.size}.max
b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, widt... |
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... | #Fortran | Fortran | recursive function binarySearch_R (a, value) result (bsresult)
real, intent(in) :: a(:), value
integer :: bsresult, mid
mid = size(a)/2 + 1
if (size(a) == 0) then
bsresult = 0 ! not found
else if (a(mid) > value) then
bsresult= binarySearch_R(a(:mid-1), value)
e... |
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... | #Run_BASIC | Run BASIC | list$ = "abracadabra seesaw pop grrrrrr up a"
while word$(list$,ii + 1," ") <> ""
ii = ii + 1
w$ = word$(list$,ii," ")
bs$ = bestShuffle$(w$)
count = 0
for i = 1 to len(w$)
if mid$(w$,i,1) = mid$(bs$,i,1) then count = count + 1
next i
print w$;" ";bs$;" ";count
wend
function bestShuffle$(s1$)
... |
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... | #Rust | Rust | extern crate permutohedron;
extern crate rand;
use std::cmp::{min, Ordering};
use std::env;
use rand::{thread_rng, Rng};
use std::str;
const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];
#[derive(Eq)]
struct Solution {
original: String,
shuffled: String,
sco... |
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
... | #D | D | void main() {
import std.stdio;
foreach (immutable i; 0 .. 16)
writefln("%b", i);
} |
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.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc drawLine {image colour point0 point1} {
lassign $point0 x0 y0
lassign $point1 x1 y1
set steep [expr {abs($y1 - $y0) > abs($x1 - $x0)}]
if {$steep} {
lassign [list $x0 $y0] y0 x0
lassign [list $x1 $y1] y1 x1
}
if {$x0 > $x1} {
... |
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... | #smart_BASIC | smart BASIC | /*Boxing The Compass by rbytes December 2017*/
GET SCREEN SIZE sw,sh
OPTION BASE 1
DIM point$(32,5)
FOR i=1 TO 32
FOR j=1 TO 5
READ point$(i,j)
NEXT j
NEXT i
html$= "<table border=1>"
html$&= "<TR><TD align=right></td><td>Boxing The Compass</td><td>Abbr</td><td>Min</td><td>Med</td><td>Max</td></tr>"
FOR i =1 TO 32
h... |
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 |... | #MAXScript | MAXScript | fn bitwise a b =
(
format "a and b: %\n" (bit.and a b)
format "a or b: %\n" (bit.or a b)
format "a xor b: %\n" (bit.xor a b)
format "not a: %\n" (bit.not a)
format "Left shift a: %\n" (bit.shift a b)
format "Right shift a: %\n" (bit.shift a -b)
)
bitwise 255 170 |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
const proc: main is func
local
var PRIMITIVE_WINDOW: myPixmap is PRIMITIVE_WINDOW.value;
var color: myColor is black;
begin
myPixmap := newPixmap(300, 200);
clear(myPixmap, light_green);
point(myPixmap, 20, 30, color(256, 512, 768));
myColor ... |
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... | #SequenceL | SequenceL | RGB ::= (R: int(0), G: int(0), B: int(0));
newBitmap: int * int -> RGB(2);
newBitmap(width, height)[y, x] :=
(R: 0, G: 0, B: 0)
foreach y within 1 ... height,
x within 1 ... width;
fill: RGB(2) * RGB -> RGB(2);
fill(bitmap(2), color)[y, x] :=
color
foreach y within 1 ... size(bitmap),
x within 1 ... ... |
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... | #Scala | Scala | // Fibonacci Sequence (begining with 1,1): 1 1 2 3 5 8 13 21 34 55 ...
val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail }
/**
* Given a numeric sequence, return the distribution of the most-signicant-digit
* as expected by Benford's Law and ... |
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... | #Rust | Rust | // 2.5 implementations presented here: naive, optimized, and an iterator using
// the optimized function. The speeds vary significantly: relative
// speeds of optimized:iterator:naive implementations is 625:25:1.
#![feature(test)]
extern crate num;
extern crate test;
use num::bigint::{BigInt, ToBigInt};
use num:... |
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... | #Futhark | Futhark |
fun main(as: [n]int, value: int): int =
let low = 0
let high = n-1
loop ((low,high)) = while low <= high do
-- invariants: value > as[i] for all i < low
-- value < as[i] for all i > high
let mid = (low+high) / 2
in if as[mid] > value
then (low, mid - 1)
else if as[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... | #Scala | Scala |
def coincidients(s1: Seq[Char], s2: Seq[Char]): Int = (s1, s2).zipped.count(p => (p._1 == p._2))
def freqMap(s1: List[Char]) = s1.groupBy(_.toChar).mapValues(_.size)
def estimate(s1: List[Char]): Int = if (s1 == Nil) 0 else List(0, freqMap(s1).maxBy(_._2)._2 - (s1.size / 2)).max
def bestShuffle(s: String): ... |
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
... | #Dart | Dart | String binary(int n) {
if(n<0)
throw new IllegalArgumentException("negative numbers require 2s complement");
if(n==0) return "0";
String res="";
while(n>0) {
res=(n%2).toString()+res;
n=(n/2).toInt();
}
return res;
}
main() {
print(binary(0));
print(binary(1));
print(binary(5));
print(... |
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.
| #TI-89_BASIC | TI-89 BASIC | (lx0, ly0, lx1, ly1)
Prgm
Local steep, x, y, dx, dy, ystep, error, tmp
abs(ly1 - ly0) > abs(lx1 - lx0) → steep
If steep Then
lx0 → tmp
ly0 → lx0
tmp → ly0
lx1 → tmp
ly1 → lx1
tmp → ly1
EndIf
If lx0 > lx1 Then
lx0 → tmp
lx1 → lx0
tmp → lx1
ly0 → tmp
ly1 → ly0
tmp... |
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... | #Tcl | Tcl | proc angle2compass {angle} {
set dirs {
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
}
set unpack {N "north" E "east" W "west" S "south" b " by "}
# Compute the width of each compass segment
set sep [expr {360... |
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 |... | #ML.2FI | ML/I | MCSKIP "WITH" NL
"" Bitwise operations
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
a and b = %%T1.&%T2..
a or b = %%T1.|%T2..
The other operators are not supported.
MCSET S10=0
>
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=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... | #Smalltalk | Smalltalk | |img1 img2|
"a depth24 RGB image"
img1 := Image width:100 height:200 depth:24.
img1 fillRectangle:(0@0 corner:100@100) with:Color red.
img1 fillRectangle:(0@100 corner:100@100) with:(Color rgbValue: 16rFF00FF).
img1 colorAt:(10 @ 10) put:(Color green).
img1 saveOn:'sampleFile.png'.
img1 displayOn:Transcript window gr... |
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... | #Scheme | Scheme | ; Compute the probability of leading digit d (an integer [1,9]) according to Benford's law.
(define benford-probability
(lambda (d)
(- (log (1+ d) 10) (log d 10))))
; Determine the distribution of the leading digit of the sequence provided by the given
; generator. Return as a vector of 10 elements -- the 0t... |
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... | #Scala | Scala | /** Roll our own pared-down BigFraction class just for these Bernoulli Numbers */
case class BFraction( numerator:BigInt, denominator:BigInt ) {
require( denominator != BigInt(0), "Denominator cannot be zero" )
val gcd = numerator.gcd(denominator)
val num = numerator / gcd
val den = denominator / gcd
de... |
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... | #GAP | GAP | Find := function(v, x)
local low, high, mid;
low := 1;
high := Length(v);
while low <= high do
mid := QuoInt(low + high, 2);
if v[mid] > x then
high := mid - 1;
elif v[mid] < x then
low := mid + 1;
else
return mid;
fi;
od;
return fail;
end;
u := [1..10]*7;
# [ 7, 14, ... |
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... | #Scheme | Scheme |
(define count
(lambda (str1 str2)
(let ((len (string-length str1)))
(let loop ((index 0)
(result 0))
(if (= index len)
result
(loop (+ index 1)
(if (eq? (string-ref str1 index)
(string-ref str2 index))
... |
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
... | #dc | dc | 2o 5p 50p 9000p |
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.
| #VBScript | VBScript | 'Bitmap/Bresenham's line algorithm - VBScript - 13/05/2019
Dim map(48,40), list(10), ox, oy
data=Array(1,8, 8,16, 16,8, 8,1, 1,8)
For i=0 To UBound(map,1): For j=0 To UBound(map,2)
map(i,j)="."
Next: Next 'j, i
points=(UBound(data)+1)/2
For p=1 To points
x=data((p-1)*2)
y=data((p-1)*2+1)
list(p)=Array(x,... |
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... | #True_BASIC | True BASIC | DIM POINT$(32)
FUNCTION compasspoint$ (h)
LET x = h / 11.25 + 1.5
IF (x >= 33) THEN LET x = x - 32
LET compasspoint$ = POINT$(INT(x))
END FUNCTION
RESTORE
DATA "North ", "North by east ", "North-northeast ", "Northeast by north"
DATA "Northeast ", "Northeast by east ", "East-... |
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.