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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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(Word.Not(a)) & "\n");
c := a;
IO.Put("c LeftShift b: " & Fmt.Unsigned(Word.LeftShift(c, b)) & "\n");
IO.Put("c RightShift b: " & Fmt.Unsigned(Word.RightShift(c, b)) & "\n");
IO.Put("c LeftRotate b: " & Fmt.Unsigned(Word.LeftRotate(c, b)) & "\n");
IO.Put("c RightRotate b: " & Fmt.Unsigned(Word.RightRotate(c, b)) & "\n");
END Bitwise;
BEGIN
Bitwise(255, 5);
END Bitwise. |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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 colour point} {
lassign $point x y
$image put $colour -to [max 0 $x] [max 0 $y]
}
proc getPixel {image point} {
lassign $point x y
# [$img get] returns a list: {r g b}; this proc should return a colour value
format {#%02x%02x%02x} {*}[$image get $x $y]
}
# create the image and display it
set img [newImage 150 150]
label .l -image $img
pack .l
fill $img red
setPixel $img green {40 40}
set rbg [getPixel $img {40 40}] |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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(
i, "%.2f".sprintf(100 * actuals[i - 1]),
"%.2f".sprintf(100 * expected[i - 1]),
)
} |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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))))))
(vector-ref a 0))))
; Convert a rational to a string. If an integer, ends with "/1".
(define rational->string
(lambda (rational)
(format "~a/~a" (numerator rational) (denominator rational))))
; Returns the string length of the numerator of a rational.
(define rational-numerator-length
(lambda (rational)
(string-length (format "~a" (numerator rational)))))
; Formats a rational with left-padding such that total length to the slash is as given.
(define rational-padded
(lambda (rational total-length-to-slash)
(let* ((length-padding (- total-length-to-slash (rational-numerator-length rational)))
(padding-string (make-string length-padding #\ )))
(string-append padding-string (rational->string rational)))))
; Return the Bernoulli numbers 0 through n in a list.
(define make-bernoulli-list
(lambda (n)
(if (= n 0)
(list (bernoulli n))
(append (make-bernoulli-list (1- n)) (list (bernoulli n))))))
; Print the non-zero Bernoulli numbers 0 through 60 aligning the slashes.
(let* ((bernoullis-list (make-bernoulli-list 60))
(numerator-lengths (map rational-numerator-length bernoullis-list))
(max-numerator-length (apply max numerator-lengths)))
(let print-bernoulli ((index 0) (numbers bernoullis-list))
(cond
((null? numbers))
((= 0 (car numbers))
(print-bernoulli (1+ index) (cdr numbers)))
(else
(printf "B(~2@a) = ~a~%" index (rational-padded (car numbers) max-numerator-length))
(print-bernoulli (1+ index) (cdr numbers)))))) |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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 <> j and stri[i] <> shuffled[j] and stri[j] <> shuffled[i] then
tmp := shuffled[i];
shuffled @:= [i] shuffled[j];
shuffled @:= [j] tmp;
end if;
end for;
end for;
end func;
const proc: main is func
local
const array string: testData is [] ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a");
var string: original is "";
var string: shuffled is "";
var integer: j is 0;
var integer: score is 0;
begin
for original range testData do
shuffled := bestShuffle(original);
score := 0;
for key j range shuffled do
if original[j] = shuffled[j] then
incr(score);
end if;
end for;
writeln(original <& ", " <& shuffled <& ", (" <& score <& ")");
end for;
end func; |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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))
}
for word (<abracadabra seesaw elk grrrrrr up a>) {
var (sword, score) = best_shuffle(word)
"%-12s %12s: %d\n".printf(word, sword, score)
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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));
writeln('9000: '+IntToBinStr(9000));
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.
| #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 } else { #34=-1 } // x step
if (#2 < #4) { #35=1 } else { #35=-1 } // y step
if (#32 > #31) { // steep angle, step by Y
#33 = #32 / 2 // error distance
while (#2 <= #4) {
Call("DRAW_PIXEL")
#33 -= #31
if (#33 < 0) {
#1 += #34 // move right
#33 += #32
}
#2++ // move up
}
} else { // not steep, step by X
#33 = #31 / 2
while (#1 <= #3) {
Call("DRAW_PIXEL")
#33 -= #32
if (#33 < 0) {
#2 += #35 // move up
#33 += #31
}
#1++ // move right
}
}
Num_Pop(31,35)
return |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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 Step -1 ' Now read the values, but reverse
@(x) = Pop() ' Since the last value is on top
Next ' of the data stack
For x = 0 To 32 ' Here comes the payload
j = ((@(x) * 32 / 3600) + 5) / 10 ' Scale by ten, then correct
Print Using "_#";(j % 32) + 1;" "; ' Print heading
GoSub 100 + ((j % 32) * 10) ' Now get the compass point
Print Using "__#.##"; @(x) ' Finally, print the angle
' which is scaled by 100
Next
End
' All compass points
100 Print "North "; : Return
110 Print "North by east "; : Return
120 Print "North-northeast "; : Return
130 Print "Northeast by north "; : Return
140 Print "Northeast "; : Return
150 Print "Northeast by east "; : Return
160 Print "East-northeast "; : Return
170 Print "East by north "; : Return
180 Print "East "; : Return
190 Print "East by south "; : Return
200 Print "East-southeast "; : Return
210 Print "Southeast by east "; : Return
220 Print "Southeast "; : Return
230 Print "Southeast by south "; : Return
240 Print "South-southeast "; : Return
250 Print "South by east "; : Return
260 Print "South "; : Return
270 Print "South by west "; : Return
280 Print "South-southwest "; : Return
290 Print "Southwest by south "; : Return
300 Print "Southwest "; : Return
310 Print "Southwest by west "; : Return
320 Print "West-southwest "; : Return
330 Print "West by south "; : Return
340 Print "West "; : Return
350 Print "West by north "; : Return
360 Print "West-northwest "; : Return
370 Print "Northwest by west "; : Return
380 Print "Northwest "; : Return
390 Print "Northwest by north "; : Return
400 Print "North-northwest "; : Return
410 Print "North by west "; : Return
420 Print "North "; : Return |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 = $loader.loadprim("std@int32_or", 2);
var int32_xor = $loader.loadprim("std@int32_xor", 2);
var int32_shl = $loader.loadprim("std@int32_shl", 2);
var int32_shr = $loader.loadprim("std@int32_shr", 2);
var int32_ushr = $loader.loadprim("std@int32_ushr", 2);
var int32_complement = $loader.loadprim("std@int32_complement", 1);
// Function to show bitwise operations on a,b
var bitwise = function(a, b) {
var ia = int32_new(a);
var ib = int32_new(b);
$print("Neko 32 bit integer library\n");
$print("a AND b: ", a, " ", b, " ", int32_and(ia, ib), "\n");
$print("a OR b: ", a, " ", b, " ", int32_or(ia, ib), "\n");
$print("a XOR b: ", a, " ", b, " ", int32_xor(ia, ib), "\n");
$print("ones complement a: ", a, " ", int32_complement(ia), "\n");
$print("a SHL b: ", a, " ", b, " ", int32_shl(ia, ib), "\n");
$print("a SHR b: ", a, " ", b, " ", int32_shr(ia, ib), "\n");
$print("a USHR b: ", a, " ", b, " ", int32_ushr(ia, ib), "\n");
$print("a ROL b: is not directly supported in Neko Int32\n");
$print("a ROR b: is not directly supported in Neko Int32\n");
$print("\nNormal Neko 31 bit signed integers\n");
a = $int(a);
b = $int(b);
$print("a AND b: ", a, " ", b, " ", a & b, "\n");
$print("a OR b: ", a, " ", b, " ", a | b, "\n");
$print("a XOR b: ", a, " ", b, " ", a ^ b, "\n");
$print("NOT a: is not directly supported in Neko syntax\n");
$print("a SHL b: ", a, " ", b, " ", a << b, "\n");
$print("a SHR b: ", a, " ", b, " ", a >> b, "\n");
$print("a USHR b: ", a, " ", b, " ", a >>> b, "\n");
$print("a ROL b: is not directly supported in Neko syntax\n");
$print("a ROR b: is not directly supported in Neko syntax\n");
}
// Pass command line arguments to the demo function
// initially as float, to ensure no internal bit truncation
var a = $float($loader.args[0]);
var b = $float($loader.args[1]);
if a == null a = 0;
if b == null b = 0;
bitwise(a,b); |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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 255"; }
function yellow { print "255 255 0"; }
function magenta { print "255 0 255"; }
function cyan { print "0 255 255"; }
)
typeset -T Bitmap_t=(
integer height
integer width
typeset -a data
function fill {
typeset color=$1
if [[ -z ${color:+set} ]]; then
print -u2 "error: no fill color specified"
return 1
fi
integer x y
for ((y=0; y<_.height; y++)); do
for ((x=0; x<_.width; x++)); do
_.data[y][x]="$color"
done
done
}
function setpixel {
integer x=$1 y=$2
typeset color=$3
_.data[y][x]=$color
}
function getpixel {
integer x=$1 y=$2
print "${_.data[y][x]}"
}
function to_s {
typeset ppm=""
ppm+="P3"$'\n'
ppm+="${_.width} ${_.height}"$'\n'
ppm+="255"$'\n'
typeset sep
for ((y=0; y<_.height; y++)); do
sep=""
for ((x=0; x<_.width; x++)); do
ppm+="$sep${_.data[y][x]}"
sep=" "
done
ppm+=$'\n'
done
print -- "$ppm"
}
)
RGBColor_t color
Bitmap_t b=( width=3 height=2 )
b.fill "$(color.white)"
b.setpixel 0 0 "$(color.red)"
b.setpixel 1 0 "$(color.green)"
b.setpixel 2 0 "$(color.blue)"
b.setpixel 0 1 "$(color.yellow)"
b.setpixel 1 1 "$(color.white)"
b.setpixel 2 1 "$(color.black)"
echo "$(b.getpixel 0 0)"
b.to_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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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(num) AS penult FROM benford WHERE num NOT IN (SELECT MAX(num) FROM benford))
-- Repeat as many times as desired
-- in Oracle SQL*Plus, press "Slash, Enter" a lot of times
-- or wrap this in a loop, but that will require something db-specific...
-- Do sums
SELECT
digit,
COUNT(digit) / numbers AS actual,
log(10, 1 + 1 / digit) AS expected
FROM
(
SELECT
FLOOR(num/POWER(10,LENGTH(num)-1)) AS digit
FROM
benford
),
(
SELECT
COUNT(*) AS numbers
FROM
benford
)
GROUP BY digit, numbers
ORDER BY digit;
-- Tidy up
DROP TABLE benford; |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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 bigRational.value;
for m range 0 to n do
a[m] := 1_ / bigInteger(succ(m));
for j range m downto 1 do
a[pred(j)] := bigRational(j) * (a[j] - a[pred(j)]);
end for;
end for;
bernoulli := a[0];
end func;
const proc: main is func
local
var bigRational: bernoulli is bigRational.value;
var integer: i is 0;
begin
for i range 0 to 60 do
bernoulli := bernoulli(i);
if bernoulli <> bigRational.value then
writeln("B(" <& i lpad 2 <& ") = " <& bernoulli.numerator lpad 44 <&
" / " <& bernoulli.denominator rpad 8 <& " " <& bernoulli);
end if;
end for;
end func; |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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[(m + 1)..<n],key, offset + m + 1) \
: [index: offset + m]
}
|
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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
set score [llength $origin]
struct::list foreachperm p $origin {
if {$score > [set score [tcl::mathfunc::min $score [count $origin $p]]]} {
set best $p
}
}
set best [join $best ""]
return "$str,$best,($score)"
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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)
y y0)
for x x0 (x <= x1) ++x
if steep
plot y x
plot x y
error -= deltay
when (error < 0)
y += ystep
error += deltax |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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.62 50.63 67.50
84.37 84.38 101.25 118.12 118.13 135.00 151.87
151.88 168.75 185.62 185.63 202.50 219.37 219.38
236.25 253.12 253.13 270.00 286.87 286.88 303.75
320.62 320.63 337.50 354.37 354.38 )
capitalize() {
printf '%s%s\n' "$(tr a-z A-Z <<<"${1:0:1}")" "${1:1}"
}
# convert compass point abbreviation to full text of label
function expand_point {
local label=$1
set -- N north E east S south W west b " by "
while (( $# )); do
label=${label//$1/$2}
shift 2
done
capitalize "$label"
}
# modulus function that returns 1..N instead of 0..N-1
function amod {
echo $(( ($1 - 1) % $2 + 1 ))
}
# convert a compass angle from degrees into a box index (1..32)
function compass_point {
# use bc or dc depending on what's on the system
#amod $(dc <<<"$1 5.625 + 11.25 / 1 + p") 32
amod $(bc <<<"($1 + 5.625) / 11.25 + 1") 32
}
# Now output the table of test data
header_format="%-7s | %-18s | %s\n"
row_format="%7.2f | %-18s | %2d\n"
printf "$header_format" "Degrees" "Closest Point" "Index"
for angle in ${test_angles[@]}; do
let index=$(compass_point $angle)
abbr=${compass_points[index-1]}
label="$(expand_point $abbr)"
printf "$row_format" $angle "$label" $index
done |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 integral type,
// the operator performs an arithmetic shift right
WriteLine($"$(i :> uint) rshift $j is $(c >> j)"); // When the left operand of the >> operator is of an unsigned integral type,
// the operator performs a logical shift right
// there are no rotation operators in Nemerle, but you could define your own w/ a macro if you really wanted it |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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 255"; }
function yellow { print "255 255 0"; }
function magenta { print "255 0 255"; }
function cyan { print "0 255 255"; }
)
typeset -T Bitmap_t=(
integer height
integer width
typeset -a data
function fill {
typeset color=$1
if [[ -z ${color:+set} ]]; then
print -u2 "error: no fill color specified"
return 1
fi
integer x y
for ((y=0; y<_.height; y++)); do
for ((x=0; x<_.width; x++)); do
_.data[y][x]="$color"
done
done
}
function setpixel {
integer x=$1 y=$2
typeset color=$3
_.data[y][x]=$color
}
function getpixel {
integer x=$1 y=$2
print "${_.data[y][x]}"
}
function to_s {
typeset ppm=""
ppm+="P3"$'\n'
ppm+="${_.width} ${_.height}"$'\n'
ppm+="255"$'\n'
typeset sep
for ((y=0; y<_.height; y++)); do
sep=""
for ((x=0; x<_.width; x++)); do
ppm+="$sep${_.data[y][x]}"
sep=" "
done
ppm+=$'\n'
done
print -- "$ppm"
}
)
RGBColor_t color
Bitmap_t b=( width=3 height=2 )
b.fill "$(color.white)"
b.setpixel 0 0 "$(color.red)"
b.setpixel 1 0 "$(color.green)"
b.setpixel 2 0 "$(color.blue)"
b.setpixel 0 1 "$(color.yellow)"
b.setpixel 1 1 "$(color.white)"
b.setpixel 2 1 "$(color.black)"
echo "$(b.getpixel 0 0)"
b.to_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 frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 probabilities
f,p
1 2
+-----------------------------+
1 | 297 301.0299957 |
2 | 178 176.0912591 |
3 | 127 124.9387366 |
4 | 96 96.91001301 |
5 | 80 79.18124605 |
6 | 67 66.94678963 |
7 | 57 57.99194698 |
8 | 53 51.15252245 |
9 | 45 45.75749056 |
+-----------------------------+ |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 {
print("Could not read from file!")
exit(-1)
}
return ret
}
/* Calculates the probability following Benford's law */
func benford(digit z:Int) -> Double {
if z<=0 || z>9 {
perror("Argument must be between 1 and 9.")
return 0
}
return log10(Double(1)+Double(1)/Double(z))
}
// get CLI input
if CommandLine.arguments.count < 2 {
print("Usage: Benford [FILE]")
exit(-1)
}
let pathToFile = CommandLine.arguments[1]
// Read from given file and parse into lines
let content = readFromFile(fileName: pathToFile)
let lines = content.components(separatedBy: "\n")
var digitCount:UInt64 = 0
var countDigit:[UInt64] = [0,0,0,0,0,0,0,0,0]
// check digits line by line
for line in lines {
if line == "" {
continue
}
let charLine = Array(line.characters)
switch(charLine[0]){
case "1":
countDigit[0] += 1
digitCount += 1
break
case "2":
countDigit[1] += 1
digitCount += 1
break
case "3":
countDigit[2] += 1
digitCount += 1
break
case "4":
countDigit[3] += 1
digitCount += 1
break
case "5":
countDigit[4] += 1
digitCount += 1
break
case "6":
countDigit[5] += 1
digitCount += 1
break
case "7":
countDigit[6] += 1
digitCount += 1
break
case "8":
countDigit[7] += 1
digitCount += 1
break
case "9":
countDigit[8] += 1
digitCount += 1
break
default:
break
}
}
// print result
print("Digit\tBenford [%]\tObserved [%]\tDeviation")
print("~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~")
for i in 0..<9 {
let temp:Double = Double(countDigit[i])/Double(digitCount)
let ben = benford(digit: i+1)
print(String(format: "%d\t%.2f\t\t%.2f\t\t%.4f", i+1,ben*100,temp*100,ben-temp))
} |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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 Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
LT -> bSearch p (low, mid - 1)
GT -> bSearch p (mid + 1, high)
EQ -> Just mid
-- Application to an array:
bSearchArray
:: (Ix i, Integral i, Ord e)
=> Array i e -> e -> Maybe i
bSearchArray a x = bSearch (compare x . (a !)) (bounds a)
-- TEST -----------------------------------------------------------------------
axs
:: (Num i, Ix i)
=> Array i String
axs =
listArray
(0, 11)
[ "alpha"
, "beta"
, "delta"
, "epsilon"
, "eta"
, "gamma"
, "iota"
, "kappa"
, "lambda"
, "mu"
, "theta"
, "zeta"
]
main :: IO ()
main =
let e = "mu"
found = bSearchArray axs e
in putStrLn $
'\'' :
e ++
case found of
Nothing -> "' Not found"
Just x -> "' found at index " ++ show x |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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: Limit = 1
Case Else
i = NbLettersDiff(W(b))
If i >= Len(W(b)) \ 2 Then
Limit = 0
ElseIf i = 1 Then
Limit = Len(W(b))
Else
Limit = Len(W(b)) - i
End If
End Select
RePlay:
Do
S() = ShuffleIntegers(Len(W(b)))
myB = GoodShuffle(S, Limit)
Loop While Not myB
Anagram = ShuffleWord(CStr(W(b)), S)
Count = Nb(W(b), Anagram)
If Count > Limit Then GoTo RePlay
Debug.Print W(b) & " ==> " & Anagram & " (Score : " & Count & ")"
Next
End Sub
Function ShuffleIntegers(l As Long) As Long()
Dim i As Integer, ou As Integer, temp() As Long
Dim C As New Collection
ReDim temp(l - 1)
If l = 1 Then
temp(0) = 0
ElseIf l = 2 Then
temp(0) = 1: temp(1) = 0
Else
Randomize
Do
ou = Int(Rnd * l)
On Error Resume Next
C.Add CStr(ou), CStr(ou)
If Err <> 0 Then
On Error GoTo 0
Else
temp(ou) = i
i = i + 1
End If
Loop While C.Count <> l
End If
ShuffleIntegers = temp
End Function
Function GoodShuffle(t() As Long, Lim As Byte) As Boolean
Dim i&, C&
For i = LBound(t) To UBound(t)
If t(i) = i Then C = C + 1
Next i
GoodShuffle = (C <= Lim)
End Function
Function ShuffleWord(W$, S() As Long) As String
Dim i&, temp, strR$
temp = Split(StrConv(W, vbUnicode), Chr(0))
For i = 0 To UBound(S)
strR = strR & temp(S(i))
Next i
ShuffleWord = strR
End Function
Function Nb(W, A) As Integer
Dim i As Integer, l As Integer
For i = 1 To Len(W)
If Mid(W, i, 1) = Mid(A, i, 1) Then l = l + 1
Next i
Nb = l
End Function
Function NbLettersDiff(W) As Integer
Dim i&, C As New Collection
For i = 1 To Len(W)
On Error Resume Next
C.Add Mid(W, i, 1), Mid(W, i, 1)
Next i
NbLettersDiff = C.Count
End Function
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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)
}
}
static bmpPset(name, x, y, col) { ImageData[name].pset(x, y, col) }
static bmpPget(name, x, y) { ImageData[name].pget(x, y) }
static bmpLine(name, x0, y0, x1, y1, col) {
var dx = (x1 - x0).abs
var dy = (y1 - y0).abs
var sx = (x0 < x1) ? 1 : -1
var sy = (y0 < y1) ? 1 : -1
var err = ((dx > dy ? dx : - dy) / 2).floor
while (true) {
bmpPset(name, x0, y0, col)
if (x0 == x1 && y0 == y1) break
var e2 = err
if (e2 > -dx) {
err = err - dy
x0 = x0 + sx
}
if (e2 < dy) {
err = err + dx
y0 = y0 + sy
}
}
}
static init() {
Window.title = "Bresenham's line algorithm"
var size = 200
Window.resize(size, size)
Canvas.resize(size, size)
var name = "bresenham"
var bmp = bmpCreate(name, size, size)
bmpFill(name, Color.white)
bmpLine(name, 50, 100, 100, 190, Color.black)
bmpLine(name, 100, 190, 150, 100, Color.black)
bmpLine(name, 150, 100, 100, 10, Color.black)
bmpLine(name, 100, 10, 50, 100, Color.black)
bmp.draw(0, 0)
}
static update() {}
static draw(alpha) {}
} |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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", "Northeast by north"}]
compass_points(2) = [{ "Northeast", "Northeast by east", "East-northeast", "East by north"}]
compass_points(3) = [{ "East", "East by south", "East-southeast", "Southeast by east"}]
compass_points(4) = [{ "Southeast", "Southeast by south", "South-southeast", "South by east"}]
compass_points(5) = [{ "South", "South by west", "South-southwest", "Southwest by south"}]
compass_points(6) = [{ "Southwest", "Southwest by west", "West-southwest", "West by south"}]
compass_points(7) = [{ "West", "West by north", "West-northwest", "Northwest by west"}]
compass_points(8) = [{ "Northwest", "Northwest by north", "North-northwest", "North by west"}]
test_points(1) = [{ 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12}]
test_points(2) = [{ 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25}]
test_points(3) = [{ 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38}]
For i = 1 To 3
For Each t In test_points(i)
test_points_all.Add t
Next t
Next i
For i = 1 To 8
For Each c In compass_points(i)
compass_points_all.Add c
Next c
Next i
For i = 1 To test_points_all.Count
compass_point = (WorksheetFunction.Floor(test_points_all(i) * 32 / 360 + 0.5, 1) Mod 32) + 1
Debug.Print Format(compass_point, "@@"); " "; compass_points_all(compass_point);
Debug.Print String$(20 - Len(compass_points_all(compass_point)), " ");
Debug.Print test_points_all(i)
Next i
End Sub |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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 // Red
#6 = 0 // Green
#7 = 64 // Blue
Call("FILL_IMAGE")
// Draw one pixel in orange color
//
#1 = 100 // x
#2 = 50 // y
#5 = 255 #6 = 128 #7 = 0 // Orange color
Call("DRAW_PIXEL")
// Get the color of a pixel
//
#1 = 10
#2 = 3
Call("GET_COLOR")
Buf_Switch(#10) Buf_Quit(OK)
Return
/////////////////////////////////////////////////////////////////////
//
// Fill image with given color: #5 = Red, #6 = Green, #7 = Blue
//
:FILL_IMAGE:
BOF
Repeat (File_Size/3) {
IC(#5,OVERWRITE) IC(#6,OVERWRITE) IC(#7,OVERWRITE)
}
Return
/////////////////////////////////////////////////////////////////////
//
// Daw a pixel. #1 = x, #2 = y
//
:DRAW_PIXEL:
Goto_Pos((#1 + #2*#11)*3)
IC(#5,OVERWRITE) IC(#6,OVERWRITE) IC(#7,OVERWRITE)
Return
/////////////////////////////////////////////////////////////////////
//
// Get color of a pixel. #1 = x, #2 = y
// Return: #5 = Red, #6 = Green, #7 = Blue
//
:GET_COLOR:
Goto_Pos((#1 + #2*#11)*3)
#5 = Cur_Char
#6 = Cur_Char(1)
#7 = Cur_Char(2)
Return |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 | measured | theory"
puts "-------+----------+--------"
dict for {digit count} $accum {
puts [format "%6d | %7.2f%% | %5.2f%%" $digit \
[expr {$count * 100.0 / [llength $numbers]}] \
[expr {log(1+1./$digit)/log(10)*100.0}]]
}
} |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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] - arr[j]) * Frac(numerator: T(j), denominator: 1)
}
}
return arr[0]
}
for n in 0...60 {
let b = bernoulli(n: n) as Frac<BigInt>
guard b != 0 else {
continue
}
print("B(\(n)) = \(b)")
} |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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} {set q [expr {$p % [set p $q]}]}
lset A $j [list [expr {$x/$p}] [expr {$y/$p}]]
}
}
return [lindex $A 0]
}
set len 0
for {set n 0} {$n <= 60} {incr n} {
set b [bernoulli $n]
if {[lindex $b 0]} {
lappend result $n {*}$b
set len [expr {max($len, [string length [lindex $b 0]])}]
}
}
foreach {n num denom} $result {
puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom]
} |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
IF( low > high) THEN
binarySearch = 0
RETURN
ELSE
mid = INT( (low + high) / 2 )
IF( A(mid) > value) THEN
high = mid - 1
ELSEIF( A(mid) < value ) THEN
low = mid + 1
ELSE
binarySearch = mid
RETURN
ENDIF
ENDIF
ENDDO
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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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 = 0 To UBound(arr):Do
If arr(i) <> Mid(s, i + 1, 1) Then Exit Do
For j = 0 To UBound(arr)
If arr(i) <> arr(j) And arr(i) <> Mid(s, j + 1, 1) And arr(j) <> Mid(s, i + 1, 1) Then
tmp = arr(i)
arr(i) = arr(j)
arr(j) = tmp
End If
Next
Loop While False:Next
shuffled_word = Join(arr,"")
'This section is the scorer
score = 0
For k = 1 To Len(s)
If Mid(s,k,1) = Mid(shuffled_word,k,1) Then
score = score + 1
End If
Next
bestshuffle = shuffled_word & ",(" & score & ")"
End Function
Function shuffler(array)
Set rand = CreateObject("System.Random")
For i = UBound(array) to 0 Step -1
r = rand.next_2(0, i + 1)
tmp = array(i)
array(i) = array(r)
array(r) = tmp
Next
shuffler = array
End Function
'Testing the function
word_list = Array("abracadabra","seesaw","elk","grrrrrr","up","a")
For Each word In word_list
WScript.StdOut.WriteLine word & "," & bestshuffle(word)
Next |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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(3); \restore normal text mode
] |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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
heading -= 5.62
End Select
Console.WriteLine("{0,2}: {1,-18} {2,6:F2}°", (i Mod 32) + 1, InitialUpper(GetPoint(heading)), heading)
Next
End Sub
Private Sub BuildPoints()
Dim cardinal As String() = New String() {"north", "east", "south", "west"}
Dim pointDesc As String() = New String() {"1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1"}
Dim str1, str2, strC As String
For i As Integer = 0 To 3
str1 = cardinal(i)
str2 = cardinal((i + 1) Mod 4)
strC = IIf(str1 = "north" Or str1 = "south", str1 & str2, str2 & str1)
For j As Integer = 0 To 7
_points(i * 8 + j) = pointDesc(j).Replace("1", str1).Replace("2", str2).Replace("C", strC)
Next
Next
End Sub
Private Function InitialUpper(ByVal s As String) As String
Return s.Substring(0, 1).ToUpper() & s.Substring(1)
End Function
Private Function GetPoint(ByVal Degrees As Double) As String
Dim testD As Double = (Degrees / 11.25) + 0.5
Return _points(CInt(Math.Floor(testD Mod 32)))
End Function
End Module
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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"
DetailPrint "There are no Arithmetic shifts in NSIS"
IntOp $2 $0 >> $1
DetailPrint "Right Shift: $0 >> 1 = $2"
IntOp $2 $0 << $1
DetailPrint "Left Shift: $0 << $1 = $2"
DetailPrint "There are no Rotates in NSIS"
Pop $2
Pop $1
Pop $0
FunctionEnd |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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)> _
Public R As Byte
Public Sub New(ByVal r As Byte, ByVal g As Byte, ByVal b As Byte)
Me.R = r
Me.G = g
Me.B = b
End Sub
End Structure |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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
Total= Application.Sum(BenResult)
biggest= Len(CStr(BenResult(1)))
txt = "# | Values | Real | Expected " & vbCrLf
For i = 1 To 9
If BenResult(i) > 0 Then
txt = txt & "#" & i & " | " & vbTab
txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab
txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab
txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf
End If
Next
MsgBox txt, vbOKOnly, "Finish"
End Sub
}
|
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 leading digit of the first 1000 Fibonacci numbers
a[1,1] = "1"
a[1,2] = 1
a[2,1] = "1"
a[2,2] = 1
FOR i = 3 TO n
a[i,2] = a[i-2,2] + a[i-1,2]
a[i,1] = LEFT(TRANSFORM(a[i,2]), 1)
ENDFOR
APPEND FROM ARRAY a FIELDS dig
CREATE CURSOR results (digit I, count I, prob B(6), expected B(6))
INSERT INTO results ;
SELECT dig, COUNT(1), COUNT(1)/n, Pr(VAL(dig)) FROM fibo GROUP BY dig ORDER BY dig
n1 = RECCOUNT()
*!* Correlation coefficient
SELECT (n1*SUM(prob*expected) - SUM(prob)*SUM(expected))/;
(SQRT(n1*SUM(prob*prob) - SUM(prob)*SUM(prob))*SQRT(n1*SUM(expected*expected) - SUM(expected)*SUM(expected))) ;
FROM results INTO ARRAY res
rho = CAST(res[1] As B(6))
SET SAFETY OFF
COPY TO benford.txt TYPE CSV
c = FILETOSTR("benford.txt")
*!* Replace commas with tabs
c = STRTRAN(c, COMMA, CTAB) + CRLF + "Correlation Coefficient: " + TRANSFORM(rho)
STRTOFILE(c, "benford.txt", 0)
SET SAFETY ON
FUNCTION Pr(d As Integer) As Double
RETURN LOG10(1 + 1/d)
ENDFUNC
|
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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 = y
y = y2
Loop Until y = 0
Return x
End Function 'gcd_BigInt
Sub bernoul_BigInt(n As Integer, ByRef bnum As BigInteger, ByRef bden As BigInteger)
Dim j, m As Integer
Dim f As BigInteger
Dim anum(), aden() As BigInteger
ReDim anum(n + 1), aden(n + 1)
For m = 0 To n
anum(m + 1) = 1
aden(m + 1) = m + 1
For j = m To 1 Step -1
anum(j) = j * (aden(j + 1) * anum(j) - aden(j) * anum(j + 1))
aden(j) = aden(j) * aden(j + 1)
f = gcd_BigInt(BigInteger.Abs(anum(j)), BigInteger.Abs(aden(j)))
If f <> 1 Then
anum(j) = anum(j) / f
aden(j) = aden(j) / f
End If
Next
Next
bnum = anum(1) : bden = aden(1)
End Sub 'bernoul_BigInt
Sub bernoulli_BigInt()
Dim i As Integer
Dim bnum, bden As BigInteger
bnum = 0 : bden = 0
For i = 0 To 60
bernoul_BigInt(i, bnum, bden)
If bnum <> 0 Then
Console.WriteLine("B(" & i & ")=" & bnum.ToString("D") & "/" & bden.ToString("D"))
End If
Next i
End Sub 'bernoulli_BigInt
End Module 'Bernoulli_numbers |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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
}
}
static count_(ca, s1) {
var count = 0
for (i in 0...ca.count) if (s1[i] == ca[i]) count = count + 1
return count
}
static invoke(s1) {
var s2 = s1.toList
shuffle_(s2)
for (i in 0...s2.count) {
if (s2[i] == s1[i]) {
for (j in 0...s2.count) {
if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {
var tmp = s2[i]
s2[i] = s2[j]
s2[j] = tmp
break
}
}
}
}
return s1 + ", " + s2.join() + ", (" + "%(count_(s2, s1))" + ")"
}
}
var words = ["tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]
words.each { |w| System.print(BestShuffle.invoke(w)) } |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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 cpx = Fn.new { |h|
var x = (h/11.25+0.5).floor % 32
if (x < 0) x = x + 32
return x
}
// printable compass points
var compassPoint = [
"North",
"North by east",
"North-northeast",
"Northeast by north",
"Northeast",
"Northeast by east",
"East-northeast",
"East by north",
"East",
"East by south",
"East-southeast",
"Southeast by east",
"Southeast",
"Southeast by south",
"South-southeast",
"South by east",
"South",
"South by west",
"South-southwest",
"Southwest by south",
"Southwest",
"Southwest by west",
"West-southwest",
"West by south",
"West",
"West by north",
"West-northwest",
"Northwest by west",
"Northwest",
"Northwest by north",
"North-northwest",
"North by west"
]
// function required by task
var degreesToCompassPoint = Fn.new { |h| compassPoint[cpx.call(h)] }
var r = [
0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,
84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,
185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0,
286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38
]
System.print("Index Compass point Degree")
var i = 0
for (h in r) {
var index = i%32 + 1 // printable index computed per pseudocode
var d = degreesToCompassPoint.call(h)
System.print("%(Fmt.d(4, index)) %(Fmt.s(-19, d)) %(Fmt.f(7, h, 2))°")
i = i + 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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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.Int(SYSTEM.VAL(LONGINT,x / y),0);Out.Ln;
Out.String("a and ~b:> ");Out.Int(SYSTEM.VAL(LONGINT,x - y),0);Out.Ln;
Out.String("~a :> ");Out.Int(SYSTEM.VAL(LONGINT,-x),0);Out.Ln;
Out.String("a left shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.LSH(x,b)),0);Out.Ln;
Out.String("a right shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.LSH(x,-b)),0);Out.Ln;
Out.String("a left rotate b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.ROT(x,b)),0);Out.Ln;
Out.String("a right rotate b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.ROT(x,-b)),0);Out.Ln;
Out.String("a arithmetic left shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,ASH(a,b)),0);Out.Ln;
Out.String("a arithmetic right shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,ASH(a,-b)),0);Out.Ln
END Do;
BEGIN
Do(10,2);
END Bitwise.
|
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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)
}
}
static bmpPset(name, x, y, col) { ImageData[name].pset(x, y, col) }
static bmpPget(name, x, y) { ImageData[name].pget(x, y) }
static init() {
Window.title = "Bitmap"
var size = 600
Window.resize(size, size)
Canvas.resize(size, size)
var bmp = bmpCreate("rcbmp", size/2, size/2)
bmpFill("rcbmp", Color.yellow)
bmpPset("rcbmp", size/4, size/4, Color.blue) // 'blue' is #29ADFF on the default palette
var col = bmpPget("rcbmp", size/4, size/4)
System.print(col.toString) // check it's blue - alpha component (FF) will also be shown
bmp.draw(150, 150)
}
static update() {}
static draw(alpha) {}
} |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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"[0]-'1'[0]]++
}
println(title)
println("Digit Observed Predicted")
for i, n in f {
println(" ${i+1} ${f64(n)/f64(c.len):9.3f} ${math.log10(1+1/f64(i+1)):8.3f}")
}
} |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 }
var show = Fn.new { |c, title|
var f = List.filled(9, 0)
for (v in c) {
var t = "%(v)".bytes[0] - 49
f[t] = f[t] + 1
}
System.print(title)
System.print("Digit Observed Predicted")
for (i in 0...f.count) {
var n = f[i]
var obs = Fmt.f(9, n/c.count, 3)
var t = log10.call(1/(i + 1) + 1)
var pred = Fmt.f(8, t, 3)
System.print(" %(i+1) %(obs) %(pred)")
}
}
show.call(fib1000.call(), "First 1000 Fibonacci numbers:") |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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.new(j, 1)
j = j - 1
}
}
return (n != 1) ? a[0] : -a[0] // 'first' Bernoulli number
}
for (n in 0..60) {
var b = bernoulli.call(n)
if (b != BigRat.zero) Fmt.print("B($2d) = $44i / $i", n, b.num, b.den)
} |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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 in a word
char W0;
char W(20), SW(20);
int L, I, S, SS, C, T;
[L:= StrLen(W0); \word length
for I:= 0 to L do W(I):= W0(I); \get working copy of word (including 0)
SS:= 20; \initialize best (saved) score
for C:= 1 to 1_000_000 do \overkill? XPL0 is fast
[I:= Ran(L); \shuffle: swap random char with end char
T:= W(I); W(I):= W(L-1); W(L-1):= T;
S:= 0; \compute score
for I:= 0 to L-1 do
if W(I) = W0(I) then S:= S+1;
if S < SS then
[SS:= S; \save best score and best shuffle
for I:= 0 to L do SW(I):= W(I);
];
];
Text(0, W0); Text(0, ", "); \show original and shuffled words, score
Text(0, SW); Text(0, ", ("); IntOut(0, SS); ChOut(0, ^)); CrLf(0);
];
int S, I;
[S:= ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];
for I:= 0 to 5 do Shuffle(S(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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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.zipWith('==,str).sum(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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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
ind = mod(i,32)+1
print ind,"\t",compasspoint$( heading),"\t",heading
next i
end
sub compasspoint$(h)
x = h / 11.25 + 1.5
if (x >= 33.0) x = x - 32.0
return point$(int(x))
end sub
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 ", "South-southwest "
60 data "Southwest by south", "Southwest ", "Southwest by west ", "West-southwest "
70 data "West by south ", "West ", "West by north ", "West-northwest "
80 data "Northwest by west ", "Northwest ", "Northwest by north", "North-northwest "
90 data "North 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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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->GetInstance()->Print("a xor b: ")->PrintLine(a xor b);
# shift left & right are supported by the compiler and VM but not
# exposed to end-users; those instructions are used for optimizations
}
}
} |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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, y As Integer) As Color
Return p.RGBSurface.Pixel(x, y)
End Function
Sub SetPixelColor(p As Picture, x As Integer, y As Integer, pColor As Color)
p.RGBSurface.Pixel(x, y) = pColor
End Sub
|
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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" (first digit)
f[v.toString()[0].toInt()-1].inc(); }
println(title);
println("Digit Observed Predicted");
foreach i,n in ([1..].zip(f)){ // -->(1,Ref)...(9,Ref)
println(" %d %9.3f %8.3f".fmt(i,n.value.toFloat()/data.len(),
(1.0+1.0/i).log10()))
}
} |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #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 REM Fibonacci
1010 LET fiboI=0: LET b=1
1020 FOR j=1 TO i
1030 LET temp=fiboI+b
1040 LET fiboI=b
1050 LET b=temp
1060 NEXT j
1070 RETURN
|
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of Standards and Technology convention).
The nth Bernoulli number is expressed as Bn.
Task
show the Bernoulli numbers B0 through B60.
suppress the output of values which are equal to zero. (Other than B1 , all odd Bernoulli numbers have a value of zero.)
express the Bernoulli numbers as fractions (most are improper fractions).
the fractions should be reduced.
index each number in some way so that it can be discerned which Bernoulli number is being displayed.
align the solidi (/) if used (extra credit).
An algorithm
The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:
for m from 0 by 1 to n do
A[m] ← 1/(m+1)
for j from m by -1 to 1 do
A[j-1] ← j×(A[j-1] - A[j])
return A[0] (which is Bn)
See also
Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences.
Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
Luschny's The Bernoulli Manifesto for a discussion on B1 = -½ versus +½.
| #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){
if(Rational.isChildOf(n)) self(a*n.b + b*n.a, b*n.b); // Rat + Rat
else self(b*n + a, b); // Rat + Int
}
fcn __opSub(n){ self(a*n.b - b*n.a, b*n.b) } // Rat - Rat
fcn __opMul(n){
if(Rational.isChildOf(n)) self(a*n.a, b*n.b); // Rat * Rat
else self(a*n, b); // Rat * Int
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
} |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did not change.
Example
tree, eetr, (0)
Test cases
abracadabra
seesaw
elk
grrrrrr
up
a
Related tasks
Anagrams/Deranged anagrams
Permutations/Derangements
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #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 LET t$=b$(i): LET b$(i)=b$(j): LET b$(j)=t$
1110 NEXT j
1120 NEXT i
1130 RETURN
2000 DATA "abracadabra","seesaw","elk","grrrrrr","up","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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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.25*i;
switch(i%3){ // or heading+=5.62*((i+1).divr(3)[1]-1);
case(1){ heading+=5.62 }
case(2){ heading-=5.62 }
}
box:=compassBox(heading);
println("%6.2f\UB0; : %2d\t%s".fmt(heading,box,A[box]));
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 *)
Printf.printf "a lsr b: %d\n" (a lsr b); (* logical 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 pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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)
Point(X, Y, Color);
Move(60, 60); HexOut(6, ReadPix(0,0)); \show color of pixel at 0,0
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore display to normal text mode
] |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given pixel with a color,
one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
These functions are used as a base for the articles in the category raster graphics operations,
and a basic output function to check the results
is available in the article write ppm file.
| #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)));
}
fcn __sGet(x,y) { data.toBigEndian(3*y*w + 3*x,3); } //ppm[x,y]
fcn __sSet(rbg,x,y){ data[3*y*w + 3*x,3]=rbg.toBigEndian(3); } //ppm[x,y]=rgb
fcn write(out){ // write bottom to top to move (0,0) from bottom left to bottom left
out.write("P6\n#rosettacode PPM\n%d %d\n255\n".fmt(w,h));
[h-1..0, -1].pump(out,'wrap(h){ data.seek(3*h*w); data.read(3*w) });
out.close();
}
} |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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;
} else if (nums[guess] < check) {
lo = guess + 1;
} else {
return guess;
}
}
return -1;
}
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + 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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #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","South-southwest"
60 DATA "Southwest by south","Southwest","Southwest by west","West-southwest"
70 DATA "West by south","West","West by north","West-northwest"
80 DATA "Northwest by west","Northwest","Northwest by north","North-northwest"
90 DATA "North by west"
100 DIM p$(32,18)
110 FOR i=1 TO 32
120 READ p$(i)
130 NEXT i
140 FOR i=0 TO 32
150 LET h=i*11.25
160 LET r=FN m(i,3)
170 IF r=1 THEN LET h=h+5.62: GO TO 190
180 IF r=2 THEN LET h=h-5.62
190 LET ind=FN m(i,32)+1
200 PRINT ind;TAB 4;
210 LET x=h/11.25+1.5
220 IF x>=33 THEN LET x=x-32
230 PRINT p$(INT x);TAB 25;h
240 NEXT i
250 STOP
260 DEF FN m(i,n)=((i/n)-INT (i/n))*n : REM modulus function
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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))));
printf("simul not %s = %s", dec2bin(a), dec2bin(bitxor(a, 0xffffffff)));
endfunction
bitops(0x1e, 0x3); |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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) then binarySearch($mid+1; high)
else $mid
end
end;
binarySearch(0; length-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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 used for expanding the shorter string.
* 10.11.2012 Walter Pachl taken over from REXX and extended for ooRexx
**********************************************************************/
a=21
b=347
Say ' a :'c2b(a) ' 'c2x(a)
Say ' b :'c2b(b) c2x(b)
Say 'bitand(a,b) :'c2b(bitand(a,b)) c2x(bitand(a,b))
Say 'bitor(a,b) :'c2b(bitor(a,b)) c2x(bitor(a,b))
Say 'bitxor(a,b) :'c2b(bitxor(a,b)) c2x(bitxor(a,b))
p='11111111'B
Say 'ooRexx only:'
Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p))
Exit
c2b: return x2b(c2x(arg(1))) |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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[mid] > needle) {
high = mid - 1;
} else if (haystack[mid] < needle) {
low = mid + 1;
} else {
return mid;
}
}
return null;
}
/* recursive */
function binarySearchRecursive(haystack, needle, low, high) {
if (high < low) { return null; }
var mid = Math.floor((low + high) / 2);
if (haystack[mid] > needle) {
return binarySearchRecursive(haystack, needle, low, mid - 1);
}
if (haystack[mid] < needle) {
return binarySearchRecursive(haystack, needle, mid + 1, high);
}
return mid;
}
/* Testing and timing */
if (Interp.conf('unitTest') > 0) {
var arr = [];
for (var i = -5000; i <= 5000; i++) { arr.push(i); }
assert(arr.length == 10001);
assert(binarySearchIterative(arr, 0) == 5000);
assert(binarySearchRecursive(arr, 0, 0, arr.length - 1) == 5000);
assert(binarySearchIterative(arr, 5000) == 10000);
assert(binarySearchRecursive(arr, -5000, 0, arr.length - 1) == 0);
assert(binarySearchIterative(arr, -5001) == null);
puts('--Time 100 passes--');
puts('Iterative:', Util.times(function() { binarySearchIterative(arr, 42); }, 100), 'µs');
puts('Recursive:', Util.times(function() { binarySearchRecursive(arr, 42, 0, arr.length - 1); }, 100), 'µ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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
end |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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
}
fun <T : Comparable<T>> Array<T>.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int {
if (hi < lo) return -1
val guess = (hi + lo) / 2
return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1)
else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi)
else guess
}
fun main(args: Array<String>) {
val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)
var target = 6
var r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 6
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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 operations to return signed ints
print "after use integer:\n";
print 'a << b: ', $a << $b, "\n"; # left shift
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
} |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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} :i1 }
else :v is at array[:m] }}}}} }
{lambda {:a :v}
{BS.r :a :v 0 {- {array.length :a} 1}} }}
-> BS
{def A {array 12 14 16 18 20 22 25 27 30}}
-> A = [12,14,16,18,20,22,25,27,30]
{BS {A} -1} -> -1 is not found
{BS {A} 24} -> 24 is not found
{BS {A} 25} -> 25 is at array[6]
{BS {A} 123} -> 123 is not found
{def B {array {serie 1 100000 2}}}
-> B = [1,3,5,... 99997,99999]
{BS {B} 100} -> 100 is not found
{BS {B} 12345} -> 12345 is at array[6172]
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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 conversion and binary masking example
hex 0FF binary . cr
decimal 679 binary . cr
binary 11111111111 00000110000 and . cr
decimal
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #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
@@:
cmp dl,SAR
jne @f
sar eax,cl
jmp :storeres
@@:
cmp dl,SHR
jne @f
shr eax,cl
jmp :storeres
@@:
cmp dl,ROL
jne @f
rol eax,cl
jmp :storeres
@@:
cmp dl,ROR
jne @f
ror eax,cl
jmp :storeres
@@:
int3
::storeres
lea edi,[res]
call :%pStoreMint
[64]
mov rax,[a]
mov rcx,[b]
mov edx,[op]
cmp dl,SHL
jne @f
shl rax,cl
jmp :storeres
@@:
cmp dl,SAR
jne @f
sar rax,cl
jmp :storeres
@@:
cmp dl,SHR
jne @f
shr rax,cl
jmp :storeres
@@:
cmp dl,ROL
jne @f
rol rax,cl
jmp :storeres
@@:
cmp dl,ROR
jne @f
ror eax,cl
jmp :storeres
@@:
int3
::storeres
lea rdi,[res]
call :%pStoreMint
}
return res
end function
procedure bitwise(atom a, atom b)
printf(1,"and_bits(%b,%b) = %032b\n",{a,b,and_bits(a,b)})
printf(1," or_bits(%b,%b) = %032b\n",{a,b, or_bits(a,b)})
printf(1,"xor_bits(%b,%b) = %032b\n",{a,b,xor_bits(a,b)})
printf(1,"not_bits(%b) = %032b\n",{a,not_bits(a)})
printf(1," shl(%b,%b) = %032b\n",{a,b,bitop(a,b,SHL)})
printf(1," sar(%b,%b) = %032b\n",{a,b,bitop(a,b,SAR)})
printf(1," shr(%b,%b) = %032b\n",{a,b,bitop(a,b,SHR)})
printf(1," rol(%b,%b) = %032b\n",{a,b,bitop(a,b,ROL)})
printf(1," ror(%b,%b) = %032b\n",{a,b,bitop(a,b,ROR)})
end procedure
bitwise(0x800000FE,7)
|
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #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 > theArray(middle) then binarySearch = binarySearch(val, middle+1, hi)
if val = theArray(middle) then binarySearch = middle
END IF
END FUNCTION
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #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
! tobin 9000
!10001100101000
program bits
implicit none
integer, dimension(3) :: a
integer :: i
data a/5,50,9000/
do i = 1, 3
call s(a(i))
enddo
contains
subroutine s(a)
integer, intent(in) :: a
integer :: i
if (a .eq. 0) then
write(6,'(a)')'0'
return
endif
do i = 31, 0, -1
if (btest(a, i)) exit
enddo
do while (0 .lt. i)
if (btest(a, i)) then
write(6,'(a)',advance='no')'1'
else
write(6,'(a)',advance='no')'0'
endif
i = i-1
enddo
if (btest(a, i)) then
write(6,'(a)')'1'
else
write(6,'(a)')'0'
endif
end subroutine s
end program bits
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.