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.
| #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
' FB doesn't have built-in logical shift right or rotation operators
' but, as they're not difficult to implement, I've done so below.
Function lsr(x As Const Integer, y As Const Integer) As Integer
Dim As UInteger z = x
Return z Shr y
End Function
Function rol(x As Const Integer, y As Const UInteger) As Integer
Dim z As Integer = x
Dim high As Integer
For i As Integer = 1 To y
high = Bit(z, 63)
For j As Integer = 62 To 0 Step -1
If Bit(z, j) Then
z = BitSet(z, j + 1)
Else
z = BitReset (z, j + 1)
End If
Next j
If high Then
z = BitSet(z, 0)
Else
z = BitReset(z, 0)
End If
Next i
Return z
End Function
Function ror(x As Const Integer, y As Const UInteger) As Integer
Dim z As Integer = x
Dim low As Integer
For i As Integer = 1 To y
low = Bit(z, 0)
For j As Integer = 1 To 63
If Bit(z, j) Then
z = BitSet(z, j - 1)
Else
z = BitReset (z, j - 1)
End If
Next j
If low Then
z = BitSet(z, 63)
Else
z = BitReset(z, 63)
End If
Next i
Return z
End Function
Sub bitwise(x As Integer, y As Integer)
Print "x = "; x
Print "y = "; y
Print "x AND y = "; x And y
Print "x OR y = "; x Or y
Print "x XOR y = "; x XOr y
Print "NOT x = "; Not x
Print "x SHL y = "; x Shl y
Print "x SHR y = "; x Shr y
Print "x LSR y = "; lsr(x, y)
Print "x ROL y = "; rol(x, y)
Print "x ROR y = "; ror(x, y)
End Sub
bitwise -15, 3
Print
Print "Press any key to quit"
Sleep |
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.
| #J | J | makeRGB=: 0&$: : (($,)~ ,&3)
fillRGB=: makeRGB }:@$
setPixels=: (1&{::@[)`(<"1@(0&{::@[))`]}
getPixels=: <"1@[ { ] |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Maple | Maple | bell1:=proc(n)
option remember;
add(binomial(n-1,k)*bell1(k),k=0..n-1)
end:
bell1(0):=1:
bell1(50);
# 185724268771078270438257767181908917499221852770
combinat[bell](50);
# 185724268771078270438257767181908917499221852770
bell1~([$0..20]);
# [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570,
# 4213597, 27644437, 190899322, 1382958545, 10480142147,
# 82864869804, 682076806159, 5832742205057, 51724158235372] |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
BellTriangle[n_Integer?Positive] := NestList[Accumulate[# /. {a___, b_} :> {b, a, b}] &, {1}, n - 1];
BellNumber[n_Integer] := BellTriangle[n][[n, 1]];
|
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the 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 .
| #Groovy | Groovy | def tallyFirstDigits = { size, generator ->
def population = (0..<size).collect { generator(it) }
def firstDigits = [0]*10
population.each { number ->
firstDigits[(number as String)[0] as int] ++
}
firstDigits
} |
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 .
| #Haskell | Haskell | import qualified Data.Map as M
import Data.Char (digitToInt)
fstdigit :: Integer -> Int
fstdigit = digitToInt . head . show
n = 1000 :: Int
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
fibdata = map fstdigit $ take n fibs
freqs = M.fromListWith (+) $ zip fibdata (repeat 1)
tab :: [(Int, Double, Double)]
tab =
[ ( d
, fromIntegral (M.findWithDefault 0 d freqs) / fromIntegral n
, logBase 10.0 $ 1 + 1 / fromIntegral d)
| d <- [1 .. 9] ]
main = print tab |
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 +½.
| #Frink | Frink | BernoulliNumber[n] :=
{
a = new array
for m = 0 to n
{
a@m = 1/(m+1)
for j = m to 1 step -1
a@(j-1) = j * (a@(j-1) - a@j)
}
return a@0
}
result = new array
for n=0 to 60
{
b = BernoulliNumber[n]
if b != 0
{
[num,den] = numeratorDenominator[b]
result.push[[n, num, "/", den]]
}
}
println[formatTable[result, "right"]] |
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.
| #Batch_File | Batch File |
@echo off & setlocal enabledelayedexpansion
:: Binary Chop Algorithm - Michael Sanders 2017
::
:: example output...
::
:: binary chop algorithm vs. standard for loop
::
:: number to find 941
:: for loop required 941 iterations
:: binchop required 10 iterations
:setup
set x=1
set y=999
set /a z=(%random% * (%y% - 1) / 32768 + 1)
:pseudoarray
for /l %%q in (%x%,1,%y%) do set /a array[%%q]=%%q
:std4loop
for /l %%q in (%x%,1,%y%) do (
if !array[%%q]!==%z% (set f=%%q& goto :binchop)
)
:binchop
if !x! leq !y! (
set /a i+=1
set /a "p=(!x!+!y!)/2"
call set /a t=%%array[!p!]%%
if !t! equ !z! (set b=!i!& goto :done)
if !t! lss !z! (set /a x=!p!+1) else (set /a y=!p!-1)
goto :binchop
)
:done
cls
echo binary chop algorithm vs. standard for loop...
echo.
echo . number to find !z!
echo . for loop required !f! iterations
echo . binchop required !b! iterations
endlocal & exit /b 0
|
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
| #FutureBasic | FutureBasic |
include "Tlbx GameplayKit.incl"
include "NSLog.incl"
local fn ShuffleString( string as CFStringRef ) as CFStringRef
NSInteger i
CFMutableArrayRef mutArr = fn MutableArrayWithCapacity( 0 )
for i = 0 to fn StringLength( string ) - 1
MutableArrayAddObject( mutArr, fn StringSubstringWithRange( string, fn CFRangeMake( i, 1 ) ) )
next
CFArrayRef shuffledArr = fn GKRandomSourceArrayByShufflingObjectsInArray( fn GKRandomSourceInit, mutArr )
end fn = fn ArrayComponentsJoinedByString( shuffledArr, @"" )
local fn StringDifferences( string1 as CFStringRef, string2 as CFStringRef ) as NSInteger
NSInteger i, unchangedPosition = 0
if fn StringLength( string1 ) != fn StringLength( string2 ) then NSLog( @"Strings must be of equal length." ) : exit fn
for i = 0 to fn StringLength( string1 ) -1
CFStringRef tempStr1 = fn StringSubstringWithRange( string1, fn CFRangeMake( i, 1 ) )
CFStringRef tempStr2 = fn StringSubstringWithRange( string2, fn CFRangeMake( i, 1 ) )
if fn StringIsEqual( tempStr1, tempStr2 ) == YES then unchangedPosition++
next
end fn = unchangedPosition
NSInteger i, j, count
CFArrayRef stringArr
CFStringRef originalStr, shuffledStr
stringArr = @[@"abracadabra", @"seesaw", @"elk", @"grrrrrr", @"up", @"a"]
count = fn ArrayCount( stringArr )
for i = 0 to 3
for j = 0 to count - 1
originalStr = stringArr[j]
shuffledStr = fn ShuffleString( stringArr[j] )
NSLog( @"%@, %@, (%ld)", originalStr, shuffledStr, fn StringDifferences( originalStr, shuffledStr ) )
next
NSLog( @"\n" )
next
HandleEvents
|
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
| #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"}
func main() {
rand.Seed(time.Now().UnixNano())
for _, s := range ts {
// create shuffled byte array of original string
t := make([]byte, len(s))
for i, r := range rand.Perm(len(s)) {
t[i] = s[r]
}
// algorithm of Icon solution
for i := range t {
for j := range t {
if i != j && t[i] != s[j] && t[j] != s[i] {
t[i], t[j] = t[j], t[i]
break
}
}
}
// count unchanged and output
var count int
for i, ic := range t {
if ic == s[i] {
count++
}
}
fmt.Printf("%s -> %s (%d)\n", s, string(t), count)
}
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Lingo | Lingo | -- String creation and destruction
foo = "Hello world!" -- created by assignment; destruction via garbage collection
-- Strings are binary safe
put numtochar(0) into char 6 of foo
put chartonum(foo.char[6])
-- 0
put str.char[7..foo.length]
-- "world!"
-- String cloning and copying
bar = foo -- copies foo contents to bar
-- String comparison
put (foo=bar) -- TRUE
put (foo<>bar) -- FALSE
-- Check if a string is empty
put (foo=EMPTY)
put (foo="")
put (foo.length=0)
-- Append a byte to a string
put "X" after foo
put chartonum(88) after foo
-- Extract a substring from a string
put foo.char[3..5]
-- Replace every occurrence of a byte (or a string) in a string with another string
----------------------------------------
-- Replace in string
-- @param {string} stringToFind
-- @param {string} stringToInsert
-- @param {string} input
-- @return {string}
----------------------------------------
on replaceAll (stringToFind, stringToInsert, input)
output = ""
findLen = stringToFind.length - 1
repeat while TRUE
currOffset = offset(stringToFind, input)
if currOffset=0 then exit repeat
put input.char[1..currOffset] after output
delete the last char of output
put stringToInsert after output
delete input.char[1..(currOffset + findLen)]
end repeat
put input after output
return output
end
put replaceAll("o", "X", foo)
-- Join strings (4x the same result)
foo = "Hello " & "world!"
foo = "Hello" & numtochar(32) & "world!"
foo = "Hello" & SPACE & "world!"
foo = "Hello" && "world!" |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Lua | Lua | foo = 'foo' -- Ducktyping foo to be string 'foo'
bar = 'bar'
assert (foo == "foo") -- Comparing string var to string literal
assert (foo ~= bar)
str = foo -- Copy foo contents to str
if #str == 0 then -- # operator returns string length
print 'str is empty'
end
str=str..string.char(50)-- Char concatenated with .. operator
substr = str:sub(1,3) -- Extract substring from index 1 to 3, inclusively
str = "string string string string"
-- This function will replace all occurances of 'replaced' in a string with 'replacement'
function replaceAll(str,replaced,replacement)
local function sub (a,b)
if b > a then
return str:sub(a,b)
end
return nil
end
a,b = str:find(replaced)
while a do
str = str:sub(1,a-1) .. replacement .. str:sub(b+1,#str)
a,b = str:find(replaced)
end
return str
end
str = replaceAll (str, 'ing', 'ong')
print (str)
str = foo .. bar -- Strings concatenate with .. operator |
http://rosettacode.org/wiki/Bin_given_limits | Bin given limits | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
Task
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will print the limit of each bin
together with the count of items that fell in the range.
Assume the numbers to bin are too large to practically sort.
Task examples
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| #Wren | Wren | import "/sort" for Find
import "/fmt" for Fmt
var getBins = Fn.new { |limits, data|
var n = limits.count
var bins = List.filled(n+1, 0)
for (d in data) {
var res = Find.all(limits, d) // uses binary search
var found = res[0]
var index = res[2].from
if (found) index = index + 1
bins[index] = bins[index] + 1
}
return bins
}
var printBins = Fn.new { |limits, bins|
for (i in 0..limits.count) {
if (i == 0) {
Fmt.print(" < $3d = $2d", limits[0], bins[0])
} else if (i == limits.count) {
Fmt.print(">= $3d = $2d", limits[i-1], bins[i])
} else {
Fmt.print(">= $3d and < $3d = $2d", limits[i-1], limits[i], bins[i])
}
}
System.print()
}
var limitsList = [
[23, 37, 43, 53, 67, 83],
[14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
]
var dataList = [
[
95,21,94,12,99,4,70,75,83,93,52,80,57, 5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96, 6,98,40,79,97,45,64,60,29,49,36,43,55
],
[
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749
]
]
for (i in 0...limitsList.count) {
System.print("Example %(i+1):\n")
var bins = getBins.call(limitsList[i], dataList[i])
printBins.call(limitsList[i], bins)
} |
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.
| #AWK | AWK | BEGIN {
print tobinary(5)
print tobinary(50)
print tobinary(9000)
}
function tobinary(num) {
outstr = ""
l = num
while ( l ) {
if ( l%2 == 0 ) {
outstr = "0" outstr
} else {
outstr = "1" outstr
}
l = int(l/2)
}
# Make sure we output a zero for a value of zero
if ( outstr == "" ) {
outstr = "0"
}
return outstr
} |
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.
| #Korn_Shell | Korn Shell | function line {
x0=$1; y0=$2 x1=$3; y1=$4
if (( x0 > x1 ))
then
((dx = x0 - x1)); ((sx = -1))
else
((dx = x1 - x0)); ((sx = 1))
fi
if (( y0 > y1 ))
then
((dy = y0 - y1)); ((sy = -1))
else
((dy = y1 - y0)); ((sy = 1))
fi
if (( dx > dy ))
then
((err = dx))
else
((err = -dy))
fi
((err /= 2)); ((e2 = 0))
while /bin/true
do
echo $x0 $y0
(( x0 == x1 && y0 == y1 )) && return
((e2 = err))
(( e2 > -dx)) && { ((err -= dy )); (( x0 += sx )) }
(( e2 < dy)) && { ((err += dx )); (( y0 += sy )) }
done
} |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #PL.2FM | PL/M | IF 0 THEN /* THIS WON'T RUN */;
IF 1 THEN /* THIS WILL */;
IF 2 THEN /* THIS WON'T */;
IF 3 THEN /* THIS WILL */; |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Plain_English | Plain English | true
false |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Pony | Pony | true
false |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass 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)..
| #Nim | Nim | import math, sequtils, strformat, strutils
const
headingNames: array[1..32, string] = [
"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"]
maxNameLength = headingNames.mapIt(it.len).max
degreesPerHeading = 360 / 32
func toCompassIndex(degree: float): 1..32 =
var degree = (degree + degreesPerHeading / 2).floorMod 360
int(degree / degreesPerHeading) + 1
func toCompassHeading(degree: float): string = headingNames[degree.toCompassIndex]
for i in 0..32:
let
heading = float(i) * 11.25 + (case i mod 3
of 1: 5.62
of 2: -5.62
else: 0)
index = heading.toCompassIndex
compassHeading = heading.toCompassHeading.alignLeft(maxNameLength)
echo fmt"{index:>2} {compassHeading} {heading:6.2f}" |
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.
| #FutureBasic | FutureBasic | window 1, @"Bitwise Operations", (0,0,650,270)
def fn rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127)
def fn rotr( b as long, n as long ) as long = (b >> n mod 32) or ( b << (32-n) mod 32)
local fn bitwise( a as long, b as long )
print @"Input: a = "; a; @" b = "; b
print
print @"AND :", @"a && b = ", bin(a && b), @": "; a && b
print @"NAND :", @"a ^& b = ", bin(a ^& b), @": "; a ^& b
print @"OR :", @"a || b = ", bin(a || b), @": "; a || b
print @"NOR :", @"a ^| b = ", bin(a ^| b), @": "; a ^| b
print @"XOR :", @"a ^^ b = ", bin(a ^^ b), @": "; a ^^ b
print @"NOT :", @" not a = ", bin( not a), @": "; not a
print
print @"Left shift :", @"a << b =", bin(a << b), @": "; a << b
print @"Right shift :", @"a >> b =", bin(a >> b), @": "; a >> b
print
print @"Rotate left :", @"fn rotl( a, b ) = ", bin(fn rotl( a, b)), @": "; fn rotl( a, b )
print @"Rotate right :", @"fn rotr( a, b ) = ", bin(fn rotr( a, b )),@": "; fn rotr( a, b )
end fn
fn bitwise( 255, 2 )
HandleEvents |
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.
| #Java | Java | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
public class BasicBitmapStorage {
private final BufferedImage image;
public BasicBitmapStorage(int width, int height) {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
public void fill(Color c) {
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
public void setPixel(int x, int y, Color c) {
image.setRGB(x, y, c.getRGB());
}
public Color getPixel(int x, int y) {
return new Color(image.getRGB(x, y));
}
public Image getImage() {
return image;
}
} |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Nim | Nim | import math
iterator b(): int =
## Iterator yielding the bell numbers.
var numbers = @[1]
yield 1
var n = 0
while true:
var next = 0
for k in 0..n:
next += binom(n, k) * numbers[k]
numbers.add(next)
yield next
inc n
when isMainModule:
import strformat
const Limit = 25 # Maximum index beyond which an overflow occurs.
echo "Bell numbers from B0 to B25:"
var i = 0
for n in b():
echo fmt"{i:2d}: {n:>20d}"
inc i
if i > Limit:
break |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #PARIGP | PARIGP |
genit(maxx=50)={bell=List();
for(n=0,maxx,q=sum(k=0,n,stirling(n,k,2));
listput(bell,q));bell}
END |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the 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 .
| #Icon_and_Unicon | Icon and Unicon | global counts, total
procedure main()
counts := table(0)
total := 0.0
every benlaw(fib(1 to 1000))
every i := 1 to 9 do
write(i,": ",right(100*counts[string(i)]/total,9)," ",100*P(i))
end
procedure benlaw(n)
if counts[n ? (tab(upto('123456789')),move(1))] +:= 1 then total +:= 1
end
procedure P(d)
return log(1+1.0/d, 10)
end
procedure fib(n) # From Fibonacci Sequence task
return fibMat(n)[1]
end
procedure fibMat(n)
if n <= 0 then return [0,0]
if n = 1 then return [1,0]
fp := fibMat(n/2)
c := fp[1]*fp[1] + fp[2]*fp[2]
d := fp[1]*(fp[1]+2*fp[2])
if n%2 = 1 then return [c+d, d]
else return [d, c]
end |
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 +½.
| #FunL | FunL | import integers.choose
def B( n ) = sum( 1/(k + 1)*sum((if 2|r then 1 else -1)*choose(k, r)*(r^n) | r <- 0..k) | k <- 0..n )
for i <- 0..60 if i == 1 or 2|i
printf( "B(%2d) = %s\n", i, B(i) ) |
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.
| #BQN | BQN | BSearch ← {
BS ⟨a, value⟩:
BS ⟨a, value, 0, ¯1+≠a⟩;
BS ⟨a, value, low, high⟩:
mid ← ⌊2÷˜low+high
{
high<low ? ¯1;
(mid⊑a)>value ? BS ⟨a, value, low, mid-1⟩;
(mid⊑a)<value ? BS ⟨a, value, mid+1, high⟩;
mid
}
}
•Show BSearch ⟨8‿30‿35‿45‿49‿77‿79‿82‿87‿97, 97⟩ |
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
| #Groovy | Groovy | def shuffle(text) {
def shuffled = (text as List)
for (sourceIndex in 0..<text.size()) {
for (destinationIndex in 0..<text.size()) {
if (shuffled[sourceIndex] != shuffled[destinationIndex] && shuffled[sourceIndex] != text[destinationIndex] && shuffled[destinationIndex] != text[sourceIndex]) {
char tmp = shuffled[sourceIndex];
shuffled[sourceIndex] = shuffled[destinationIndex];
shuffled[destinationIndex] = tmp;
break;
}
}
}
[original: text, shuffled: shuffled.join(""), score: score(text, shuffled)]
}
def score(original, shuffled) {
int score = 0
original.eachWithIndex { character, index ->
if (character == shuffled[index]) {
score++
}
}
score
}
["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"].each { text ->
def result = shuffle(text)
println "${result.original}, ${result.shuffled}, (${result.score})"
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | (* String creation and destruction *) BinaryString = {}; BinaryString = . ;
(* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65}
-> {12,56,82,65}
-> {83,12,56,65}
(* String comparison *) BinaryString1 === BinaryString2
-> False
(* String cloning and copying *) BinaryString3 = BinaryString1
-> {12,56,82,65}
(* Check if a string is empty *) BinaryString3 === {}
-> False
(* Append a byte to a string *) AppendTo[BinaryString3, 22]
-> {12,56,82,65,22}
(* Extract a substring from a string *) Take[BinaryString3, {2, 5}]
-> {56,82,65,22}
(* Replace every occurrence of a byte (or a string) in a string with another string *)
BinaryString3 /. {22 -> Sequence[33, 44]}
-> {12,56,82,65,33,44}
(* Join strings *) BinaryString4 = Join[BinaryString1 , BinaryString2]
-> {12,56,82,65,83,12,56,65} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #MATLAB_.2F_Octave | MATLAB / Octave |
a=['123',0,' abc '];
b=['456',9];
c='789';
disp(a);
disp(b);
disp(c);
% string comparison
printf('(a==b) is %i\n',strcmp(a,b));
% string copying
A = a;
B = b;
C = c;
disp(A);
disp(B);
disp(C);
% check if string is empty
if (length(a)==0)
printf('\nstring a is empty\n');
else
printf('\nstring a is not empty\n');
end
% append a byte to a string
a=[a,64];
disp(a);
% substring
e = a(1:6);
disp(e);
% join strings
d=[a,b,c];
disp(d);
|
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.
| #Axe | Axe | Lbl BIN
.Axe supports 16-bit integers, so 16 digits are enough
L₁+16→P
0→{P}
While r₁
P--
{(r₁ and 1)▶Hex+3}→P
r₁/2→r₁
End
Disp P,i
Return |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #Lua | Lua |
-----------------------------------------------
-- Bitmap replacement
-- (why? current Lua impl lacks a "set" method)
-----------------------------------------------
local Bitmap = {
new = function(self, width, height)
local instance = setmetatable({ width=width, height=height }, self)
instance:alloc()
return instance
end,
alloc = function(self)
self.pixels = {}
for y = 1, self.height do
self.pixels[y] = {}
for x = 1, self.width do
self.pixels[y][x] = 0x00000000
end
end
end,
clear = function(self, c)
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = c or 0x00000000
end
end
end,
get = function(self, x, y)
x, y = math.floor(x+1), math.floor(y+1)
if ((x>=1) and (x<=self.width) and (y>=1) and (y<=self.height)) then
return self.pixels[y][x]
else
return nil
end
end,
set = function(self, x, y, c)
x, y = math.floor(x+1), math.floor(y+1)
if ((x>=1) and (x<=self.width) and (y>=1) and (y<=self.height)) then
self.pixels[y][x] = c or 0x00000000
end
end,
}
Bitmap.__index = Bitmap
setmetatable(Bitmap, { __call = function (t, ...) return t:new(...) end })
------------------------------
-- Bresenham's Line Algorithm:
------------------------------
Bitmap.line = function(self, x1, y1, x2, y2, c)
local dx, sx = math.abs(x2-x1), x1<x2 and 1 or -1
local dy, sy = math.abs(y2-y1), y1<y2 and 1 or -1
local err = math.floor((dx>dy and dx or -dy)/2)
while(true) do
self:set(x1, y1, c or 0xFFFFFFFF)
if (x1==x2 and y1==y2) then break end
if (err > -dx) then
err, x1 = err-dy, x1+sx
if (x1==x2 and y1==y2) then
self:set(x1, y1, c or 0xFFFFFFFF)
break
end
end
if (err < dy) then
err, y1 = err+dx, y1+sy
end
end
end
--------
-- Demo:
--------
Bitmap.render = function(self, charmap)
for y = 1, self.height do
local rowtab = {}
for x = 1, self.width do
rowtab[x] = charmap[self.pixels[y][x]]
end
print(table.concat(rowtab))
end
end
local bitmap = Bitmap(61,21)
bitmap:clear()
bitmap:line(0,10,30,0)
bitmap:line(30,0,60,10)
bitmap:line(60,10,30,20)
bitmap:line(30,20,0,10)
bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'}) |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #PostScript | PostScript | true
false |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #PowerShell | PowerShell | $true
$false |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Python | Python | >>> True
True
>>> not True
False
>>> # As numbers
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> # Numbers as booleans
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> # Collections as booleans
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass 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)..
| #Objeck | Objeck |
class BoxCompass {
function : Main(args : String[]) ~ Nil {
points := [
"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 " ];
for(i := 0; i<= 32; i += 1;) {
heading := i * 11.25;
select(i % 3) {
label 1: {
heading += 5.62;
}
label 2: {
heading -= 5.62;
}
};
IO.Console->Print((i % 32) + 1)->Print('\t')->Print(points[GetPoint(heading)])
->Print('\t')->PrintLine(heading);
};
}
function : GetPoint(degrees : Float) ~ Int {
return (degrees / 11.25 + 0.5)->Floor()->As(Int) % 32;
}
}
|
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.
| #Go | Go | package main
import "fmt"
func bitwise(a, b int16) {
fmt.Printf("a: %016b\n", uint16(a))
fmt.Printf("b: %016b\n", uint16(b))
// Bitwise logical operations
fmt.Printf("and: %016b\n", uint16(a&b))
fmt.Printf("or: %016b\n", uint16(a|b))
fmt.Printf("xor: %016b\n", uint16(a^b))
fmt.Printf("not: %016b\n", uint16(^a))
if b < 0 {
fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
return
}
ua := uint16(a)
ub := uint32(b)
// Logical shifts (unsigned left operand)
fmt.Printf("shl: %016b\n", uint16(ua<<ub))
fmt.Printf("shr: %016b\n", uint16(ua>>ub))
// Arithmetic shifts (signed left operand)
fmt.Printf("las: %016b\n", uint16(a<<ub))
fmt.Printf("ras: %016b\n", uint16(a>>ub))
// Rotations
fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}
func main() {
var a, b int16 = -460, 6
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.
| #JavaScript | JavaScript |
// Set up the canvas
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
width = 400, height = 400;
ctx.canvas.width = width;
ctx.canvas.height = height;
// Optionaly add it to the current page
document.body.appendChild(canvas);
// Draw an image
var img = document.createElement("img");
img.onload = function(){
// Draw the element into the top-left of the canvas
ctx.drawImage(img, 0, 0);
};
img.src = "//placehold.it/400x400";
// Fill the canvas with a solid blue color
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, width, height);
// Place a black pixel in the middle
// Note that a pixel is a 1 by 1 rectangle
// This is the fastest method as of 2012 benchmarks
ctx.fillStyle = "black";
ctx.fillRect(width / 2, height / 2, 1, 1);
|
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Pascal | Pascal | program BellNumbers;
{$Ifdef FPC}
{$optimization on,all}
{$ElseIf}
{Apptype console}
{$EndIf}
uses
sysutils,gmp;
var
T0 :TDateTime;
procedure BellNumbersUint64(OnlyBellNumbers:Boolean);
var
BList : array[0..24] of Uint64;
BellNum : Uint64;
BListLenght,i :nativeUInt;
begin
IF OnlyBellNUmbers then
Begin
writeln('Bell triangles ');
writeln(' 1 = 1');
end
else
Begin
writeln('Bell numbers');
writeln(' 1 = 1');
writeln(' 2 = 1');
end;
BList[0]:= 1;
BListLenght := 1;
BellNum := 1;
repeat
// For i := BListLenght downto 1 do BList[i] := BList[i-1]; or
move(Blist[0],Blist[1],BListLenght*SizeOf(Blist[0]));
BList[0] := BellNum;
For i := 1 to BListLenght do
Begin
BellNum += BList[i];
BList[i] := BellNum;
end;
// Output
IF OnlyBellNUmbers then
Begin
IF BListLenght<=9 then
Begin
write(BListLenght+1:3,' = ');
For i := 0 to BListLenght do
write(BList[i]:7);
writeln;
end
ELSE
BREAK;
end
else
writeln(BListLenght+2:3,' = ',BellNum);
inc(BListLenght);
until BListLenght >= 25;
writeln;
end;
procedure BellNumbersMPInteger;
const
MaxIndex = 5000;//must be > 0
var
//MPInteger as alternative to mpz_t -> selfcleaning
BList : array[0..MaxIndex] of MPInteger;
BellNum : MPInteger;
BListLenght,i :nativeUInt;
BellNumStr : AnsiString;
Begin
BellNumStr := '';
z_init(BellNum);
z_ui_pow_ui(BellNum,10,32767);
BListLenght := z_size(BellNum);
writeln('init length ',BListLenght);
For i := 0 to MaxIndex do
Begin
// z_init2_set(BList[i],BListLenght);
z_add_ui( BList[i],i);
end;
writeln('init length ',z_size(BList[0]));
T0 := now;
BListLenght := 1;
z_set_ui(BList[0],1);
z_set_ui(BellNum,1);
repeat
//Move does not fit moving interfaces // call fpc_intf_assign
For i := BListLenght downto 1 do BList[i] := BList[i-1];
z_set(BList[0],BellNum);
For i := 1 to BListLenght do
Begin
BellNum := z_add(BellNum,BList[i]);
z_set(BList[i],BellNum);
end;
inc(BListLenght);
if (BListLenght+1) MOD 100 = 0 then
Begin
BellNumStr:= z_get_str(10,BellNum);
//z_sizeinbase (BellNum, 10) is not exact :-(
write('Bell(',(IntToStr(BListLenght)):6,') has ',
(IntToStr(Length(BellNumStr))):6,' decimal digits');
writeln(FormatDateTime(' NN:SS.ZZZ',now-T0),'s');
end;
until BListLenght>=MaxIndex;
BellNumStr:= z_get_str(10,BellNum);
writeln(BListLenght:6,'.th ',Length(BellNumStr):8);
//clean up ;-)
BellNumStr := '';
z_clear(BellNum);
For i := MaxIndex downto 0 do
z_clear(BList[i]);
end;
BEGIN
BellNumbersUint64(True);BellNumbersUint64(False);
BellNumbersMPInteger;
END. |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the 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 .
| #J | J | log10 =: 10&^.
benford =: log10@:(1+%)
assert '0.30 0.18 0.12 0.10 0.08 0.07 0.06 0.05 0.05' -: 5j2 ": benford >: i. 9
append_next_fib =: , +/@:(_2&{.)
assert 5 8 13 -: append_next_fib 5 8
leading_digits =: {.@":&>
assert '581' -: leading_digits 5 8 13x
count =: #/.~ /: ~.
assert 2 1 3 4 -: count 'XCXBAXACXC' NB. 2 A's, 1 B, 3 C's, and some X's.
normalize =: % +/
assert 1r3 2r3 -: normalize 1 2x
FIB =: append_next_fib ^: (1000-#) 1 1
LDF =: leading_digits FIB
TALLY_BY_KEY =: count LDF
assert 9 -: # TALLY_BY_KEY NB. If all of [1-9] are present then we know what the digits are.
mean =: +/ % #
center=: - mean
mp =: $:~ :(+/ .*)
num =: mp&:center
den =: %:@:(*&:(+/@:(*:@:center)))
r =: num % den NB. r is the LibreOffice correl function
assert '_0.982' -: 6j3 ": 1 2 3 r 6 5 3 NB. confirmed using LibreOffice correl function
assert '0.9999' -: 6j4 ": (normalize TALLY_BY_KEY) r benford >: i.9
assert '0.9999' -: 6j4 ": TALLY_BY_KEY r benford >: i.9 NB. Of course we don't need normalization |
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 +½.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do
Print(a, "\n");
od;
[ 0, 1 ]
[ 1, -1/2 ]
[ 2, 1/6 ]
[ 4, -1/30 ]
[ 6, 1/42 ]
[ 8, -1/30 ]
[ 10, 5/66 ]
[ 12, -691/2730 ]
[ 14, 7/6 ]
[ 16, -3617/510 ]
[ 18, 43867/798 ]
[ 20, -174611/330 ]
[ 22, 854513/138 ]
[ 24, -236364091/2730 ]
[ 26, 8553103/6 ]
[ 28, -23749461029/870 ]
[ 30, 8615841276005/14322 ]
[ 32, -7709321041217/510 ]
[ 34, 2577687858367/6 ]
[ 36, -26315271553053477373/1919190 ]
[ 38, 2929993913841559/6 ]
[ 40, -261082718496449122051/13530 ]
[ 42, 1520097643918070802691/1806 ]
[ 44, -27833269579301024235023/690 ]
[ 46, 596451111593912163277961/282 ]
[ 48, -5609403368997817686249127547/46410 ]
[ 50, 495057205241079648212477525/66 ]
[ 52, -801165718135489957347924991853/1590 ]
[ 54, 29149963634884862421418123812691/798 ]
[ 56, -2479392929313226753685415739663229/870 ]
[ 58, 84483613348880041862046775994036021/354 ]
[ 60, -1215233140483755572040304994079820246041491/56786730 ] |
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.
| #Brat | Brat | binary_search = { search_array, value, low, high |
true? high < low
{ null }
{
mid = ((low + high) / 2).to_i
true? search_array[mid] > value
{ binary_search search_array, value, low, mid - 1 }
{ true? search_array[mid] < value
{ binary_search search_array, value, mid + 1, high }
{ mid }
}
}
}
#Populate array
numbers = 1000.of { random 1000 }
#Sort the array
numbers.sort!
#Find a number
x = random 1000
p "Looking for #{x}"
index = binary_search numbers, x, 0, numbers.length - 1
null? index
{ p "Not found" }
{ p "Found at index: #{index}" } |
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
| #Haskell | Haskell | shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2
printTest prog = mapM_ test texts
where
test s = do
x <- prog s
putStrLn $ unwords $ [ show s
, show x
, show $ shufflingQuality s x]
texts = [ "abba", "abracadabra", "seesaw", "elk" , "grrrrrr"
, "up", "a", "aaaaa.....bbbbb"
, "Rosetta Code is a programming chrestomathy site." ] |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Nim | Nim | var # creation
x = "this is a string"
y = "this is another string"
z = "this is a string"
if x == z: echo "x is z" # comparison
z = "now this is another string too" # assignment
y = z # copying
if x.len == 0: echo "empty" # check if empty
x.add('!') # append a byte
echo x[5..8] # substring
echo x[8 .. ^1] # substring
z = x & y # join strings
import strutils
echo z.replace('t', 'T') # replace occurences of t with T |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #OCaml | OCaml | # String.create 10 ;;
- : string = "\000\023\000\000\001\000\000\000\000\000" |
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.
| #BaCon | BaCon | ' Binary digits
OPTION MEMTYPE int
INPUT n$
IF VAL(n$) = 0 THEN
PRINT "0"
ELSE
PRINT CHOP$(BIN$(VAL(n$)), "0", 1)
ENDIF |
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.
| #Maple | Maple | SegmentBresenham := proc (img, x0, y0, x1, y1)
local deltax, deltay, x, y, ystep, steep, err, img2, x02, y02, x12, y12;
x02, x12, y02, y12 := y0, y1, x0, x1;
steep := abs(x12 - x02) < abs(y12 - y02);
img2 := copy(img);
if steep then
x02, y02 := y02, x02;
x12, y12 := y12, x12;
end if;
if x12 < x02 then
x02, x12 := x12, x02;
y02, y12 := y12, y02;
end if;
deltax := x12 - x02;
deltay := abs(y12 - y02);
err := deltax / 2;
y := y02;
if y02 < y12 then
ystep := 1
else
ystep := -1
end if;
for x from x02 to x12 do
if steep then
img2[y, x] := 0
else
img2[x, y] := 0
end if;
err := err - deltay;
if err < 0 then
y := y + ystep;
err := err + deltax
end if;
end do;
return img2;
end proc: |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Quackery | Quackery | (cond ([(< 4 3) 'apple]
['bloggle 'pear]
[else 'nectarine]) |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #R | R | (cond ([(< 4 3) 'apple]
['bloggle 'pear]
[else 'nectarine]) |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Racket | Racket | (cond ([(< 4 3) 'apple]
['bloggle 'pear]
[else 'nectarine]) |
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)..
| #OCaml | OCaml |
let test_cases = [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];;
let directions = ["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";];;
let get_direction_index input =
let shifted = (input +. 5.6201) in
let shifted = if shifted > 360. then shifted -. 360. else shifted in
int_of_float (shifted /. 11.25);;
let print_direction input =
let index = get_direction_index input in
let direction = List.nth directions index in
let test = Printf.printf "%3d %-20s %.2f\n" (index + 1) direction in
test input;;
List.iter (print_direction) test_cases;;
|
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.
| #Groovy | Groovy | def bitwise = { a, b ->
println """
a & b = ${a} & ${b} = ${a & b}
a | b = ${a} | ${b} = ${a | b}
a ^ b = ${a} ^ ${b} = ${a ^ b}
~ a = ~ ${a} = ${~ a}
a << b = ${a} << ${b} = ${a << b}
a >> b = ${a} >> ${b} = ${a >> b} arithmetic (sign-preserving) shift
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) 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.
| #Julia | Julia | using Images, Colors
Base.hex(p::RGB{T}) where T = join(hex(c(p), 2) for c in (red, green, blue))
function showhex(m::Matrix{RGB{T}}, pad::Integer=4) where T
for r in 1:size(m, 1)
println(" " ^ pad, join(hex.(m[r, :]), " "))
end
end
w, h = 5, 7
cback = RGB(1, 0, 1)
cfore = RGB(0, 1, 0)
img = Array{RGB{N0f8}}(h, w);
println("Uninitialized image:")
showhex(img)
fill!(img, cback)
println("\nImage filled with background color:")
showhex(img)
img[2, 3] = cfore
println("\nImage with a pixel set for foreground color:")
showhex(img) |
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.
| #KonsolScript | KonsolScript | function main() {
Var:Number shape;
Image:New(50, 50, shape)
Draw:RectFill(0, 0, 50, 50, 0xFF0000, shape) //one to fill an image with a plain RED color
Draw:Pixel(30, 30, 0x0000FF, shape) //set a given pixel at (30,30) with a BLUE color
while (B1 == false) {
Image:Blit(10, 10, shape, screen)
Screen:Render()
}
} |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Perl | Perl | use strict 'vars';
use warnings;
use feature 'say';
use bigint;
my @b = 1;
my @Aitkens = [1];
push @Aitkens, do {
my @c = $b[-1];
push @c, $b[$_] + $c[$_] for 0..$#b;
@b = @c;
[@c]
} until (@Aitkens == 50);
my @Bell_numbers = map { @$_[0] } @Aitkens;
say 'First fifteen and fiftieth Bell numbers:';
printf "%2d: %s\n", 1+$_, $Bell_numbers[$_] for 0..14, 49;
say "\nFirst ten rows of Aitken's array:";
printf '%-7d'x@{$Aitkens[$_]}."\n", @{$Aitkens[$_]} for 0..9; |
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 .
| #Java | Java | import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
} |
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 +½.
| #GAP | GAP | for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do
Print(a, "\n");
od;
[ 0, 1 ]
[ 1, -1/2 ]
[ 2, 1/6 ]
[ 4, -1/30 ]
[ 6, 1/42 ]
[ 8, -1/30 ]
[ 10, 5/66 ]
[ 12, -691/2730 ]
[ 14, 7/6 ]
[ 16, -3617/510 ]
[ 18, 43867/798 ]
[ 20, -174611/330 ]
[ 22, 854513/138 ]
[ 24, -236364091/2730 ]
[ 26, 8553103/6 ]
[ 28, -23749461029/870 ]
[ 30, 8615841276005/14322 ]
[ 32, -7709321041217/510 ]
[ 34, 2577687858367/6 ]
[ 36, -26315271553053477373/1919190 ]
[ 38, 2929993913841559/6 ]
[ 40, -261082718496449122051/13530 ]
[ 42, 1520097643918070802691/1806 ]
[ 44, -27833269579301024235023/690 ]
[ 46, 596451111593912163277961/282 ]
[ 48, -5609403368997817686249127547/46410 ]
[ 50, 495057205241079648212477525/66 ]
[ 52, -801165718135489957347924991853/1590 ]
[ 54, 29149963634884862421418123812691/798 ]
[ 56, -2479392929313226753685415739663229/870 ]
[ 58, 84483613348880041862046775994036021/354 ]
[ 60, -1215233140483755572040304994079820246041491/56786730 ] |
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.
| #C | C | #include <stdio.h>
int bsearch (int *a, int n, int x) {
int i = 0, j = n - 1;
while (i <= j) {
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
i = k + 1;
}
else {
j = k - 1;
}
}
return -1;
}
int bsearch_r (int *a, int x, int i, int j) {
if (j < i) {
return -1;
}
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
return bsearch_r(a, x, k + 1, j);
}
else {
return bsearch_r(a, x, i, k - 1);
}
}
int main () {
int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
int n = sizeof a / sizeof a[0];
int x = 2;
int i = bsearch(a, n, x);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
x = 5;
i = bsearch_r(a, x, 0, n - 1);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
return 0;
}
|
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
| #Icon_and_Unicon | Icon and Unicon | # every !t :=: ?t # Uncomment to get a random best shuffling |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #PARI.2FGP | PARI/GP | cmp_str(u,v)=u==v
copy_str(v)=v \\ Creates a copy, not a pointer
append_str(v,n)=concat(v,n)
replace_str(source, n, replacement)=my(v=[]);for(i=1,#source,v=concat(v,if(source[i]==n,replacement,source[i]))); v
u=[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100];
v=[];
cmp_str(u,v)
w=copy_str(v)
#w==0
append_str(u,33)
u[8..12]
replace_str(u,108,[121])
concat(v,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.
| #BASIC | BASIC | 0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END
1 LET N2 = ABS ( INT (N))
2 LET B$ = ""
3 FOR N1 = N2 TO 0 STEP 0
4 LET N2 = INT (N1 / 2)
5 LET B$ = STR$ (N1 - N2 * 2) + B$
6 LET N1 = N2
7 NEXT N1
8 PRINT B$
9 RETURN |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Rasterize[Style[Graphics[Line[{{0, 0}, {20, 10}}]], Antialiasing -> False]] |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Raku | Raku | my Bool $crashed = False;
my $val = 0 but True; |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Raven | Raven | TRUE print
FALSE print
2 1 > print # TRUE (-1)
3 2 < print # FALSE (0)
42 FALSE != # TRUE (-1) |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #REBOL | REBOL | true = 1
false = 0 |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #OoRexx | OoRexx | /* Rexx */
Do
globs = '!DEG !MIN !SEC !FULL'
Drop !DEG !MIN !SEC !FULL
sign. = ''
sign.!DEG = 'c2b0'x -- degree sign : U+00B0
sign.!MIN = 'e280b2'x -- prime : U+2032
sign.!SEC = 'e280b3'x -- double prime : U+2033
points. = ''
Call display_compass_points
Call display_sample
Say
headings. = ''
headings.0 = 0
Call make_headings
Call flush_queue
Do h_ = 1 to headings.0
Queue headings.h_
End h_
Call display_sample
Say
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
flush_queue:
Procedure
Do
Do q_ = 1 to queued()
Parse pull .
End q_
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
display_sample:
Procedure Expose points. sign. (globs)
Do
Do q_ = 1 to queued()
Parse pull heading
index = get_index(heading)
Parse Value get_point(index) with p_abbrev p_full
Say index~right(3),
p_abbrev~left(4) p_full~left(20),
heading~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(heading)')',
''
End q_
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
display_compass_points:
Procedure Expose points. sign. (globs)
Do
points = 32
one_pt = 360 / points
Do h_ = 0 to points - 1
heading = h_ * 360 / points
hmin = heading - one_pt / 2
hmax = heading + one_pt / 2
If hmin < 0 then Do
hmin = hmin + 360
End
If hmax >= 360 then Do
hmax = hmax - 360
End
index = (h_ // points) + 1
Parse Value get_point(index) with p_abbrev p_full
Say index~right(3),
p_abbrev~left(4) p_full~left(20),
hmin~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(hmin)')',
heading~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(heading)')',
hmax~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(hmax)')',
''
End h_
Say
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
make_headings:
Procedure Expose headings.
Do
points = 32
Do i_ = 0 to points
heading = i_ * 360 / 32
it = i_ // 3
Select
When it = 1 then Do
heading_h = heading + 5.62
End
When it = 2 then Do
heading_h = heading - 5.62
End
Otherwise Do
heading_h = heading
End
End
index = (i_ // points) + 1
ix = headings.0 + 1; headings.0 = ix; headings.ix = heading_h
End i_
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
get_index:
Procedure
Do
Parse Arg heading .
one_pt = 360 / 32
hn = heading // 360
hi = hn % one_pt
If hn > hi * one_pt + one_pt / 2 then Do
hi = hi + 1 -- greater than max range for this point; bump to next point
End
idx = hi // 32 + 1 -- add one to get index into points. stem
Return idx
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
get_point:
Procedure Expose points. sign. (globs)
Do
Parse arg index .
Call get_points
Return points.index points.index.!FULL
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
get_points:
Procedure Expose points. sign. (globs)
Do
Drop !FULL
points. = ''
p_ = 0
p_ = p_ + 1; points.0 = p_; points.p_ = 'N'; points.p_.!FULL = 'North'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NbE'; points.p_.!FULL = 'North by East'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NNE'; points.p_.!FULL = 'North-Northeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NEbn'; points.p_.!FULL = 'Northeast by North'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NE'; points.p_.!FULL = 'Northeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NEbE'; points.p_.!FULL = 'Northeast by East'
p_ = p_ + 1; points.0 = p_; points.p_ = 'ENE'; points.p_.!FULL = 'East-Northeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'EbN'; points.p_.!FULL = 'East by North'
p_ = p_ + 1; points.0 = p_; points.p_ = 'E'; points.p_.!FULL = 'East'
p_ = p_ + 1; points.0 = p_; points.p_ = 'EbS'; points.p_.!FULL = 'East by South'
p_ = p_ + 1; points.0 = p_; points.p_ = 'ESE'; points.p_.!FULL = 'East-Southeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SEbE'; points.p_.!FULL = 'Southeast by East'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SE'; points.p_.!FULL = 'Southeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SEbS'; points.p_.!FULL = 'Southeast by South'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SSE'; points.p_.!FULL = 'South-Southeast'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SbE'; points.p_.!FULL = 'South by East'
p_ = p_ + 1; points.0 = p_; points.p_ = 'S'; points.p_.!FULL = 'South'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SbW'; points.p_.!FULL = 'South by West'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SSW'; points.p_.!FULL = 'South-Southwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SWbS'; points.p_.!FULL = 'Southwest by South'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SW'; points.p_.!FULL = 'Southwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'SWbW'; points.p_.!FULL = 'Southwest by West'
p_ = p_ + 1; points.0 = p_; points.p_ = 'WSW'; points.p_.!FULL = 'Southwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'WbS'; points.p_.!FULL = 'West by South'
p_ = p_ + 1; points.0 = p_; points.p_ = 'W'; points.p_.!FULL = 'West'
p_ = p_ + 1; points.0 = p_; points.p_ = 'WbN'; points.p_.!FULL = 'West by North'
p_ = p_ + 1; points.0 = p_; points.p_ = 'WNW'; points.p_.!FULL = 'West-Northwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NWbW'; points.p_.!FULL = 'Northwest by West'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NW'; points.p_.!FULL = 'Northwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NWbN'; points.p_.!FULL = 'Northwest by North'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NNW'; points.p_.!FULL = 'North-Northwest'
p_ = p_ + 1; points.0 = p_; points.p_ = 'NbW'; points.p_.!FULL = 'North by West'
Return
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
get_decimal_angle:
Procedure Expose sign. (globs)
Do
Parse Arg degrees ., minutes ., seconds .
degrees = degrees * 10 % 10
minutes = minutes * 10 % 10
angle = degrees + minutes / 60 + seconds / 60 / 60
Return angle
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
format_decimal_angle:
Procedure Expose sign. (globs)
Do
Parse Arg degrees ., minutes ., seconds .
Return get_decimal_angle(degrees, minutes, seconds)~format(5, 3) || sign.!DEG
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
get_degrees_minutes_seconds:
Procedure Expose sign. (globs)
Do
Parse arg angle .
degrees = angle * 100 % 100
minutes = ((angle - degrees) * 60) * 100 % 100
seconds = ((((angle - degrees) * 60) - minutes) * 60) * 100 % 100
Return degrees minutes seconds
End
Exit
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
format_degrees_minutes_seconds:
Procedure Expose sign. (globs)
Do
Parse arg angle .
Parse Value get_degrees_minutes_seconds(angle) with degrees minutes seconds .
formatted = degrees~right(3) || sign.!DEG || minutes~right(2, 0) || sign.!MIN || seconds~right(2, 0) || sign.!SEC
Return formatted
End
Exit
|
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.
| #Harbour | Harbour |
PROCEDURE Main(...)
local n1 := 42, n2 := 2
local aPar := hb_AParams()
local nRot
if ! Empty( aPar )
n1 := Val( aPar[1] )
hb_Adel( aPar, 1, .T. )
if ! Empty( aPar )
n2 := Val( aPar[1] )
endif
endif
clear screen
? "Bitwise operations with two integers"
? "n1 =", hb_ntos(n1)
? "n2 =", hb_ntos(n2)
? "------------------------------------"
? "AND -->", hb_BitAnd( n1, n2 )
? "OR -->", hb_BitOr( n1, n2 )
? "XOR -->", hb_BitXor( n1, n2 )
? "NOT -->", hb_BitNot( n1 )
? "LSHIFT -->", hb_bitShift( n1, n2 )
? "RSHIFT -->", hb_bitShift( n1, -n2 )
? "RarSHIFT -->", hb_bitShift( n1, -n2 )
/* left/right rotation is not implemented, but we can use inline C-code to do it */
/* rotate n1 to the left by n2 bits */
nRot := hb_Inline( n1, n2 ) {
HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 );
hb_retni( (x << s) | (x >> (-s & 31)) );
} // (x << s) | (x >> (32 - s));
? "Rotate left -->", nRot
/* rotate n1 to the right by n2 bits */
nRot := HB_INLINE( n1, n2 ){
HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 );
hb_retni( (x >> s) | (x << (32 - s)) );
}
? "Rotate right -->", nRot
return
|
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.
| #Kotlin | Kotlin | // version 1.1.4-3
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val width = 640
val height = 480
val bbs = BasicBitmapStorage(width, height)
with (bbs) {
fill(Color.cyan)
setPixel(width / 2, height / 2, Color.black)
val c1 = getPixel(width / 2, height / 2)
val c2 = getPixel(20, 20)
print("The color of the pixel at (${width / 2}, ${height / 2}) is ")
println(if (c1 == Color.black) "black" else "unknown")
print("The color of the pixel at (120, 120) is ")
println(if (c2 == Color.cyan) "cyan" else "unknown")
}
} |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Phix | Phix | with javascript_semantics
include mpfr.e
function bellTriangle(integer n)
-- nb: returns strings to simplify output
mpz z = mpz_init(1)
string sz = "1"
sequence tri = {}, line = {}
for i=1 to n do
line = prepend(line,mpz_init_set(z))
tri = append(tri,{sz})
for j=2 to length(line) do
mpz_add(z,z,line[j])
mpz_set(line[j],z)
sz = mpz_get_str(z)
tri[$] = append(tri[$],sz)
end for
end for
line = mpz_free(line)
z = mpz_free(z)
return tri
end function
sequence bt = bellTriangle(50)
printf(1,"First fifteen and fiftieth Bell numbers:\n%s\n50:%s\n\n",
{join(vslice(bt[1..15],1)),bt[50][1]})
printf(1,"The first ten rows of Bell's triangle:\n")
for i=1 to 10 do
printf(1,"%s\n",{join(bt[i])})
end for
|
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 .
| #JavaScript | JavaScript | const fibseries = n => [...Array(n)]
.reduce(
(fib, _, i) => i < 2 ? (
fib
) : fib.concat(fib[i - 1] + fib[i - 2]),
[1, 1]
);
const benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9]
.map(val => [val, array
.reduce(
(sum, item) => sum + (
`${item}` [0] === `${val}`
),
0
) / array.length, Math.log10(1 + 1 / val)
]);
console.log(benford(fibseries(1000))) |
http://rosettacode.org/wiki/Bernoulli_numbers | Bernoulli numbers | Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.
Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per The National Institute of 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 +½.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func b(n int) *big.Rat {
var f big.Rat
a := make([]big.Rat, n+1)
for m := range a {
a[m].SetFrac64(1, int64(m+1))
for j := m; j >= 1; j-- {
d := &a[j-1]
d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j]))
}
}
return f.Set(&a[0])
}
func main() {
for n := 0; n <= 60; n++ {
if b := b(n); b.Num().BitLen() > 0 {
fmt.Printf("B(%2d) =%45s/%s\n", n, b.Num(), b.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.
| #C.23 | C# | namespace Search {
using System;
public static partial class Extensions {
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value)
where T : IComparable {
return entries.RecursiveBinarySearchForGLB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
if (left <= right) {
var middle = left + (right - left) / 2;
return entries[middle].CompareTo(value) < 0 ?
entries.RecursiveBinarySearchForGLB(value, middle + 1, right) :
entries.RecursiveBinarySearchForGLB(value, left, middle - 1);
}
//[Assert]left == right + 1
// GLB: entries[right] < value && value <= entries[right + 1]
return right;
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value)
where T : IComparable {
return entries.RecursiveBinarySearchForLUB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
if (left <= right) {
var middle = left + (right - left) / 2;
return entries[middle].CompareTo(value) <= 0 ?
entries.RecursiveBinarySearchForLUB(value, middle + 1, right) :
entries.RecursiveBinarySearchForLUB(value, left, middle - 1);
}
//[Assert]left == right + 1
// LUB: entries[left] > value && value >= entries[left - 1]
return left;
}
}
} |
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
| #J | J | bestShuf =: verb define
yy=. <@({~ ?~@#)@I.@= y
y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy
)
fmtBest=:3 :0
b=. bestShuf y
y,', ',b,' (',')',~":+/b=y
)
|
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Pascal | Pascal | const
greeting = 'Hello';
var
s1: string;
s2: ansistring;
s3: pchar;
begin
{ Assignments }
s1 := 'Mister Presiden'; (* typo is on purpose. See below! *)
{ Comparisons }
if s2 > 'a' then
writeln ('The first letter of ', s1, ' is later than a');
{ Cloning and copying }
s2 := greeting;
{ Check if a string is empty }
if s1 = '' then
writeln('This string is empty!');
{ Append a byte to a string }
s1 := s1 + 't';
{ Extract a substring from a string }
s3 := copy(S2, 2, 4); (* s3 receives ello *)
{ String replacement } (* the unit StrUtils of the FreePascal rtl has AnsiReplaceStr *)
s1 := AnsiReplaceStr('Thees ees a text weeth typos', 'ee', 'i');
{ Join strings}
s3 := greeting + ' and how are you, ' + s1 + '?';
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.
| #Bash | Bash |
function to_binary () {
if [ $1 -ge 0 ]
then
val=$1
binary_digits=()
while [ $val -gt 0 ]; do
bit=$((val % 2))
quotient=$((val / 2))
binary_digits+=("${bit}")
val=$quotient
done
echo "${binary_digits[*]}" | rev
else
echo ERROR : "negative number"
exit 1
fi
}
array=(5 50 9000)
for number in "${array[@]}"; do
echo $number " :> " $(to_binary $number)
done
|
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.
| #MATLAB | MATLAB |
%screen = Bitmap object
%startPoint = [x0,y0]
%endPoint = [x1,y1]
%color = [red,green,blue]
function bresenhamLine(screen,startPoint,endPoint,color)
if( any(color > 255) )
error 'RGB colors must be between 0 and 255';
end
%Check for vertical line, x0 == x1
if( startPoint(1) == endPoint(1) )
%Draw vertical line
for i = (startPoint(2):endPoint(2))
setPixel(screen,[startPoint(1) i],color);
end
end
%Simplified Bresenham algorithm
dx = abs(endPoint(1) - startPoint(1));
dy = abs(endPoint(2) - startPoint(2));
if(startPoint(1) < endPoint(1))
sx = 1;
else
sx = -1;
end
if(startPoint(2) < endPoint(2))
sy = 1;
else
sy = -1;
end
err = dx - dy;
pixel = startPoint;
while(true)
screen.setPixel(pixel,color); %setPixel(x0,y0)
if( pixel == endPoint )
break;
end
e2 = 2*err;
if( e2 > -dy )
err = err - dy;
pixel(1) = pixel(1) + sx;
end
if( e2 < dx )
err = err + dx;
pixel(2) = pixel(2) + sy;
end
end
assignin('caller',inputname(1),screen); %saves the changes to the object
end
|
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #ReScript | ReScript | true = 1
false = 0 |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Retro | Retro | true = 1
false = 0 |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #REXX | REXX | true = 1
false = 0 |
http://rosettacode.org/wiki/Box_the_compass | Box the compass | There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
Task description
Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
Notes;
The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| #PARI.2FGP | PARI/GP | box(x)={["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"][round(x*4/45)%32+1]};
for(i=0,32,print(i%32+1" "box(x=i*11.25+if(i%3==1,5.62,if(i%3==2,-5.62)))" "x)) |
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.
| #Haskell | Haskell | import Data.Bits
bitwise :: Int -> Int -> IO ()
bitwise a b =
mapM_
print
[ a .&. b
, a .|. b
, a `xor` b
, complement a
, shiftL a b -- left shift
, shiftR a b -- arithmetic right shift
, shift a b -- You can also use the "unified" shift function;
-- positive is for left shift, negative is for right shift
, shift a (-b)
, rotateL a b -- rotate left
, rotateR a b -- rotate right
, rotate a b -- You can also use the "unified" rotate function;
-- positive is for left rotate, negative is for right rotate
, rotate a (-b)
]
main :: IO ()
main = bitwise 255 170 |
http://rosettacode.org/wiki/Bitmap | Bitmap | Show a basic storage type to handle a simple RGB raster graphics image,
and some primitive associated functions.
If possible provide a function to allocate an uninitialised image,
given its width and height, and provide 3 additional functions:
one to fill an image with a plain RGB color,
one to set a given 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.
| #Lingo | Lingo | -- Creates a new image object of size 640x480 pixel and 32-bit color depth
img = image(640, 480, 32)
-- Fills image with plain red
img.fill(img.rect, rgb(255,0,0))
-- Gets the color value of the pixel at point (320, 240)
col = img.getPixel(320, 240)
-- Changes the color of the pixel at point (320, 240) to black
img.setPixel(320, 240, rgb(0,0,0)) |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Picat | Picat | main =>
B50=b(50),
println(B50[1..18]),
println(b50=B50.last),
nl.
b(M) = R =>
A = new_array(M-1),
bind_vars(A,0),
A[1] := 1,
R = [1, 1],
foreach(N in 2..M-1)
A[N] := A[1],
foreach(K in N..-1..2)
A[K-1] := A[K-1] + A[K],
end,
R := R ++ [A[1]]
end. |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #PicoLisp | PicoLisp | (de bell (N)
(make
(setq L (link (list 1)))
(do N
(setq L
(link
(make
(setq A (link (last L)))
(for B L
(setq A (link (+ A B))) ) ) ) ) ) ) )
(setq L (bell 51))
(for N 15
(tab (2 -2 -2) N ":" (get L N 1)) )
(prinl 50 ": " (get L 50 1))
(prinl)
(prinl "First ten rows:")
(for N 10
(println (get L N)) ) |
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 .
| #jq | jq | # Generate the first n Fibonacci numbers: 1, 1, ...
# Numerical accuracy is insufficient beyond about 1450.
def fibonacci(n):
# input: [f(i-2), f(i-1), countdown]
def fib: (.[0] + .[1]) as $sum
| if .[2] <= 0 then empty
elif .[2] == 1 then $sum
else $sum, ([ .[1], $sum, .[2] - 1 ] | fib)
end;
[1, 0, n] | fib ;
# is_prime is tailored to work with jq 1.4
def is_prime:
if . == 2 then true
else 2 < . and . % 2 == 1 and
. as $in
| (($in + 1) | sqrt) as $m
| (((($m - 1) / 2) | floor) + 1) as $max
| reduce range(1; $max) as $i
(true; if . then ($in % ((2 * $i) + 1)) > 0 else false end)
end ;
# primes in [m,n)
def primes(m;n):
range(m;n) | select(is_prime);
def runs:
reduce .[] as $item
( [];
if . == [] then [ [ $item, 1] ]
else .[length-1] as $last
| if $last[0] == $item
then (.[0:length-1] + [ [$item, $last[1] + 1] ] )
else . + [[$item, 1]]
end
end ) ;
# Inefficient but brief:
def histogram: sort | runs;
def benford_probability:
tonumber
| if . > 0 then ((1 + (1 /.)) | log) / (10|log)
else 0
end ;
# benford takes a stream and produces an array of [ "d", observed, expected ]
def benford(stream):
[stream | tostring | .[0:1] ] | histogram as $histogram
| reduce ($histogram | .[] | .[0]) as $digit
([]; . + [$digit, ($digit|benford_probability)] )
| map(select(type == "number")) as $probabilities
| ([ $histogram | .[] | .[1] ] | add) as $total
| reduce range(0; $histogram|length) as $i
([]; . + ([$histogram[$i] + [$total * $probabilities[$i]] ] ) ) ;
# given an array of [value, observed, expected] values,
# produce the χ² statistic
def chiSquared:
reduce .[] as $triple
(0;
if $triple[2] == 0 then .
else . + ($triple[1] as $o | $triple[2] as $e | ($o - $e) | (.*.)/$e)
end) ;
# truncate n places after the decimal point;
# return a string since it can readily be converted back to a number
def precision(n):
tostring as $s | $s | index(".")
| if . then $s[0:.+n+1] else $s end ;
# Right-justify but do not truncate
def rjustify(n):
length as $length | if n <= $length then . else " " * (n-$length) + . end;
# Attempt to align decimals so integer part is in a field of width n
def align(n):
index(".") as $ix
| if n < $ix then .
elif $ix then (.[0:$ix]|rjustify(n)) +.[$ix:]
else rjustify(n)
end ;
# given an array of [value, observed, expected] values,
# produce rows of the form: value observed expected
def print_rows(prec):
.[] | map( precision(prec)|align(5) + " ") | add ;
def report(heading; stream):
benford(stream) as $array
| heading,
" Digit Observed Expected",
( $array | print_rows(2) ),
"",
" χ² = \( $array | chiSquared | precision(4))",
""
;
def task:
report("First 100 fibonacci numbers:"; fibonacci( 100) ),
report("First 1000 fibonacci numbers:"; fibonacci(1000) ),
report("Primes less than 1000:"; primes(2;1000)),
report("Primes between 1000 and 10000:"; primes(1000;10000)),
report("Primes less than 100000:"; primes(2;100000))
;
task |
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 .
| #Julia | Julia | fib(n) = ([one(n) one(n) ; one(n) zero(n)]^n)[1,2]
ben(l) = [count(x->x==i, map(n->string(n)[1],l)) for i='1':'9']./length(l)
benford(l) = [Number[1:9;] ben(l) log10(1.+1./[1:9;])] |
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 +½.
| #Haskell | Haskell | import Data.Ratio
import System.Environment
main = getArgs >>= printM . defaultArg
where
defaultArg as =
if null as
then 60
else read (head as)
printM m =
mapM_ (putStrLn . printP) .
takeWhile ((<= m) . fst) . filter (\(_, b) -> b /= 0 % 1) . zip [0 ..] $
bernoullis
printP (i, r) =
"B(" ++ show i ++ ") = " ++ show (numerator r) ++ "/" ++ show (denominator r)
bernoullis = map head . iterate (ulli 1) . map berno $ enumFrom 0
where
berno i = 1 % (i + 1)
ulli _ [_] = []
ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs) |
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.
| #C.2B.2B | C++ |
template <class T> int binsearch(const T array[], int low, int high, T value) {
if (high < low) {
return -1;
}
auto mid = (low + high) / 2;
if (value < array[mid]) {
return binsearch(array, low, mid - 1, value);
} else if (value > array[mid]) {
return binsearch(array, mid + 1, high, value);
}
return mid;
}
#include <iostream>
int main()
{
int array[] = {2, 3, 5, 6, 8};
int result1 = binsearch(array, 0, sizeof(array)/sizeof(int), 4),
result2 = binsearch(array, 0, sizeof(array)/sizeof(int), 8);
if (result1 == -1) std::cout << "4 not found!" << std::endl;
else std::cout << "4 found at " << result1 << std::endl;
if (result2 == -1) std::cout << "8 not found!" << std::endl;
else std::cout << "8 found at " << result2 << std::endl;
return 0;
} |
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
| #Java | Java | import java.util.Random;
public class BestShuffle {
private final static Random rand = new Random();
public static void main(String[] args) {
String[] words = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"};
for (String w : words)
System.out.println(bestShuffle(w));
}
public static String bestShuffle(final String s1) {
char[] s2 = s1.toCharArray();
shuffle(s2);
for (int i = 0; i < s2.length; i++) {
if (s2[i] != s1.charAt(i))
continue;
for (int j = 0; j < s2.length; j++) {
if (s2[i] != s2[j] && s2[i] != s1.charAt(j) && s2[j] != s1.charAt(i)) {
char tmp = s2[i];
s2[i] = s2[j];
s2[j] = tmp;
break;
}
}
}
return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")";
}
public static void shuffle(char[] text) {
for (int i = text.length - 1; i > 0; i--) {
int r = rand.nextInt(i + 1);
char tmp = text[i];
text[i] = text[r];
text[r] = tmp;
}
}
private static int count(final String s1, final char[] s2) {
int count = 0;
for (int i = 0; i < s2.length; i++)
if (s1.charAt(i) == s2[i])
count++;
return count;
}
} |
http://rosettacode.org/wiki/Binary_strings | Binary strings | Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.
This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them.
If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language.
In particular the functions you need to create are:
String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
String assignment
String comparison
String cloning and copying
Check if a string is empty
Append a byte to a string
Extract a substring from a string
Replace every occurrence of a byte (or a string) in a string with another string
Join strings
Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
| #Perl | Perl | $s = undef;
say 'Nothing to see here' if ! defined $s; # 'Nothing to see here'
say $s = ''; # ''
say 'Empty string' if $s eq ''; # 'Empty string'
say $s = 'be'; # 'be'
say $t = $s; # 'be'
say 'Same' if $t eq $s; # 'Same'
say $t = $t .'e' # 'bee'
say $t .= 'keeper'; # 'beekeeper'
$t =~ s/ee/ook/; say $t; # 'bookkeeper'
say $u = substr $t, 2, 2; # 'ok'
say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK' |
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.
| #Batch_File | Batch File | @echo off
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
set /a n=%~1
set rtn=
for /l %%b in (0,1,31) do (
set /a "d=n&1, n>>=1"
set rtn=!d!!rtn!
)
for /f "tokens=* delims=0" %%a in ("!rtn!") do set rtn=%%a
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b |
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.
| #MAXScript | MAXScript | fn plot img coord steep col =
(
if steep then
(
swap coord[1] coord[2]
)
setPixels img coord col
)
fn drawLine img start end col =
(
local steep = (abs (end.y - start.y)) > (abs (end.x - start.x))
if steep then
(
swap start.x start.y
swap end.x end.y
)
if start.x > end.x then
(
swap start.x end.x
swap start.y end.y
)
local deltaX = end.x - start.x
local deltaY = abs (end.y - start.y)
local error = deltaX / 2.0
local yStep = -1
local y = start.y
if start.y < end.y then
(
yStep = 1
)
for x in start.x to end.x do
(
plot img [x, y] steep col
error -= deltaY
if error < 0 then
(
y += yStep
error += deltaX
)
)
img
)
myBitmap = bitmap 512 512 color:(color 0 0 0)
myBitmap = drawLine myBitmap [0, 511] [511, 0] #((color 255 255 255))
display myBitmap |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Ring | Ring |
x = True
y = False
see "x and y : " + (x and y) + nl
see "x or y : " + (x or y) + nl
see "not x : " + (not x) + nl
|
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Ruby | Ruby |
fn main() {
// Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
// Expressions inside `if` and `while` statements must result in type `bool`. There is no
// automatic conversion to the boolean type.
let true_value = true;
if true_value {
println!("foo is {}.", true_value);
}
let false_value = false;
if !false_value {
println!("bar is {}.", false_value);
}
}
|
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Rust | Rust |
fn main() {
// Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
// Expressions inside `if` and `while` statements must result in type `bool`. There is no
// automatic conversion to the boolean type.
let true_value = true;
if true_value {
println!("foo is {}.", true_value);
}
let false_value = false;
if !false_value {
println!("bar is {}.", false_value);
}
}
|
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)..
| #Pascal | Pascal | program BoxTheCompass(output);
function compasspoint(angle: real): string;
const
points: array [1..32] of string =
('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 '
);
var
index: integer;
begin
index := round (angle / 11.25);
index := index mod 32 + 1;
compasspoint := points[index];
end;
var
i: integer;
heading: real;
begin
for i := 0 to 32 do
begin
heading := i * 11.25;
case (i mod 3) of
1: heading := heading + 5.62;
2: heading := heading - 5.62;
end;
writeln((i mod 32) + 1:2, ' ', compasspoint(heading), ' ', heading:8:4);
end;
end. |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #HicEst | HicEst | i = IAND(k, j)
i = IOR( k, j)
i = IEOR(k, j)
i = NOT( k ) |
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.
| #LiveCode | LiveCode |
-- create an image container box at the center of the current stack window with default properties
create image "test"
-- programtically choose the paint bucket tool
choose bucket tool
-- LiveCode engine has built-in color keywords:
set the brushColor to "dark green"
-- programtically mouse click at the center of image container box to fill
click at the loc of image "test"
-- get the RGBA values of the first pixel in the image box
put byteToNum(byte 1 of the imageData of image "test") into tRed
put byteToNum(byte 2 of the imageData of image "test") into tGreen
put byteToNum(byte 3 of the imageData of image "test") into tBlue
put byteToNum(byte 4 of the imageData of image "test") into tAlpha
-- log message the info in the message box
put "First Pixel Color is Red:"& tRed &" Green:"& tGreen &" Blue:"& tBlue &" Transparency:"& tAlpha
-- just for fun replace the contents with RosettaCode logo
wait 2 seconds
set the filename of image "test" to "http://rosettacode.org/mw/title.png"
-- the next line is copy of the Write a PPM task:
export image "test" to file "~/Test.PPM" as paint -- paint format is one of PBM, PGM, or PPM
|
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.
| #Lua | Lua | function Allocate_Bitmap( width, height )
local bitmap = {}
for i = 1, width do
bitmap[i] = {}
for j = 1, height do
bitmap[i][j] = {}
end
end
return bitmap
end
function Fill_Bitmap( bitmap, color )
for i = 1, #bitmap do
for j = 1, #bitmap[1] do
bitmap[i][j] = color
end
end
end
function Get_Pixel( bitmap, x, y )
return bitmap[x][y]
end |
http://rosettacode.org/wiki/Bell_numbers | Bell numbers | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}.
So
B0 = 1 trivially. There is only one way to partition a set with zero elements. { }
B1 = 1 There is only one way to partition a set with one element. {a}
B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b}
B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}
and so on.
A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
Task
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence.
If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle.
See also
OEIS:A000110 Bell or exponential numbers
OEIS:A011971 Aitken's array | #Prolog | Prolog | bell(N, Bell):-
bell(N, Bell, [], _).
bell(0, [[1]|T], T, [1]):-!.
bell(N, Bell, B, Row):-
N1 is N - 1,
bell(N1, Bell, [Row|B], Last),
next_row(Row, Last).
next_row([Last|Bell], Bell1):-
last(Bell1, Last),
next_row1(Last, Bell, Bell1).
next_row1(_, [], []):-!.
next_row1(X, [Y|Rest], [B|Bell]):-
Y is X + B,
next_row1(Y, Rest, Bell).
print_bell_numbers(_, 0):-!.
print_bell_numbers([[Number|_]|Bell], N):-
writef('%w\n', [Number]),
N1 is N - 1,
print_bell_numbers(Bell, N1).
print_bell_rows(_, 0):-!.
print_bell_rows([Row|Rows], N):-
print_bell_row(Row),
N1 is N - 1,
print_bell_rows(Rows, N1).
print_bell_row([Number]):-
!,
writef('%w\n', [Number]).
print_bell_row([Number|Numbers]):-
writef('%w ', [Number]),
print_bell_row(Numbers).
main:-
bell(49, Bell),
writef('First 15 Bell numbers:\n'),
print_bell_numbers(Bell, 15),
last(Bell, [Number|_]),
writef('\n50th Bell number: %w\n', [Number]),
writef('\nFirst 10 rows of Bell triangle:\n'),
print_bell_rows(Bell, 10). |
http://rosettacode.org/wiki/Benford%27s_law | Benford's law |
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit
d
{\displaystyle d}
(
d
∈
{
1
,
…
,
9
}
{\displaystyle d\in \{1,\ldots ,9\}}
) occurs with probability
P
(
d
)
=
log
10
(
d
+
1
)
−
log
10
(
d
)
=
log
10
(
1
+
1
d
)
{\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)}
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
See also:
numberphile.com.
A starting page on Wolfram Mathworld is Benfords Law .
| #Kotlin | Kotlin | import java.math.BigInteger
interface NumberGenerator {
val numbers: Array<BigInteger>
}
class Benford(ng: NumberGenerator) {
override fun toString() = str
private val firstDigits = IntArray(9)
private val count = ng.numbers.size.toDouble()
private val str: String
init {
for (n in ng.numbers) {
firstDigits[n.toString().substring(0, 1).toInt() - 1]++
}
str = with(StringBuilder()) {
for (i in firstDigits.indices) {
append(i + 1).append('\t').append(firstDigits[i] / count)
append('\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\n')
}
toString()
}
}
}
object FibonacciGenerator : NumberGenerator {
override val numbers: Array<BigInteger> by lazy {
val fib = Array<BigInteger>(1000, { BigInteger.ONE })
for (i in 2 until fib.size)
fib[i] = fib[i - 2].add(fib[i - 1])
fib
}
}
fun main(a: Array<String>) = println(Benford(FibonacciGenerator)) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.