task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Binary_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.
| #Scheme | Scheme | (display (number->string 5 2)) (newline)
(display (number->string 50 2)) (newline)
(display (number->string 9000 2)) (newline) |
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.
| #Yabasic | Yabasic | sub floor(n)
return int(n + .5)
end sub
sub binarySearch(list(), value)
local low, high, mid
low = 1 : high = arraysize(list(), 1)
while(low <= high)
mid = floor((low + high) / 2)
if list(mid) > value then
high = mid - 1
elsif list(mid) < value then
low = mid + 1
else
return mid
end if
wend
return false
end sub
ITEMS = 10e6
dim list(ITEMS)
for n = 1 to ITEMS
list(n) = n
next n
print binarySearch(list(), 3)
print peek("millisrunning") |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 0 to 16 do
writeln(number radix 2);
end for;
end func; |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
Task
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
Recursive Pseudocode:
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
Iterative Pseudocode:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
Recursive Pseudocode:
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
Iterative Pseudocode:
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
mid = (low + high) / 2
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
mid = low + (high - low) / 2
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
mid = (low + high) >>> 1
where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
Related task
Guess the number/With Feedback (Player)
See also
wp:Binary search algorithm
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #z.2FArch_Assembler | z/Arch Assembler | * Binary search
BINSRCH LA R5,TABLE Begin of table
SR R2,R2 low = 0
LA R3,ENTRIES-1 high = N-1
LOOP CR R2,R3 while (low <= high)
JH NOTFOUND {
ARK R4,R2,R3 mid = low + high
SRL R4,1 mid = mid / 2
LA R1,1(R4) mid + 1
AHIK R0,R4,-1 mid - 1
MSFI R4,ENTRYL mid * length
AR R4,R5 Table[mid]
CLC 0(L'KEY,R4),SEARCH Compare
JE FOUND Equal? => Found
LOCRH R3,R0 High? => HIGH = MID-1
LOCRL R2,R1 Low? => LOW = MID+1
J LOOP } |
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.
| #SequenceL | SequenceL | main := toBinaryString([5, 50, 9000]);
toBinaryString(number(0)) :=
let
val := "1" when number mod 2 = 1 else "0";
in
toBinaryString(floor(number/2)) ++ val when floor(number/2) > 0
else
val; |
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.
| #zkl | zkl | fcn bsearch(list,value){ // list is sorted
fcn(list,value, low,high){
if (high < low) return(Void); // not found
mid:=(low + high) / 2;
if (list[mid] > value) return(self.fcn(list,value, low, mid-1));
if (list[mid] < value) return(self.fcn(list,value, mid+1, high));
return(mid); // found
}(list,value,0,list.len()-1);
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Sidef | Sidef | [5, 50, 9000].each { |n|
say n.as_bin;
} |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DATA 2,3,5,6,8,10,11,15,19,20
20 DIM t(10)
30 FOR i=1 TO 10
40 READ t(i)
50 NEXT i
60 LET value=4: GO SUB 100
70 LET value=8: GO SUB 100
80 LET value=20: GO SUB 100
90 STOP
100 REM Binary search
110 LET lo=1: LET hi=10
120 IF lo>hi THEN LET idx=0: GO TO 170
130 LET middle=INT ((hi+lo)/2)
140 IF value<t(middle) THEN LET hi=middle-1: GO TO 120
150 IF value>t(middle) THEN LET lo=middle+1: GO TO 120
160 LET idx=middle
170 PRINT "Value ";value;
180 IF idx=0 THEN PRINT " not found": RETURN
190 PRINT " found at index ";idx: RETURN
|
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.
| #Simula | Simula | BEGIN
PROCEDURE OUTINTBIN(N); INTEGER N;
BEGIN
IF N > 1 THEN OUTINTBIN(N//2);
OUTINT(MOD(N,2),1);
END OUTINTBIN;
INTEGER SAMPLE;
FOR SAMPLE := 5, 50, 9000 DO BEGIN
OUTINTBIN(SAMPLE);
OUTIMAGE;
END;
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.
| #SkookumScript | SkookumScript | println(5.binary)
println(50.binary)
println(9000.binary) |
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.
| #Smalltalk | Smalltalk | 5 printOn: Stdout radix:2
50 printOn: Stdout radix:2
9000 printOn: Stdout radix:2 |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Action.21 | Action! | BYTE FUNC FindIndex(BYTE b)
IF b>='A AND b<='Z THEN
RETURN (b-'A)
ELSEIF b>='a AND b<='z THEN
RETURN (b-'a+26)
ELSEIF b>='0 AND b<='9 THEN
RETURN (b-'0+52)
ELSEIF b='+ THEN
RETURN (62)
ELSEIF b='/ THEN
RETURN (63)
FI
RETURN (-1)
PROC PrintChar(CHAR c)
IF c=10 THEN
PutE()
ELSE
Put(c)
FI
RETURN
PROC Decode(CHAR ARRAY s)
BYTE i,b1,b2,b3,b4,i1,i2,i3,i4
CHAR c
IF s(0) MOD 4#0 THEN
PrintE("Invalid length of string!!!")
Break()
FI
i=1
WHILE i<=s(0)
DO
b1=s(i) i==+1
b2=s(i) i==+1
b3=s(i) i==+1
b4=s(i) i==+1
i1=FindIndex(b1)
i2=FindIndex(b2)
c=i1 LSH 2
c==%i2 RSH 4
PrintChar(c)
IF b3#'= THEN
i3=FindIndex(b3)
c=(i2&$0F) LSH 4
c==%i3 RSH 2
PrintChar(c)
IF b4#'= THEN
i4=FindIndex(b4)
c=(i3&$03) LSH 6
c==%i4
PrintChar(c)
FI
FI
OD
RETURN
PROC Test(CHAR ARRAY s)
PrintE("Encoded:")
PrintE(s)
PutE()
PrintE("Decoded:")
Decode(s)
PutE()
RETURN
PROC Main()
Test("VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo")
RETURN |
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.
| #SNOBOL4 | SNOBOL4 |
define('bin(n,r)') :(bin_end)
bin bin = le(n,0) r :s(return)
bin = bin(n / 2, REMDR(n,2) r) :(return)
bin_end
output = bin(5)
output = bin(50)
output = bin(9000)
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.
| #SNUSP | SNUSP |
/recurse\
$,binary!\@\>?!\@/<@\.#
! \=/ \=itoa=@@@+@+++++#
/<+>- \ div2
\?!#-?/+# mod2
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Ada | Ada | with Ada.Text_IO;
with AWS.Translator;
procedure Decode_AWS is
Input : constant String :=
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" &
"IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Result : constant String := AWS.Translator.Base64_Decode (Input);
begin
Ada.Text_IO.Put_Line (Input);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (Result);
end Decode_AWS; |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Arturo | Arturo | text: "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
print decode text |
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.
| #Standard_ML | Standard ML | print (Int.fmt StringCvt.BIN 5 ^ "\n");
print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n"); |
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.
| #Swift | Swift | for num in [5, 50, 9000] {
println(String(num, radix: 2))
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #BaCon | BaCon | data$ = "AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAE.......QAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE="
ico$ = B64DEC$(data$)
BSAVE ico$ TO "favicon.ico" SIZE LEN(ico$) |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Bash | Bash | #! /bin/bash
declare -a encodeTable=(
# + , - . / 0 1 2 3 4 5 6 7 8 9 :
62 -1 -1 -1 63 52 53 54 55 56 57 58 59 60 61 -1
# ; < = > ? @ A B C D E F G H I J
-1 -1 -1 -1 -1 -1 0 1 2 3 4 5 6 7 8 9
# K L M N O P Q R S T U V W X Y Z
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# [ \ ] ^ _ ` a b c d e f g h i j
-1 -1 -1 -1 -1 -1 26 27 28 29 30 31 32 33 34 35
# k l m n o p q r s t u v w x y z
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
)
function a2b6()
{
if [ $1 -lt 43 -o $1 -gt 122 ]
then
echo -1
else
echo ${encodeTable[$(($1-43))]}
fi
}
function flush() {
for (( k=2; k>=4-CNT; k-- ))
do
(( b8=BUF>>(k*8)&255 ))
printf -v HEX %x $b8
printf \\x$HEX
done
}
while read INPUT
do
for (( i=0; i<${#INPUT}; i++ ))
do
printf -v NUM %d "'${INPUT:$i:1}"
if (( NUM==61 ))
then
flush
exit 0
else
DEC=$( a2b6 $NUM )
if (( DEC>=0 ))
then
(( BUF|=DEC<<6*(3-CNT) ))
if (( ++CNT==4 ))
then
flush
(( CNT=0, BUF=0 ))
fi
fi
fi
done
done |
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.
| #Tcl | Tcl | proc num2bin num {
# Convert to _fixed width_ big-endian 32-bit binary
binary scan [binary format "I" $num] "B*" binval
# Strip useless leading zeros by reinterpreting as a big decimal integer
scan $binval "%lld"
} |
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.
| #TI-83_BASIC | TI-83 BASIC | PROGRAM:BINARY
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Input A
:0→N
:0→B
:While 2^(N+1)≤A
:N+1→N
:End
:While N≥0
:iPart(A/2^N)→C
:10^(N)*C+B→B
:If C=1
:Then
:A-2^N→A
:End
:N-1→N
:End
:Disp B |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #C | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned char ubyte;
const ubyte BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int findIndex(const ubyte val) {
if ('A' <= val && val <= 'Z') {
return val - 'A';
}
if ('a' <= val && val <= 'z') {
return val - 'a' + 26;
}
if ('0' <= val && val <= '9') {
return val - '0' + 52;
}
if (val == '+') {
return 62;
}
if (val == '/') {
return 63;
}
return -1;
}
int decode(const ubyte source[], ubyte sink[]) {
const size_t length = strlen(source);
const ubyte *it = source;
const ubyte *end = source + length;
int acc;
if (length % 4 != 0) {
return 1;
}
while (it != end) {
const ubyte b1 = *it++;
const ubyte b2 = *it++;
const ubyte b3 = *it++; // might be the first padding byte
const ubyte b4 = *it++; // might be the first or second padding byte
const int i1 = findIndex(b1);
const int i2 = findIndex(b2);
acc = i1 << 2; // six bits came from the first byte
acc |= i2 >> 4; // two bits came from the first byte
*sink++ = acc; // output the first byte
if (b3 != '=') {
const int i3 = findIndex(b3);
acc = (i2 & 0xF) << 4; // four bits came from the second byte
acc += i3 >> 2; // four bits came from the second byte
*sink++ = acc; // output the second byte
if (b4 != '=') {
const int i4 = findIndex(b4);
acc = (i3 & 0x3) << 6; // two bits came from the third byte
acc |= i4; // six bits came from the third byte
*sink++ = acc; // output the third byte
}
}
}
*sink = '\0'; // add the sigil for end of string
return 0;
}
int main() {
ubyte data[] = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
ubyte decoded[1024];
printf("%s\n\n", data);
decode(data, decoded);
printf("%s\n\n", decoded);
return 0;
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #uBasic.2F4tH | uBasic/4tH | Do
Input "Enter base (1<X<17): "; b
While (b < 2) + (b > 16)
Loop
Input "Enter number: "; n
s = (n < 0) ' save the sign
n = Abs(n) ' make number unsigned
For x = 0 Step 1 Until n = 0 ' calculate all the digits
@(x) = n % b
n = n / b
Next x
If s Then Print "-"; ' reapply the sign
For y = x - 1 To 0 Step -1 ' print all the digits
If @(y) > 9 Then ' take care of hexadecimal digits
Gosub @(y) * 10
Else
Print @(y); ' print "decimal" digits
Endif
Next y
Print ' finish the string
End
100 Print "A"; : Return ' print hexadecimal digit
110 Print "B"; : Return
120 Print "C"; : Return
130 Print "D"; : Return
140 Print "E"; : Return
150 Print "F"; : Return |
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.
| #UNIX_Shell | UNIX Shell | # Define a function to output binary digits
tobinary() {
# We use the bench calculator for our conversion
echo "obase=2;$1"|bc
}
# Call the function with each of our values
tobinary 5
tobinary 50 |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #C.23 | C# | using System;
using System.Text;
namespace Base64DecodeData {
class Program {
static void Main(string[] args) {
var data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Console.WriteLine(data);
Console.WriteLine();
var decoded = Encoding.ASCII.GetString(Convert.FromBase64String(data));
Console.WriteLine(decoded);
}
}
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
typedef unsigned char ubyte;
const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::vector<ubyte> encode(const std::vector<ubyte>& source) {
auto it = source.cbegin();
auto end = source.cend();
std::vector<ubyte> sink;
while (it != end) {
auto b1 = *it++;
int acc;
sink.push_back(BASE64[b1 >> 2]); // first output (first six bits from b1)
acc = (b1 & 0x3) << 4; // last two bits from b1
if (it != end) {
auto b2 = *it++;
acc |= (b2 >> 4); // first four bits from b2
sink.push_back(BASE64[acc]); // second output
acc = (b2 & 0xF) << 2; // last four bits from b2
if (it != end) {
auto b3 = *it++;
acc |= (b3 >> 6); // first two bits from b3
sink.push_back(BASE64[acc]); // third output
sink.push_back(BASE64[b3 & 0x3F]); // fouth output (final six bits from b3)
} else {
sink.push_back(BASE64[acc]); // third output
sink.push_back('='); // fourth output (1 byte padding)
}
} else {
sink.push_back(BASE64[acc]); // second output
sink.push_back('='); // third output (first padding byte)
sink.push_back('='); // fourth output (second padding byte)
}
}
return sink;
}
int findIndex(ubyte val) {
if ('A' <= val && val <= 'Z') {
return val - 'A';
}
if ('a' <= val && val <= 'z') {
return val - 'a' + 26;
}
if ('0' <= val && val <= '9') {
return val - '0' + 52;
}
if ('+' == val) {
return 62;
}
if ('/' == val) {
return 63;
}
return -1;
}
std::vector<ubyte> decode(const std::vector<ubyte>& source) {
if (source.size() % 4 != 0) {
throw new std::runtime_error("Error in size to the decode method");
}
auto it = source.cbegin();
auto end = source.cend();
std::vector<ubyte> sink;
while (it != end) {
auto b1 = *it++;
auto b2 = *it++;
auto b3 = *it++; // might be first padding byte
auto b4 = *it++; // might be first or second padding byte
auto i1 = findIndex(b1);
auto i2 = findIndex(b2);
auto acc = i1 << 2; // six bits came from the first byte
acc |= i2 >> 4; // two bits came from the first byte
sink.push_back(acc); // output the first byte
if (b3 != '=') {
auto i3 = findIndex(b3);
acc = (i2 & 0xF) << 4; // four bits came from the second byte
acc |= i3 >> 2; // four bits came from the second byte
sink.push_back(acc); // output the second byte
if (b4 != '=') {
auto i4 = findIndex(b4);
acc = (i3 & 0x3) << 6; // two bits came from the third byte
acc |= i4; // six bits came from the third byte
sink.push_back(acc); // output the third byte
}
}
}
return sink;
}
int main() {
using namespace std;
string data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
vector<ubyte> datav{ begin(data), end(data) };
cout << data << "\n\n" << decode(datav).data() << endl;
return 0;
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #VBA | VBA |
Option Explicit
Sub Main_Dec2bin()
Dim Nb As Long
Nb = 5
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
Nb = 50
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
Nb = 9000
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb)
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb)
End Sub
Function DecToBin(ByVal Number As Long) As String
Dim strTemp As String
Do While Number > 1
strTemp = Number - 2 * (Number \ 2) & strTemp
Number = Number \ 2
Loop
DecToBin = Number & strTemp
End Function
Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String
If Number > 511 Then
DecToBin2 = "Error : Number is too large ! (Number must be < 511)"
ElseIf Number < -512 Then
DecToBin2 = "Error : Number is too small ! (Number must be > -512)"
Else
If Places = 0 Then
DecToBin2 = WorksheetFunction.Dec2Bin(Number)
Else
DecToBin2 = WorksheetFunction.Dec2Bin(Number, Places)
End If
End If
End Function
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>Write $System.Encryption.Base64Decode("VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")
To err is human, but to really foul things up you need a computer.
-- Paul R. Ehrlich
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Clojure | Clojure | (defn decode [str]
(String. (.decode (java.util.Base64/getDecoder) str)))
(decode "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")
|
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.
| #Vedit_macro_language | Vedit macro language | repeat (ALL) {
#10 = Get_Num("Give a numeric value, -1 to end: ", STATLINE)
if (#10 < 0) { break }
Call("BINARY")
Update()
}
return
:BINARY:
do {
Num_Ins(#10 & 1, LEFT+NOCR)
#10 = #10 >> 1
Char(-1)
} while (#10 > 0)
EOL
Ins_Newline
Return |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Common_Lisp | Common Lisp | (eval-when (:load-toplevel :compile-toplevel :execute)
(ql:quickload "cl-base64"))
;; * The package definition
(defpackage :base64-decode
(:use :common-lisp :cl-base64))
(in-package :base64-decode)
;; * The encoded data
(defvar *base64-data*
"AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZGADO0c8AODs5AK2wrgBzdnQA6+7sAPz//QAAAwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE="
"See BASE64-ENCODE for the origin of this
data. http://rosettacode.org/wiki/Base64_encode_data")
;; * The function
(defun base64-decode (&optional (data *base64-data*) (file #p"favicon-2.ico"))
"Returns the original FILE BASE64 encoded in DATA."
(with-open-file (stream file :direction :output :element-type 'unsigned-byte
:if-exists :supersede :if-does-not-exist :create)
(let* ((array (base64-string-to-usb8-array data))
(len (length array)))
(write-sequence array stream)
(format t "Wrote ~D bytes in file ~A~%" len file)))) |
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.
| #Vim_Script | Vim Script | function Num2Bin(n)
let n = a:n
let s = ""
if n == 0
let s = "0"
else
while n
if n % 2 == 0
let s = "0" . s
else
let s = "1" . s
endif
let n = n / 2
endwhile
endif
return s
endfunction
echo Num2Bin(5)
echo Num2Bin(50)
echo Num2Bin(9000) |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Crystal | Crystal | require "base64"
encoded_string = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
decoded_string = Base64.decode_string(encoded_string)
puts decoded_string |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #D | D | import std.base64;
import std.stdio;
void main() {
auto data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
writeln(data);
writeln;
auto decoded = cast(char[])Base64.decode(data);
writeln(decoded);
} |
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.
| #Visual_Basic | Visual Basic |
Public Function Bin(ByVal l As Long) As String
Dim i As Long
If l Then
If l And &H80000000 Then 'negative number
Bin = "1" & String$(31, "0")
l = l And (Not &H80000000)
For i = 0 To 30
If l And (2& ^ i) Then
Mid$(Bin, Len(Bin) - i) = "1"
End If
Next i
Else 'positive number
Do While l
If l Mod 2 Then
Bin = "1" & Bin
Else
Bin = "0" & Bin
End If
l = l \ 2
Loop
End If
Else
Bin = "0" 'zero
End If
End Function
'testing:
Public Sub Main()
Debug.Print Bin(5)
Debug.Print Bin(50)
Debug.Print Bin(9000)
End Sub
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Dart | Dart | import 'dart:convert';
void main() {
var encoded = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
var decoded = utf8.decode(base64.decode(encoded));
print(decoded);
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Delphi | Delphi | program Base64Decoder;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.NetEncoding;
const
Src = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=';
begin
WriteLn(Format('Source string: ' + sLineBreak + '"%s"', [Src]));
WriteLn(Format('Decoded string: ' + sLineBreak + '"%s"', [TNetEncoding.Base64.Decode(Src)]));
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main
For Each number In {5, 50, 9000}
Console.WriteLine(Convert.ToString(number, 2))
Next
End Sub
End Module |
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.
| #Visual_FoxPro | Visual FoxPro |
*!* Binary Digits
CLEAR
k = CAST(5 As I)
? NToBin(k)
k = CAST(50 As I)
? NToBin(k)
k = CAST(9000 As I)
? NToBin(k)
FUNCTION NTOBin(n As Integer) As String
LOCAL i As Integer, b As String, v As Integer
b = ""
v = HiBit(n)
FOR i = 0 TO v
b = IIF(BITTEST(n, i), "1", "0") + b
ENDFOR
RETURN b
ENDFUNC
FUNCTION HiBit(n As Double) As Integer
*!* Find the highest power of 2 in n
LOCAL v As Double
v = LOG(n)/LOG(2)
RETURN FLOOR(v)
ENDFUNC
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #F.23 | F# |
open System
open System.IO
let encoded = "AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZGADO0c8AODs5AK2wrgBzdnQA6+7sAPz//QAAAwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE="
let decoded = Convert.FromBase64String encoded
File.WriteAllBytes("favicon.ico", decoded)
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Factor | Factor | USING: base64 io strings ;
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"
base64> >string print |
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.
| #Whitespace | Whitespace | |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Forth | Forth | variable bitsbuff
: char>6bits ( c -- u )
dup 43 = if drop 62 exit then ( + case )
dup 47 = if drop 63 exit then ( / case )
dup 48 58 within if 48 - 52 + exit then ( 0-9 case )
dup 65 91 within if 65 - exit then ( A-Z case )
dup 97 123 within if 97 - 26 + exit then ( a-z case )
drop 0 ( padding )
;
: 6bitsin ( v -- ) bitsbuff @ 6 lshift + bitsbuff ! ;
: 4charsin ( addr -- addr+4 )
$0 bitsbuff !
dup 4 + dup rot
do I c@ char>6bits 6bitsin loop ;
: 3bytes, ( -- )
bitsbuff @ 16 rshift $ff and c,
bitsbuff @ 8 rshift $ff and c,
bitsbuff @ $ff and c, ;
: b64dec ( addr1 n1 -- addr2 n2 )
here rot rot ( addr2 addr1 n1 )
4 / ( addr2 addr1 n1/4 )
0 do
4charsin 3bytes,
loop ( addr2 addr1+4x )
( get back for padding )
1 - dup c@ 61 = if 1 else 0 then swap ( addr2 0|1 addr1+4x-1 )
1 - c@ 61 = if 1 else 0 then + ( addr2 0|1|2 )
swap ( 0|1|2 addr2 )
dup here swap - ( 0|1|2 addr2 n' )
rot - ( addr2 n2 )
;
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #FreeBASIC | FreeBASIC | Dim Shared As String B64
B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
"abcdefghijklmnopqrstuvwxyz" & _
"0123456789+/"
Function MIMEDecode(s As String ) As Integer
If Len(s) Then
MIMEdecode = Instr(B64,s) - 1
Else
MIMEdecode = -1
End If
End Function
Function Decode64(s As String) As String
Dim As Integer w1, w2, w3, w4
Dim As String mD
For n As Integer = 1 To Len(s) Step 4
w1 = MIMEdecode(Mid(s,n+0,1))
w2 = MIMEdecode(Mid(s,n+1,1))
w3 = MIMEdecode(Mid(s,n+2,1))
w4 = MIMEdecode(Mid(s,n+3,1))
If w2 >-1 Then mD+= Chr(((w1* 4 + Int(w2/16)) And 255))
If w3 >-1 Then mD+= Chr(((w2*16 + Int(w3/ 4)) And 255))
If w4 >-1 Then mD+= Chr(((w3*64 + w4 ) And 255))
Next n
Return mD
End Function
Dim As String msg64 = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" & _
"IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
Print msg64
Print: Print(Decode64(msg64))
Sleep |
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.
| #Vlang | Vlang | fn main() {
for i in 0..16 {
println("${i:b}")
}
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Go | Go | package main
import (
"encoding/base64"
"fmt"
)
func main() {
msg := "Rosetta Code Base64 decode data task"
fmt.Println("Original :", msg)
encoded := base64.StdEncoding.EncodeToString([]byte(msg))
fmt.Println("\nEncoded :", encoded)
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nDecoded :", string(decoded))
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Groovy | Groovy | import java.nio.charset.StandardCharsets
class Decode {
static void main(String[] args) {
String data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
Base64.Decoder decoder = Base64.getDecoder()
byte[] decoded = decoder.decode(data)
String decodedStr = new String(decoded, StandardCharsets.UTF_8)
System.out.println(decodedStr)
}
} |
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.
| #VTL-2 | VTL-2 | 10 N=5
20 #=100
30 N=50
40 #=100
50 N=9000
100 ;=!
110 I=18
120 I=I-1
130 N=N/2
140 :I)=%
150 #=0<N*120
160 ?=:I)
170 I=I+1
180 #=I<18*160
190 ?=""
200 #=; |
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.
| #Wortel | Wortel | \.toString 2
; the following function also casts the string to a number
^(@+ \.toString 2) |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Haskell | Haskell | --Decodes Base64 to ASCII
import qualified Data.Map.Strict as Map (Map, lookup, fromList)
import Data.Maybe (fromJust, listToMaybe, mapMaybe)
import Numeric (readInt, showIntAtBase)
import Data.Char (chr, digitToInt)
import Data.List.Split (chunksOf)
byteToASCII :: String -> String
byteToASCII = map chr . decoder
--generates list of bytes (represented by Int)
decoder :: String -> [Int]
decoder =
map readBin .
takeWhile (\x -> length x == 8) .
chunksOf 8 . concatMap toBin . mapMaybe (`Map.lookup` table) . filter (/= '=')
--turns decimal into a list of char that represents a binary number
toBin :: Int -> String
toBin n = leftPad $ showIntAtBase 2 ("01" !!) n ""
--this adds all the zeros to the left that showIntAtBase omitted
leftPad :: String -> String
leftPad a = replicate (6 - length a) '0' ++ a
--turns list of '0' and '1' into list of 0 and 1
readBin :: String -> Int
readBin = fromJust . fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
--lookup list for the sextets
table :: Map.Map Char Int
table =
Map.fromList $
zip "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" [0 ..]
main :: IO ()
main =
putStrLn $
byteToASCII
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCi0tIFBhdWwgUi4gRWhybGljaA==" |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #11l | 11l | F qmean(num)
R sqrt(sum(num.map(n -> n * n)) / Float(num.len))
print(qmean(1..10)) |
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.
| #Wren | Wren | import "/fmt" for Fmt
System.print("Converting to binary:")
for (i in [5, 50, 9000]) Fmt.print("$d -> $b", i, i) |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Haxe | Haxe | class Main {
static function main() {
var data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" +
"IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Sys.println('$data\n');
var decoded = haxe.crypto.Base64.decode(data);
Sys.println(decoded);
}
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #J | J | require'convert/misc/base64'
frombase64 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='
To err is human, but to really foul things up you need a computer.
-- Paul R. Ehrlich |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
BYTE FUNC Equal(REAL POINTER a,b)
BYTE ARRAY x,y
x=a y=b
IF x(0)=y(0) AND x(1)=y(1) AND x(2)=y(2) THEN
RETURN (1)
FI
RETURN (0)
PROC Sqrt(REAL POINTER a,b)
REAL z,half
IntToReal(0,z)
ValR("0.5",half)
IF Equal(a,z) THEN
RealAssign(z,b)
ELSE
Power(a,half,b)
FI
RETURN
PROC Main()
BYTE i
REAL x,x2,sum,tmp
IntToReal(0,sum)
FOR i=1 TO 10
DO
IntToReal(i,x)
RealMult(x,x,x2)
RealAdd(sum,x2,tmp)
RealAssign(tmp,sum)
OD
IntToReal(10,x)
RealDiv(sum,x,tmp)
Sqrt(tmp,x)
Put(125) PutE() ;clear screen
Print("RMS of 1..10 is ")
PrintRE(x)
RETURN |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ada | Ada | with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
procedure calcrms is
type float_arr is array(1..10) of Float;
function rms(nums : float_arr) return Float is
sum : Float := 0.0;
begin
for p in nums'Range loop
sum := sum + nums(p)**2;
end loop;
return sqrt(sum/Float(nums'Length));
end rms;
list : float_arr;
begin
list := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);
put( rms(list) , Exp=>0);
end calcrms; |
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.
| #X86_Assembly | X86 Assembly | .model tiny
.code
.486
org 100h
start: mov ax, 5
call binout
call crlf
mov ax, 50
call binout
call crlf
mov ax, 9000
call binout
crlf: mov al, 0Dh ;new line
int 29h
mov al, 0Ah
int 29h
ret
binout: push ax
shr ax, 1
je bo10
call binout
bo10: pop ax
and al, 01h
or al, '0'
int 29h ;display character
ret
end start |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Java | Java | import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Decode {
public static void main(String[] args) {
String data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Base64.Decoder decoder = Base64.getDecoder();
byte[] decoded = decoder.decode(data);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
System.out.println(decodedStr);
}
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #JavaScript | JavaScript | // define base64 data; in this case the data is the string: "Hello, world!"
const base64 = 'SGVsbG8sIHdvcmxkIQ==';
// atob is a built-in function.
console.log(atob(base64)); |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_68 | ALGOL 68 | # Define the rms PROCedure & ABS OPerators for LONG... REAL #
MODE RMSFIELD = #LONG...# REAL;
PROC (RMSFIELD)RMSFIELD rms field sqrt = #long...# sqrt;
INT rms field width = #long...# real width;
PROC crude rms = ([]RMSFIELD v)RMSFIELD: (
RMSFIELD sum := 0;
FOR i FROM LWB v TO UPB v DO sum +:= v[i]**2 OD;
rms field sqrt(sum / (UPB v - LWB v + 1))
);
PROC rms = ([]RMSFIELD v)RMSFIELD: (
# round off error accumulated at standard precision #
RMSFIELD sum := 0, round off error:= 0;
FOR i FROM LWB v TO UPB v DO
RMSFIELD org = sum, prod = v[i]**2;
sum +:= prod;
round off error +:= sum - org - prod
OD;
rms field sqrt((sum - round off error)/(UPB v - LWB v + 1))
);
main: (
[]RMSFIELD one to ten = (1,2,3,4,5,6,7,8,9,10);
print(("crude rms(one to ten): ", crude rms(one to ten), new line));
print(("rms(one to ten): ", rms(one to ten), new line))
) |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic code declarations
proc BinOut(N); \Output N in binary
int N;
int R;
[R:= N&1;
N:= N>>1;
if N then BinOut(N);
ChOut(0, R+^0);
];
int I;
[I:= 0;
repeat BinOut(I); CrLf(0);
I:= I+1;
until KeyHit or I=0;
] |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Yabasic | Yabasic | dim a(3)
a(0) = 5
a(1) = 50
a(2) = 9000
for i = 0 to 2
print a(i) using "####", " -> ", bin$(a(i))
next i
end |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #jq | jq | jq -rR base64d
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Jsish | Jsish | /* Base64 decode, in Jsish */
var data = exec('jsish base64.jsi', {retAll:true}).data; // or use File.read('stdin');
var icon = Util.base64(data, true);
File.write('rosetta-favicon.ico', icon); |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL-M | ALGOL-M |
BEGIN
DECIMAL FUNCTION SQRT(X);
DECIMAL X;
BEGIN
DECIMAL R1, R2, TOL;
TOL := .00001; % reasonable for most purposes %
IF X >= 1.0 THEN
BEGIN
R1 := X;
R2 := 1.0;
END
ELSE
BEGIN
R1 := 1.0;
R2 := X;
END;
WHILE (R1-R2) > TOL DO
BEGIN
R1 := (R1+R2) / 2.0;
R2 := X / R1;
END;
SQRT := R1;
END;
COMMENT - MAIN PROGRAM BEGINS HERE;
DECIMAL N, SQSUM, SQMEAN;
SQSUM := 0.0;
FOR N := 1.0 STEP 1.0 UNTIL 10.0 DO
SQSUM := SQSUM + (N * N);
SQMEAN := SQSUM / (N - 1.0);
WRITE("RMS OF WHOLE NUMBERS 1.0 THROUGH 10.0 =", SQRT(SQMEAN));
END |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_W | ALGOL W | begin
% computes the root-mean-square of an array of numbers with %
% the specified lower bound (lb) and upper bound (ub) %
real procedure rms( real array numbers ( * )
; integer value lb
; integer value ub
) ;
begin
real sum;
sum := 0;
for i := lb until ub do sum := sum + ( numbers(i) * numbers(i) );
sqrt( sum / ( ( ub - lb ) + 1 ) )
end rms ;
% test the rms procedure with the numbers 1 to 10 %
real array testNumbers( 1 :: 10 );
for i := 1 until 10 do testNumbers(i) := i;
r_format := "A"; r_w := 10; r_d := 4; % set fixed point output %
write( "rms of 1 .. 10: ", rms( testNumbers, 1, 10 ) );
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.
| #Z80_Assembly | Z80 Assembly | org &8000
PrintChar equ &BB5A ;syscall - prints accumulator to Amstrad CPC's screen
main:
ld hl,TestData0
call PrintBinary_NoLeadingZeroes
ld hl,TestData1
call PrintBinary_NoLeadingZeroes
ld hl,TestData2
call PrintBinary_NoLeadingZeroes
ret
TestData0:
byte 5,255
TestData1:
byte 5,0,255
TestData2:
byte 9,0,0,0,255
temp:
byte 0
;temp storage for the accumulator
; we can't use the stack to preserve A since that would also preserve the flags.
PrintBinary_NoLeadingZeroes:
;setup:
ld bc,&8000 ;B is the revolving bit mask, C is the "have we seen a zero yet" flag
NextDigit:
ld a,(hl)
inc hl
cp 255
jp z,Terminated
ld (temp),a
NextBit:
ld a,(temp)
and b
jr z,PrintZero
; else, print one
ld a,'1' ;&31
call &BB5A
set 0,b ;bit 0 of B is now 1, so we can print zeroes now.
jr Predicate
PrintZero:
ld a,b
or a
jr z,Predicate ;if we haven't seen a zero yet, don't print a zero.
ld a,'0' ;&30
call &BB5A
Predicate:
rrc b
;rotate the mask right by one. If it sets the carry,
; it's back at the start, and we need to load the next byte.
jr nc,NextBit
jr NextDigit ;back to top
Terminated:
ld a,13
call &BB5A
ld a,10
jp &BB5A ;its ret will return for us. |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Julia | Julia | using Base64
io = IOBuffer()
iob64_decode = Base64DecodePipe(io)
write(io, "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo")
seekstart(io)
println(String(read(iob64_decode)))
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Kotlin | Kotlin | import java.util.Base64
fun main() {
val data =
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
val decoder = Base64.getDecoder()
val decoded = decoder.decode(data)
val decodedStr = String(decoded, Charsets.UTF_8)
println(decodedStr)
} |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #APL | APL | rms←{((+/⍵*2)÷⍴⍵)*0.5}
x←⍳10
rms x
6.204836823 |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AppleScript | AppleScript | -- rootMeanSquare :: [Num] -> Real
on rootMeanSquare(xs)
script
on |λ|(a, x)
a + x * x
end |λ|
end script
(foldl(result, 0, xs) / (length of xs)) ^ (1 / 2)
end rootMeanSquare
-- TEST -----------------------------------------------------------------------
on run
rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
-- > 6.204836822995
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
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.
| #zkl | zkl | (9000).toString(2) |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET n=5: GO SUB 1000: PRINT s$
20 LET n=50: GO SUB 1000: PRINT s$
30 LET n=9000: GO SUB 1000: PRINT s$
999 STOP
1000 REM convert to binary
1010 LET t=n: REM temporary variable
1020 LET s$="": REM this will contain our binary digits
1030 LET sf=0: REM output has not started yet
1040 FOR l=126 TO 0 STEP -1
1050 LET d$="0": REM assume next digit is zero
1060 IF t>=(2^l) THEN LET d$="1": LET t=t-(2^l): LET sf=1
1070 IF (sf <> 0) THEN LET s$=s$+d$
1080 NEXT l
1090 RETURN |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Lua | Lua | -- Start taken from https://stackoverflow.com/a/35303321
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding
-- decoding
function dec(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end
-- end of copy
local data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"
print(data)
print()
local decoded = dec(data)
print(decoded) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Arturo | Arturo | rootMeanSquare: function [arr]->
sqrt (sum map arr 'i -> i^2) // size arr
print rootMeanSquare 1..10 |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Astro | Astro | sqrt(mean(x²)) |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ImportString[
"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo",
"Base64"
] |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Nim | Nim | import base64
const Source = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
echo Source.decode() |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AutoHotkey | AutoHotkey | MsgBox, % RMS(1, 10)
;---------------------------------------------------------------------------
RMS(a, b) { ; Root Mean Square of integers a through b
;---------------------------------------------------------------------------
n := b - a + 1
Loop, %n%
Sum += (a + A_Index - 1) ** 2
Return, Sqrt(Sum / n)
} |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AWK | AWK | #!/usr/bin/awk -f
# computes RMS of the 1st column of a data file
{
x = $1; # value of 1st column
S += x*x;
N++;
}
END {
print "RMS: ",sqrt(S/N);
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #OCaml | OCaml | # let plain = Base64.decode_exn enc;;
val plain : string =
"\000\000\001\000\002\000\016\016\000\000\000\000\000\000h\005\000\000&\000"... (* string length 3638; truncated *)
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Ol | Ol |
(define base64-codes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(define kernel (alist->ff (map cons (string->bytes base64-codes) (iota (string-length base64-codes)))))
; returns n bits from input binary stream
(define (bits n hold)
(let loop ((hold hold))
(vector-apply hold (lambda (v i l)
(cond
((null? l)
(values (>> v (- i n)) #false))
((pair? l)
(if (not (less? i n))
(values (>> v (- i n)) (vector (band v (- (<< 1 (- i n)) 1)) (- i n) l))
(loop (vector
(bor (<< v 6) (kernel (car l) 0))
(+ i 6)
(unless (eq? (car l) "=") (cdr l))))))
(else
(loop (vector v i (l)))))))))
; decoder.
(define (decode str)
(print "decoding string '" str "':")
(let loop ((hold [0 0 (str-iter str)]))
(let*((bit hold (bits 8 hold)))
(unless (zero? bit) (display (string bit)))
(when hold
(loop hold))))
(print)(print))
; TESTING
(decode "SGVsbG8sIExpc3Ah")
(decode "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")
(decode "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=")
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #BASIC | BASIC | DIM i(1 TO 10) AS DOUBLE, L0 AS LONG
FOR L0 = 1 TO 10
i(L0) = L0
NEXT
PRINT STR$(rms#(i()))
FUNCTION rms# (what() AS DOUBLE)
DIM L0 AS LONG, tmp AS DOUBLE, rt AS DOUBLE
FOR L0 = LBOUND(what) TO UBOUND(what)
rt = rt + (what(L0) ^ 2)
NEXT
tmp = UBOUND(what) - LBOUND(what) + 1
rms# = SQR(rt / tmp)
END FUNCTION |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Perl | Perl | sub decode_base64 {
my($d) = @_;
$d =~ tr!A-Za-z0-9+/!!cd;
$d =~ s/=+$//;
$d =~ tr!A-Za-z0-9+/! -_!;
my $r = '';
while( $d =~ /(.{1,60})/gs ){
my $len = chr(32 + length($1)*3/4);
$r .= unpack("u", $len . $1 );
}
$r;
}
$data = <<EOD;
J1R3YXMgYnJpbGxpZywgYW5kIHRoZSBzbGl0aHkgdG92ZXMKRGlkIGd5cmUgYW5kIGdpbWJsZSBp
biB0aGUgd2FiZToKQWxsIG1pbXN5IHdlcmUgdGhlIGJvcm9nb3ZlcywKQW5kIHRoZSBtb21lIHJh
dGhzIG91dGdyYWJlLgo=
EOD
print decode_base64($data) . "\n"; |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Phix | Phix | with javascript_semantics
include builtins\base64.e
string s = "Rosetta Code Base64 decode data task"
string e = encode_base64(s)
?e
?decode_base64(e)
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #BQN | BQN | RMS ← √+´∘ט÷≠
RMS 1+↕10 |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C | C | #include <stdio.h>
#include <math.h>
double rms(double *v, int n)
{
int i;
double sum = 0.0;
for(i = 0; i < n; i++)
sum += v[i] * v[i];
return sqrt(sum / n);
}
int main(void)
{
double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
printf("%f\n", rms(v, sizeof(v)/sizeof(double)));
return 0;
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #PHP | PHP | $encoded = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw' .
'IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=';
echo
$encoded, PHP_EOL,
base64_decode($encoded), PHP_EOL; |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #PicoLisp | PicoLisp | (setq *Char64
`'(chop
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ) )
(de decode64 (S)
(let S (chop S)
(pack
(make
(while S
(let
(A (dec (index (++ S) *Char64))
B (dec (index (++ S) *Char64))
C (dec (index (++ S) *Char64))
D (dec (index (++ S) *Char64)) )
(link
(char (| (>> -2 A) (>> 4 B))) )
(and
C
(link
(char
(| (>> -4 (& B 15)) (>> 2 C)) ) )
D
(link
(char (| (>> -6 (& C 3)) D)) ) ) ) ) ) ) ) )
(prinl (decode64 "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo")) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.23 | C# | using System;
namespace rms
{
class Program
{
static void Main(string[] args)
{
int[] x = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine(rootMeanSquare(x));
}
private static double rootMeanSquare(int[] x)
{
double sum = 0;
for (int i = 0; i < x.Length; i++)
{
sum += (x[i]*x[i]);
}
return Math.Sqrt(sum / x.Length);
}
}
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Pike | Pike |
string icon = Protocols.HTTP.get_url_data("http://rosettacode.org/favicon.ico");
string encoded = MIME.encode_base64(icon);
Stdio.write_file("favicon.ico", MIME.decode_base64(encoded));
|
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Prolog | Prolog | ?- Encoded = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=',
base64(Plain, Encoded).
Plain = 'To err is human, but to really foul things up you need a computer.\n -- Paul R. Ehrlich'.
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
int main( ) {
std::vector<int> numbers ;
for ( int i = 1 ; i < 11 ; i++ )
numbers.push_back( i ) ;
double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.size() ) );
std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ;
return 0 ;
} |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #PureBasic | PureBasic | b64cd$ = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" +
"IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
*p_buf = AllocateMemory(1024)
Base64Decoder(b64cd$, *p_buf, 1024)
OpenConsole("") : PrintN(PeekS(*p_buf, -1, #PB_UTF8))
Input() |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #Python | Python |
import base64
data = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='
print(base64.b64decode(data).decode('utf-8'))
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Clojure | Clojure |
(defn rms [xs]
(Math/sqrt (/ (reduce + (map #(* % %) xs))
(count xs))))
(println (rms (range 1 11))) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. QUADRATIC-MEAN-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 QUADRATIC-MEAN-VARS.
05 N PIC 99 VALUE 0.
05 N-SQUARED PIC 999.
05 RUNNING-TOTAL PIC 999 VALUE 0.
05 MEAN-OF-SQUARES PIC 99V9(16).
05 QUADRATIC-MEAN PIC 9V9(15).
PROCEDURE DIVISION.
CONTROL-PARAGRAPH.
PERFORM MULTIPLICATION-PARAGRAPH 10 TIMES.
DIVIDE RUNNING-TOTAL BY 10 GIVING MEAN-OF-SQUARES.
COMPUTE QUADRATIC-MEAN = FUNCTION SQRT(MEAN-OF-SQUARES).
DISPLAY QUADRATIC-MEAN UPON CONSOLE.
STOP RUN.
MULTIPLICATION-PARAGRAPH.
ADD 1 TO N.
MULTIPLY N BY N GIVING N-SQUARED.
ADD N-SQUARED TO RUNNING-TOTAL. |
http://rosettacode.org/wiki/Base64_decode_data | Base64 decode data | See Base64 encode data.
Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| #QB64 | QB64 | Option _Explicit
Dim As String udata, decoded
udata = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"
decoded = decode(udata)
Print udata
Print decoded
Function findIndex& (value As _Unsigned _Byte)
If Asc("A") <= value And value <= Asc("Z") Then
findIndex = value - Asc("A")
Exit Function
End If
If Asc("a") <= value And value <= Asc("z") Then
findIndex = value - Asc("a") + 26
Exit Function
End If
If Asc("0") <= value And value <= Asc("9") Then
findIndex = value - Asc("0") + 52
Exit Function
End If
If value = Asc("+") Then
findIndex = 62
Exit Function
End If
If value = Asc("/") Then
findIndex = 63
Exit Function
End If
findIndex = -1
End Function
Function encode$ (source As String)
Dim As String Base64: Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim As _Unsigned _Integer64 length: length = Len(source)
Dim As _Unsigned _Integer64 it, strend
Dim As Long acc
Dim As String sink
strend = length
While it <> strend
Dim As _Unsigned _Byte b1, b2, b3, b4
it = it + 1
b1 = Asc(Mid$(source, it, 1))
sink = sink + Mid$(Base64, _SHR(b1, 2), 1)
acc = _SHL(b1 And &H3, 4)
If it <> strend Then
it = it + 1
b2 = Asc(Mid$(source, it, 1))
acc = acc Or _SHR(b2, 4)
sink = sink + Mid$(Base64, acc, 1)
acc = _SHL(b2 And &HF, 2)
If it <> strend Then
it = it + 1
b3 = Asc(Mid$(source, it, 1))
acc = acc Or _SHR(b3, 6)
sink = sink + Mid$(Base64, acc, 1)
sink = sink + Mid$(Base64, b3 And &H3F, 1)
Else
sink = sink + Mid$(Base64, acc, 1)
sink = sink + "="
End If
Else
sink = sink + Mid$(Base64, acc, 1)
sink = sink + "="
sink = sink + "="
End If
Wend
encode = sink
End Function
Function decode$ (source As String)
Dim As _Unsigned _Integer64 length: length = Len(source)
Dim As _Unsigned _Integer64 it, strend
Dim As Long acc
Dim As String sink
strend = length
While it <> strend
Dim As _Unsigned _Byte b1, b2, b3, b4
it = it + 1
b1 = Asc(Mid$(source, it, 1))
it = it + 1
b2 = Asc(Mid$(source, it, 1))
it = it + 1
b3 = Asc(Mid$(source, it, 1))
it = it + 1
b4 = Asc(Mid$(source, it, 1))
Dim As Long i1, i2
i1 = findIndex(b1)
i2 = findIndex(b2)
acc = _SHL(i1, 2)
acc = acc Or _SHR(i2, 4)
sink = sink + Chr$(acc)
If b3 <> Asc("=") Then
Dim As Long i3
i3 = findIndex(b3)
acc = _SHL(i2 And &HF, 4)
acc = acc Or _SHR(i3, 2)
sink = sink + Chr$(acc)
If b4 <> Asc("=") Then
Dim As Long i4
i4 = findIndex(b4)
acc = _SHL(i3 And &H3, 6)
acc = acc Or i4
sink = sink + Chr$(acc)
End If
End If
Wend
decode = sink
End Function |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #CoffeeScript | CoffeeScript | root_mean_square = (ary) ->
sum_of_squares = ary.reduce ((s,x) -> s + x*x), 0
return Math.sqrt(sum_of_squares / ary.length)
alert root_mean_square([1..10]) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.