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/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #Wren | Wren | import "/date" for Date
Date.default = Date.isoFull
var dt = Date.fromNumber(0)
System.print(dt)
var dt2 = Date.unixEpoch
System.print(dt2) |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #gnuplot | gnuplot | # Return a string space or star to print at x,y.
# Must have x<y. x<0 is the left side of the triangle.
# If x<-y then it's before the left edge and the return is a space.
char(x,y) = (y+x>=0 && ((y+x)%2)==0 && ((y+x)&(y-x))==0 ? "*" : " ")
# Return a string which is row y of the triangle from character
# position x through to the right hand end x==y, inclusive.
row(x,y) = (x<=y ? char(x,y).row(x+1,y) : "\n")
# Return a string of stars, spaces and newlines which is the
# Sierpinski triangle from row y to limit, inclusive.
# The first row is y=0.
triangle(y,limit) = (y <= limit ? row(-limit,y).triangle(y+1,limit) : "")
# Print rows 0 to 15, which is the order 4 triangle per the task.
print triangle(0,15) |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #C.2B.2B | C++ | // contributed to rosettacode.org by Peter Helcmanovsky
// BCT = Binary-Coded Ternary: pairs of bits form one digit [0,1,2] (0b11 is invalid digit)
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v; // either valid BCT (v-1), or block of bottom 0b00 digits becomes invalid 0b11
return v ^ (v & (v>>1) & bct_low_bits); // fix all 0b11 to 0b10 (digit "2")
}
int main (int argc, char *argv[])
{
// parse N from first argument, if no argument, use 3 as default value
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
// check for valid N (0..9) - 16 requires 33 bits for BCT form 1<<(n*2) => hard limit
if (n < 0 || 9 < n) { // but N=9 already produces 370MB output
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2); // 3**n in BCT form (initial value for loops)
// draw the carpet, two nested loops counting down in BCT form of values
int32_t y = size_bct;
do { // all lines loop
y = bct_decrement(y); // --Y (in BCT)
int32_t x = size_bct;
do { // line loop
x = bct_decrement(x); // --X (in BCT)
// check if x has ternary digit "1" at same position(s) as y -> output space (hole)
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
} |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #jq | jq | # jq's length applied to a number is its absolute value.
def shoelace:
. as $a
| reduce range(0; length-1) as $i (0;
. + $a[$i][0]*$a[$i+1][1] - $a[$i+1][0]*$a[$i][1] )
| (. + $a[-1][0]*$a[0][1] - $a[0][0]*$a[-1][1])|length / 2;
[ [3, 4], [5, 11], [12, 8], [9, 5], [5, 6] ]
| "The polygon with vertices at \(.) has an area of \(shoelace)." |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Julia | Julia | """
Assumes x,y points go around the polygon in one direction.
"""
shoelacearea(x, y) =
abs(sum(i * j for (i, j) in zip(x, append!(y[2:end], y[1]))) -
sum(i * j for (i, j) in zip(append!(x[2:end], x[1]), y))) / 2
x, y = [3, 5, 12, 9, 5], [4, 11, 8, 5, 6]
@show x y shoelacearea(x, y) |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Gambas | Gambas | Public Sub Main()
Shell "echo Hello World"
End |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Gema | Gema | $ gema -p '\B=Hello\n@end'
Hello |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Go | Go | echo 'package main;func main(){println("hlowrld")}'>/tmp/h.go;go run /tmp/h.go |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Batch_File | Batch File | %=== Batch Files have no booleans. ===%
%=== I will instead use 1 as true and 0 as false. ===%
@echo off
setlocal enabledelayedexpansion
echo AND
for /l %%i in (0,1,1) do (
for /l %%j in (0,1,1) do (
echo.a^(%%i^) AND b^(%%j^)
call :a %%i
set res=!bool_a!
if not !res!==0 (
call :b %%j
set res=!bool_b!
)
echo.=^> !res!
)
)
echo ---------------------------------
echo OR
for /l %%i in (0,1,1) do (
for /l %%j in (0,1,1) do (
echo a^(%%i^) OR b^(%%j^)
call :a %%i
set res=!bool_a!
if !res!==0 (
call :b %%j
set res=!bool_b!
)
echo.=^> !res!
)
)
pause>nul
exit /b 0
::----------------------------------------
:a
echo. calls func a
set bool_a=%1
goto :EOF
:b
echo. calls func b
set bool_b=%1
goto :EOF |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Applesoft_BASIC | Applesoft BASIC | 0 GOTO 10: ONERR AI READ LY RND
10 LET X = 256 * PEEK (104)
11 LET X = X + PEEK (103) + 7
20 CALL - 1184:B$ = CHR$ (8)
21 NORMAL : PRINT :E = 61588
22 PRINT TAB( 29)"APPLESOFT";
23 PRINT " II"B$:M = - 1
24 PRINT TAB( 22)"BASED ON ";
25 FOR I = E + 9 TO E STEP M
26 POKE 65, PEEK (I): CALL X
27 NEXT : PRINT B$:S$ = " "
28 PRINT TAB( 28)"6502 ";
29 PRINT "BASIC V2" CHR$ (8)
30 PRINT "CHARACTER SET"
40 FOR R = 0 TO 15: PRINT
50 FOR C = 2 TO 7:A = C * 16
60 LET N$ = S$ + STR$ (A + R)
70 LET N$ = RIGHT$ (N$,4)
80 PRINT N$":" CHR$ (A + R);
90 NEXT C,R: PRINT |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #REBOL | REBOL | rebol [author: "Nick Antonaccio"]
write/append %rdb "" db: load %rdb
switch system/options/args/1 [
"new" [write/append %rdb rejoin [now " " mold/only next system/options/args newline]]
"latest" [print copy/part tail sort/skip db 4 -4]
"latestcat" [
foreach cat unique extract at db 3 4 [
t: copy []
foreach [a b c d] db [if c = cat [append t reduce [a b c d]]]
print copy/part tail sort/skip t 4 -4
]
]
"sort" [probe sort/skip db 4]
]
halt |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #zkl | zkl | zkl: Time.Clock.tickToTock(0,False)
L(1970,1,1,0,0,0) // y,m,d, h,m,s |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Go | Go | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 4
var grain = "*"
func main() {
t := []string{grain + strings.Repeat(" ", utf8.RuneCountInString(grain))}
for ; order > 0; order-- {
sp := strings.Repeat(" ", utf8.RuneCountInString(t[0])/2)
top := make([]string, len(t))
for i, s := range t {
top[i] = sp + s + sp
t[i] += s
}
t = append(top, t...)
}
for _, r := range t {
fmt.Println(r)
}
} |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Clojure | Clojure | (ns example
(:require [clojure.contrib.math :as math]))
(defn in-carpet? [x y]
(loop [x x, y y]
(cond
(or (zero? x) (zero? y)) true
(and (= 1 (mod x 3)) (= 1 (mod y 3))) false
:else (recur (quot x 3) (quot y 3)))))
(defn carpet [n]
(apply str
(interpose
\newline
(for [x (range (math/expt 3 n))]
(apply str
(for [y (range (math/expt 3 n))]
(if (in-carpet? x y) "*" " ")))))))
(println (carpet 3)) |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Kotlin | Kotlin | // version 1.1.3
class Point(val x: Int, val y: Int) {
override fun toString() = "($x, $y)"
}
fun shoelaceArea(v: List<Point>): Double {
val n = v.size
var a = 0.0
for (i in 0 until n - 1) {
a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y
}
return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0
}
fun main(args: Array<String>) {
val v = listOf(
Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6)
)
val area = shoelaceArea(v)
println("Given a polygon with vertices at $v,")
println("its area is $area")
} |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Groovy | Groovy | $ groovysh -q "println 'Hello'"
Hello |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Haskell | Haskell | $ ghc -e 'putStrLn "Hello"'
Hello |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Huginn | Huginn | $ huginn -c '"Hello"' |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #BBC_BASIC | BBC BASIC | REM TRUE is represented as -1, FALSE as 0
FOR i% = TRUE TO FALSE
FOR j% = TRUE TO FALSE
PRINT "For x=a(";FNboolstring(i%);") AND b(";FNboolstring(j%);")"
x% = FALSE
REM Short-circuit AND can be simulated by cascaded IFs:
IF FNa(i%) IF FNb(j%) THEN x%=TRUE
PRINT "x is ";FNboolstring(x%)
PRINT
PRINT "For y=a(";FNboolstring(i%);") OR b(";FNboolstring(j%);")"
y% = FALSE
REM Short-circuit OR can be simulated by De Morgan's laws:
IF NOTFNa(i%) IF NOTFNb(j%) ELSE y%=TRUE : REM Note ELSE without THEN
PRINT "y is ";FNboolstring(y%)
PRINT
NEXT:NEXT
END
DEFFNa(bool%)
PRINT "Function A used; ";
=bool%
DEFFNb(bool%)
PRINT "Function B used; ";
=bool%
DEFFNboolstring(bool%)
IF bool%=0 THEN ="FALSE" ELSE="TRUE" |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Bracmat | Bracmat | ( (a=.out$"I'm a"&!!arg)
& (b=.out$"I'm b"&!!arg)
& (false==~)
& (true==)
& !false !true:?outer
& whl
' ( !outer:%?x ?outer
& !false !true:?inner
& whl
' ( !inner:%?y ?inner
& out
$ ( Testing
(!!x&true|false)
AND
(!!y&true|false)
)
& `(a$!x&b$!y)
& out
$ ( Testing
(!!x&true|false)
OR
(!!y&true|false)
)
& `(a$!x|b$!y)
)
)
& done
);
|
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ARM_Assembly | ARM Assembly | .equ CursorX,0x02000000
.equ CursorY,0x02000001
ProgramStart:
mov sp,#0x03000000 ;Init Stack Pointer
mov r4,#0x04000000 ;DISPCNT -LCD Control
mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3
str r2,[r4] ;now the screen is visible
bl ResetTextCursors ;set text cursors to top left of screen
mov r2,#32
mov r3,#32+20 ;screen height is 20 chars
mov r5,#0 ;column spacer
mov r6,#5
;R0 = Character to print (working copy)
;R2 = real copy
;R3 = compare factor
loop_printAscii:
mov r0,r2
bl ShowHex
mov r0,#32
bl PrintChar
mov r0,r2
bl PrintChar
bl CustomNewLine
add r2,r2,#1
cmp r2,#128
beq forever ;exit early
cmp r2,r3
bne loop_printAscii
add r3,r3,#20 ;next section
;inc to next column
add r5,r5,#5
mov r0,r5
mov r1,#0
bl SetTextCursors
subs r6,r6,#1
bne loop_printAscii
forever:
b forever
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; INPUT/OUTPUT SUBROUTINES - CREATED BY KEITH OF CHIBIAKUMAS.COM
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintString: ;Print 255 terminated string
STMFD sp!,{r0-r12, lr}
PrintStringAgain:
ldrB r0,[r1],#1
cmp r0,#255
beq PrintStringDone ;Repeat until 255
bl printchar ;Print Char
b PrintStringAgain
PrintStringDone:
LDMFD sp!,{r0-r12, pc}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintChar:
STMFD sp!,{r0-r12, lr}
mov r4,#0
mov r5,#0
mov r3,#CursorX
ldrB r4,[r3] ;X pos
mov r3,#CursorY
ldrB r5,[r3] ;Y pos
mov r3,#0x06000000 ;VRAM base
mov r6,#8*2 ;Xpos, 2 bytes per pixel, 8 bytes per char
mul r2,r4,r6
add r3,r3,r2
mov r4,#240*8*2 ;Ypos, 240 pixels per line,
mul r2,r5,r4 ;2 bytes per pixel, 8 lines per char
add r3,r3,r2
adr r4,BitmapFont ;Font source
sub r0,r0,#32 ;First Char is 32 (space)
add r4,r4,r0,asl #3 ;8 bytes per char
mov r1,#8 ;8 lines
DrawLine:
mov r7,#8 ;8 pixels per line
ldrb r8,[r4],#1 ;Load Letter
mov r9,#0b100000000 ;Mask
mov r2, #0b1111111101000000; Color: ABBBBBGGGGGRRRRR A=Alpha
DrawPixel:
tst r8,r9 ;Is bit 1?
strneh r2,[r3] ;Yes? then fill pixel (HalfWord)
add r3,r3,#2
mov r9,r9,ror #1 ;Bitshift Mask
subs r7,r7,#1
bne DrawPixel ;Next Hpixel
add r3,r3,#480-16 ;Move Down a line (240 pixels *2 bytes)
subs r1,r1,#1 ;-1 char (16 px)
bne DrawLine ;Next Vline
LineDone:
mov r3,#CursorX
ldrB r0,[r3]
add r0,r0,#1 ;Move across screen
strB r0,[r3]
mov r10,#30
cmp r0,r10
bleq NewLine
LDMFD sp!,{r0-r12, pc}
NewLine:
STMFD sp!,{r0-r12, lr}
mov r3,#CursorX
mov r0,#0
strB r0,[r3]
mov r4,#CursorY
ldrB r0,[r4]
add r0,r0,#1
strB r0,[r4]
LDMFD sp!,{r0-r12, pc}
CustomNewLine:
STMFD sp!,{r0-r12, lr}
mov r3,#CursorX
mov r0,r5
strB r0,[r3]
mov r4,#CursorY
ldrB r0,[r4]
add r0,r0,#1
strB r0,[r4]
LDMFD sp!,{r0-r12, pc}
ResetTextCursors:
STMFD sp!,{r4-r6,lr}
mov r4,#0
mov r5,#CursorX
mov r6,#CursorY
strB r4,[r5]
strB r4,[r6]
LDMFD sp!,{r4-r6,lr}
bx lr
SetTextCursors:
;input: R0 = new X
; R1 = new Y
STMFD sp!,{r5-r6}
mov r5,#CursorX
mov r6,#CursorY
strB r0,[r5]
strB r1,[r6]
LDMFD sp!,{r5-r6}
bx lr
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ShowHex:
STMFD sp!,{r0-r12, lr}
mov r2,r0,ror #4
bl ShowHexChar
mov r2,r0
bl ShowHexChar
LDMFD sp!,{r0-r12, pc}
ShowHexChar:
STMFD sp!,{r0-r12, lr}
;mov r3,
and r0,r2,#0x0F ; r3
cmp r0,#10
addge r0,r0,#7 ;if 10 or greater convert to alphabet letters a-f
add r0,r0,#48
bl PrintChar
LDMFD sp!,{r0-r12, pc}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
BitmapFont:
;each byte represents a row of 8 pixels. This is a 1BPP font that is converted to the GBA's 16bpp screen format at runtime
.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 ; 20
.byte 0x10,0x18,0x18,0x18,0x18,0x00,0x18,0x00 ; 21
.byte 0x28,0x6C,0x28,0x00,0x00,0x00,0x00,0x00 ; 22
.byte 0x00,0x28,0x7C,0x28,0x7C,0x28,0x00,0x00 ; 23
.byte 0x18,0x3E,0x48,0x3C,0x12,0x7C,0x18,0x00 ; 24
.byte 0x02,0xC4,0xC8,0x10,0x20,0x46,0x86,0x00 ; 25
.byte 0x10,0x28,0x28,0x72,0x94,0x8C,0x72,0x00 ; 26
.byte 0x0C,0x1C,0x30,0x00,0x00,0x00,0x00,0x00 ; 27
.byte 0x18,0x18,0x30,0x30,0x30,0x18,0x18,0x00 ; 28
.byte 0x18,0x18,0x0C,0x0C,0x0C,0x18,0x18,0x00 ; 29
.byte 0x08,0x49,0x2A,0x1C,0x14,0x22,0x41,0x00 ; 2A
.byte 0x00,0x18,0x18,0x7E,0x18,0x18,0x00,0x00 ; 2B
.byte 0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x30 ; 2C
.byte 0x00,0x00,0x00,0x7E,0x7E,0x00,0x00,0x00 ; 2D
.byte 0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x00 ; 2E
.byte 0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x00 ; 2F
.byte 0x7C,0xC6,0xD6,0xD6,0xD6,0xC6,0x7C,0x00 ; 30
.byte 0x10,0x18,0x18,0x18,0x18,0x18,0x08,0x00 ; 31
.byte 0x3C,0x7E,0x06,0x3C,0x60,0x7E,0x3C,0x00 ; 32
.byte 0x3C,0x7E,0x06,0x1C,0x06,0x7E,0x3C,0x00 ; 33
.byte 0x18,0x3C,0x64,0xCC,0x7C,0x0C,0x08,0x00 ; 34
.byte 0x3C,0x7E,0x60,0x7C,0x06,0x7E,0x3E,0x00 ; 35
.byte 0x3C,0x7E,0x60,0x7C,0x66,0x66,0x3C,0x00 ; 36
.byte 0x3C,0x7E,0x06,0x0C,0x18,0x18,0x10,0x00 ; 37
.byte 0x3C,0x66,0x66,0x3C,0x66,0x66,0x3C,0x00 ; 38
.byte 0x3C,0x66,0x66,0x3E,0x06,0x7E,0x3C,0x00 ; 39
.byte 0x00,0x00,0x18,0x18,0x00,0x18,0x18,0x00 ; 3A
.byte 0x00,0x00,0x18,0x18,0x00,0x18,0x18,0x30 ; 3B
.byte 0x0C,0x1C,0x38,0x60,0x38,0x1C,0x0C,0x00 ; 3C
.byte 0x00,0x00,0x7E,0x00,0x00,0x7E,0x00,0x00 ; 3D
.byte 0x60,0x70,0x38,0x0C,0x38,0x70,0x60,0x00 ; 3E
.byte 0x3C,0x76,0x06,0x1C,0x00,0x18,0x18,0x00 ; 3F
.byte 0x7C,0xCE,0xA6,0xB6,0xC6,0xF0,0x7C,0x00 ; 40 @
.byte 0x18,0x3C,0x66,0x66,0x7E,0x66,0x24,0x00 ; 41 A
.byte 0x3C,0x66,0x66,0x7C,0x66,0x66,0x3C,0x00 ; 42 B
.byte 0x38,0x7C,0xC0,0xC0,0xC0,0x7C,0x38,0x00 ; 43 C
.byte 0x3C,0x64,0x66,0x66,0x66,0x64,0x38,0x00 ; 44 D
.byte 0x3C,0x7E,0x60,0x78,0x60,0x7E,0x3C,0x00 ; 45 E
.byte 0x38,0x7C,0x60,0x78,0x60,0x60,0x20,0x00 ; 46 F
.byte 0x3C,0x66,0xC0,0xC0,0xCC,0x66,0x3C,0x00 ; 47 G
.byte 0x24,0x66,0x66,0x7E,0x66,0x66,0x24,0x00 ; 48 H
.byte 0x10,0x18,0x18,0x18,0x18,0x18,0x08,0x00 ; 49 I
.byte 0x08,0x0C,0x0C,0x0C,0x4C,0xFC,0x78,0x00 ; 4A J
.byte 0x24,0x66,0x6C,0x78,0x6C,0x66,0x24,0x00 ; 4B K
.byte 0x20,0x60,0x60,0x60,0x60,0x7E,0x3E,0x00 ; 4C L
.byte 0x44,0xEE,0xFE,0xD6,0xD6,0xD6,0x44,0x00 ; 4D M
.byte 0x44,0xE6,0xF6,0xDE,0xCE,0xC6,0x44,0x00 ; 4E N
.byte 0x38,0x6C,0xC6,0xC6,0xC6,0x6C,0x38,0x00 ; 4F O
.byte 0x38,0x6C,0x64,0x7C,0x60,0x60,0x20,0x00 ; 50 P
.byte 0x38,0x6C,0xC6,0xC6,0xCA,0x74,0x3A,0x00 ; 51 Q
.byte 0x3C,0x66,0x66,0x7C,0x6C,0x66,0x26,0x00 ; 52 R
.byte 0x3C,0x7E,0x60,0x3C,0x06,0x7E,0x3C,0x00 ; 53 S
.byte 0x3C,0x7E,0x18,0x18,0x18,0x18,0x08,0x00 ; 54 T
.byte 0x24,0x66,0x66,0x66,0x66,0x66,0x3C,0x00 ; 55 U
.byte 0x24,0x66,0x66,0x66,0x66,0x3C,0x18,0x00 ; 56 V
.byte 0x44,0xC6,0xD6,0xD6,0xFE,0xEE,0x44,0x00 ; 57 W
.byte 0xC6,0x6C,0x38,0x38,0x6C,0xC6,0x44,0x00 ; 58 X
.byte 0x24,0x66,0x66,0x3C,0x18,0x18,0x08,0x00 ; 59 Y
.byte 0x7C,0xFC,0x0C,0x18,0x30,0x7E,0x7C,0x00 ; 5A Z
.byte 0x1C,0x30,0x30,0x30,0x30,0x30,0x1C,0x00 ; 5B [
.byte 0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x00 ; 5C Backslash
.byte 0x38,0x0C,0x0C,0x0C,0x0C,0x0C,0x38,0x00 ; 5D ]
.byte 0x10,0x28,0x44,0x00,0x00,0x00,0x00,0x00 ; 5E ^
.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C ; 5F _
.byte 0x10,0x08,0x00,0x00,0x00,0x00,0x00,0x00 ; 60 `
.byte 0x00,0x00,0x38,0x0C,0x7C,0xCC,0x78,0x00 ; 61
.byte 0x20,0x60,0x7C,0x66,0x66,0x66,0x3C,0x00 ; 62
.byte 0x00,0x00,0x3C,0x66,0x60,0x66,0x3C,0x00 ; 63
.byte 0x08,0x0C,0x7C,0xCC,0xCC,0xCC,0x78,0x00 ; 64
.byte 0x00,0x00,0x3C,0x66,0x7E,0x60,0x3C,0x00 ; 65
.byte 0x1C,0x36,0x30,0x38,0x30,0x30,0x10,0x00 ; 66
.byte 0x00,0x00,0x3C,0x66,0x66,0x3E,0x06,0x3C ; 67
.byte 0x20,0x60,0x6C,0x76,0x66,0x66,0x24,0x00 ; 68
.byte 0x18,0x00,0x18,0x18,0x18,0x18,0x08,0x00 ; 69
.byte 0x06,0x00,0x04,0x06,0x06,0x26,0x66,0x3C ; 6A
.byte 0x20,0x60,0x66,0x6C,0x78,0x6C,0x26,0x00 ; 6B
.byte 0x10,0x18,0x18,0x18,0x18,0x18,0x08,0x00 ; 6C
.byte 0x00,0x00,0x6C,0xFE,0xD6,0xD6,0xC6,0x00 ; 6D
.byte 0x00,0x00,0x3C,0x66,0x66,0x66,0x24,0x00 ; 6E
.byte 0x00,0x00,0x3C,0x66,0x66,0x66,0x3C,0x00 ; 6F
.byte 0x00,0x00,0x3C,0x66,0x66,0x7C,0x60,0x20 ; 70
.byte 0x00,0x00,0x78,0xCC,0xCC,0x7C,0x0C,0x08 ; 71
.byte 0x00,0x00,0x38,0x7C,0x60,0x60,0x20,0x00 ; 72
.byte 0x00,0x00,0x3C,0x60,0x3C,0x06,0x7C,0x00 ; 73
.byte 0x10,0x30,0x3C,0x30,0x30,0x3E,0x1C,0x00 ; 74
.byte 0x00,0x00,0x24,0x66,0x66,0x66,0x3C,0x00 ; 75
.byte 0x00,0x00,0x24,0x66,0x66,0x3C,0x18,0x00 ; 76
.byte 0x00,0x00,0x44,0xD6,0xD6,0xFE,0x6C,0x00 ; 77
.byte 0x00,0x00,0xC6,0x6C,0x38,0x6C,0xC6,0x00 ; 78
.byte 0x00,0x00,0x24,0x66,0x66,0x3E,0x06,0x7C ; 79
.byte 0x00,0x00,0x7E,0x0C,0x18,0x30,0x7E,0x00 ; 7A
.byte 0x10,0x20,0x20,0x40,0x40,0x20,0x20,0x10 ; 7B {
.byte 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10 ; 7C |
.byte 0x08,0x04,0x04,0x02,0x02,0x04,0x04,0x08 ; 7D }
.byte 0x00,0x00,0x00,0x20,0x52,0x0C,0x00,0x00 ; 7E ~
.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 ; 7F
.byte 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF ; 80 |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* 05.10.2014
*--------------------------------------------------------------------*/
x05='05'x
mydb='sidb.txt'
Say 'Enter your commands, ?, or end'
Do Forever
Parse Pull l
Parse Var l command text
Select
When command='?' Then
Call help
When command='add' Then Do
Parse Var text item ',' category ',' date
If date='' Then
date=date('S') /*yyyymmdd*/
Say 'adding item' item'/'category 'dated' date
Call lineout mydb,date item x05 category
End
When command='latest' Then Do
Call lineout mydb
Parse Var text category
hidt='00000000'
ol=''
Do While lines(mydb)>0
l=linein(mydb)
Parse Var l dt a (x05) b
If category=''|,
category='-' & b='' |,
b=category Then Do
If dt>>hidt Then Do
ol=l
hidt=dt
End
End
End
If ol>'' Then
Call o ol
Else
Say 'no matching item found'
End
When command='all' Then Do
Call lineout mydb
Parse Var text category
Do While lines(mydb)>0
l=linein(mydb)
Parse Var l a (x05) b
If category=''|,
category='-' & b=''|,
b=category Then
Call o l
End
End
When command='end' Then
Leave
Otherwise Do
Say 'invalid command ('command')'
Call help
End
End
End
Say 'Bye'
Exit
o: Parse Value arg(1) With dt text
Say left(dt,8) text
Return
help:
Say 'add item[,[category][,date]] to add an item'
Say 'latest category to list the latest item of a category'
Say 'latest to list the latest item'
Say 'all category to list all items of a category'
Say 'all to list all items'
Say 'end to end this program'
Say 'Use category - to list items without category'
Return |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Golfscript | Golfscript | ' /\ /__\ '4/){.+\.{[2$.]*}%\{.+}%+\}3*;n* |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Commodore_BASIC | Commodore BASIC | 100 PRINT CHR$(147); CHR$(18); "**** SIERPINSKI CARPET ****"
110 PRINT
120 INPUT "ORDER"; O$
130 O = VAL(O$)
140 IF O < 1 THEN 120
150 PRINT
160 SZ = 3 ↑ O
170 FOR Y = 0 TO SZ - 1
180 :FOR X = 0 TO SZ - 1
190 : CH$ = "#"
200 : X1 = X
210 : Y1 = Y
220 : IF (X1 = 0) OR (Y1 = 0) THEN 290
230 : X3 = X1 - 3 * INT(X1 / 3)
240 : Y3 = Y1 - 3 * INT(Y1 / 3)
250 : IF (X3 = 1) AND (Y3 = 1) THEN CH$ = " ": GOTO 290
260 : X1 = INT(X1 / 3)
270 : Y1 = INT(Y1 / 3)
280 : GOTO 220
290 : PRINT CH$;
300 :NEXT X
310 PRINT
320 NEXT Y
|
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Lambdatalk | Lambdatalk |
{def shoelace
{lambda {:pol}
{abs
{/
{-
{+ {S.map {{lambda {:pol :i} {* {car {A.get :i :pol}}
{cdr {A.get {+ :i 1} :pol}}}} :pol}
{S.serie 0 {- {A.length :pol} 2}}}
{* {car {A.get {- {A.length :pol} 1} :pol}}
{cdr {A.get 0 :pol}}}}
{+ {S.map {{lambda {:pol :i} {* {car {A.get {+ :i 1} :pol}}
{cdr {A.get :i :pol}}}} :pol}
{S.serie 0 {- {A.length :pol} 2}}}
{* {car {A.get 0 :pol}}
{cdr {A.get {- {A.length :pol} 1} :pol}}}}} 2}}}}
-> shoelace
{def pol
{A.new {cons 3 4}
{cons 5 11}
{cons 12 8}
{cons 9 5}
{cons 5 6}}}
-> pol = [(3 4),(5 11),(12 8),(9 5),(5 6)]
{shoelace {pol}}
-> 30
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Icon_and_Unicon | Icon and Unicon | echo "procedure main();write(\"hello\");end" | icont - -x |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #J | J | $ jconsole -js "exit echo 'Hello'"
Hello |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Java | Java | $ echo 'public class X{public static void main(String[]args){' \
> 'System.out.println("Hello Java!");}}' >X.java
$ javac X.java && java X |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #C | C | #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&); // b is not evaluated
TEST(true, false, ||); // b is not evaluated
TEST(true, false, &&); // b is evaluated
TEST(false, false, ||); // b is evaluated
return 0;
} |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program merkleRoot64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ O_RDWR, 0x0002 // open for reading and writing
.equ BUFFERSIZE, 65535 // file buffer
.equ LGBLOCK, 1024 // block length
.equ LGHASH, 32 // hash length
.equ NBELEMENTS, 40 // array size
.equ LGZONETRAV, 2048 // process array size
/*******************************************/
/* Structures */
/********************************************/
/* structure variables hash compute */
.struct 0
var_a: // a
.struct var_a + 4
var_b: // b
.struct var_b + 4
var_c: // c
.struct var_c + 4
var_d: // d
.struct var_d + 4
var_e: // e
.struct var_e + 4
var_f: // f
.struct var_f + 4
var_g: // g
.struct var_g + 4
var_h: // h
.struct var_h + 4
/***********************************/
/* Initialized data */
/***********************************/
.data
szFileName: .asciz "title.png"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Error detected.\n"
szMessNbHash: .asciz "Start hash number : @ \n"
szMessTest: .asciz "Rosetta code"
.align 4
/* array constantes Hi */
tbConstHi: .int 0x6A09E667 // H0
.int 0xBB67AE85 // H1
.int 0x3C6EF372 // H2
.int 0xA54FF53A // H3
.int 0x510E527F // H4
.int 0x9B05688C // H5
.int 0x1F83D9AB // H6
.int 0x5BE0CD19 // H7
/* array 64 constantes Kt */
tbConstKt:
.int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
/***********************************/
/* UnInitialized data */
/***********************************/
.bss
sBuffer: .skip BUFFERSIZE // file buffer
.align 8
qNbBlocs: .skip 8
qNbHash: .skip 8
sZoneConv: .skip 24
sZoneTrav: .skip LGZONETRAV
HashResult: .skip LGHASH + 8
HashProcess: .skip LGHASH * 2
tbListHash: .skip LGHASH * NBELEMENTS
tbH: .skip 4 * 8 // 8 variables H
tbabcdefgh: .skip 4 * 8
tbW: .skip 4 * 64 // 64 words W
/***********************************/
/* code section */
/***********************************/
.text
.global main
main:
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszFileName // File name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN // open file
svc #0
cmp x0,#0 // error ?
ble error
mov x19,x0 // save fd
ldr x1,qAdrsBuffer
mov x2,#BUFFERSIZE
mov x8,#READ // call system read file
svc 0
cmp x0,#0 // error read ?
ble error
mov x7,x0 // number of read characters
ldr x6,qAdrsBuffer
mov x5,#0 // counter characters block
1:
add x0,x6,x5 // start address of each block
ldr x1,qAdrHashResult
mov x2,#LGBLOCK
bl computeSHA256LG
bl storeHash // store hash in start array
cmp x0,#-1
beq error
add x5,x5,#LGBLOCK // new buffer offset
sub x0,x7,x5 //
cmp x0,#LGBLOCK // last block
bge 1b // and loop
sub x2,x7,x5 // length last block
add x0,x6,x5 // address last block
ldr x1,qAdrHashResult
bl computeSHA256LG
bl storeHash
cmp x0,#-1
beq error
ldr x0,qAdrqNbHash
ldr x0,[x0]
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessNbHash
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
ldr x0,qAdrtbListHash
ldr x1,qAdrHashResult
bl calculerMerkleRoot
ldr x0,qAdrHashResult
bl displaySHA256 // display résult
end:
mov x0,x19 // FD
mov x8, #CLOSE // call system close file
svc #0
cmp x0,#0
blt error
mov x0,#0 // return code
b 100f
error:
ldr x0,qAdrszMessErreur // error message
bl affichageMess
mov x0,#1 // return error code
100: // standard end of the program
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrsBuffer: .quad sBuffer
qAdrszFileName: .quad szFileName
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrHashResult: .quad HashResult
qAdrszMessNbHash: .quad szMessNbHash
qAdrszMessTest: .quad szMessTest
/******************************************************************/
/* store hash in start array */
/******************************************************************/
/* x0 hash address */
storeHash:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
ldr x2,qAdrqNbHash // number element counter
ldr x3,[x2]
ldr x1,qAdrtbListHash // address array hash
mov x4,#LGHASH // hash length
madd x5,x4,x3,x1 // compute store address
mov x1,#0 // counter
1:
ldr w4,[x0,x1] // load four bytes
str w4,[x5,x1] // store four bytes
add x1,x1,#4
cmp x1,#LGHASH // 32 bytes ?
blt 1b // no -> loop
add x3,x3,#1
cmp x3,#NBELEMENTS
bge 99f // error
str x3,[x2] // store new counter hash
b 100f
99:
mov x0,#-1 // error ?
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqNbHash: .quad qNbHash
qAdrtbListHash: .quad tbListHash
/******************************************************************/
/* compute hash root Merkle */
/******************************************************************/
// x0 start array hash address
// x1 result array address (32 bytes)
calculerMerkleRoot:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x10,x1
mov x12,sp // save stack adresse
ldr x3,qAdrqNbHash
ldr x3,[x3]
cmp x3,#0 // 0 hash ?
beq 99f // error
mov x4,#LGHASH * 2
mul x1,x3,x4 // compute hash size * blocks number * 2
sub sp,sp,x1 // reserve array
mov fp,sp // address previousTreeLayer
lsr x1,x1,#1 // reserve size / 2
add x7,fp,x1 // address TreeLayer
mov x2,#0 // counter
mov x4,#LGHASH
1:
mul x1,x2,x4
add x6,x0,x1
add x8,fp,x1
mov x5,#0
2: // loop copying 32 octets hash
ldr w9,[x6,x5]
str w9,[x8,x5]
add x5,x5,#4 // count
cmp x5,#LGHASH
blt 2b
add x2,x2,#1 // next hash block
cmp x2,x3 // maxi ?
blt 1b
mov x0,fp
mov x11,#0 // indice TreeLayer
mov x5,#0 // indice layer
3: // loop
cmp x3,#1 // one hash ?
beq 12f // yes -> end
sub x3,x3,#1
mov x4,#LGHASH
madd x8,x11,x4,fp // address hash 1
mov x9,x7 // raz TreeLayer
4:
cmp x11,x3
bgt 11f // end loop ?
blt 5f
mov x0,x8 // last odd hash
add x11,x11,#1 // no concatenation
mov x1,#0
41: // but loop copy odd hash in treelayer
ldr w4,[x0,x1]
str w4,[x9,x1]
add x1,x1,#4
cmp x1,#LGHASH
blt 41b
b 9f
5: // other hashes
add x6,x8,#LGHASH // address hash N + 1
6:
add x11,x11,#1
ldr x1,qAdrHashProcess // address array hash concatenation
mov x0,#0
7: // loop copy element N
ldr w4,[x8,x0]
rev w4,w4 // inversion byte in word
str w4,[x1,x0]
add x0,x0,#4
cmp x0,#LGHASH
blt 7b
add x1,x1,#LGHASH
mov x0,#0
8: // loop copy element N + 1
ldr w4,[x6,x0]
rev w4,w4 // inversion byte in word
str w4,[x1,x0]
add x0,x0,#4
cmp x0,#LGHASH
blt 8b
ldr x0,qAdrHashProcess
mov x1,x9
mov x2,#LGHASH * 2
bl computeSHA256LG // calcul du hash complet
9:
add x11,x11,#1 // incremente counter previousTreeLayer
add x5,x5,#1 // incremente counter treeLayer
add x9,x9,#LGHASH // next address treeLayer
add x8,x6,#LGHASH // maj element N avec N + 2
b 4b
11:
mov x0,fp
mov fp,x7 // treelayer in previous
mov x7,x0
mov x3,x5 // counter previous = counter treelayer
mov x5,#0 // raz treelayer
mov x11,#0 // raz previousTreeLayer
b 3b // and loop
12: // end process
mov x1,fp
mov x2,#0
13: // loop copy result
ldr w3,[x1,x2]
str w3,[x10,x2]
add x2,x2,#4
cmp x2,#LGHASH
blt 13b
mov x0,x10 // return address result
b 100f
99: // error
mov x0,#-1
100:
mov sp,x12 // restaur stack
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret
qAdrHashProcess: .quad HashProcess
/******************************************************************/
/* compute SHA256 avec longueur */
/******************************************************************/
/* x0 contains the string address */
/* x1 contains the return area address */
/* x2 contains string length */
computeSHA256LG:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
stp x19,x20,[sp,-16]! // save registers
mov x19,x1
ldr x1,qAdrtbH
mov x3,0
1: // modif 12/11/2021 boucle raz des 3 zones
str xzr,[x1,x3,lsl 3]
add x3,x3,1
cmp x3,4+4+32
blt 1b
ldr x1,qAdrsZoneTrav
mov x3,0
2: // modif 12/11/2021 boucle raz zone de travail
str xzr,[x1,x3,lsl 3]
add x3,x3,1
cmp x3,LGZONETRAV/8
blt 2b
mov x5,x2
mov x2,#0 // counter length
debCopy: // copy string in work area
ldrb w3,[x0,x2]
strb w3,[x1,x2]
cmp x2,x5 // modification 21/11/2021
add x4,x2,1
csel x2,x4,x2,ne
bne debCopy
//affmemtit copieSH x1 3
//affregtit copie 0
lsl x6,x2,#3 // initial message length in bits
mov x3,#0b10000000 // add bit 1 at end of string
strb w3,[x1,x2]
//affmemtit copieSH1 x1 3
add x2,x2,#1 // length in bytes
lsl x4,x2,#3 // length in bits
mov x3,#0
addZeroes:
lsr x5,x2,#6
lsl x5,x5,#6
sub x5,x2,x5
cmp x5,#56
beq storeLength // yes -> end add
strb w3,[x1,x2] // add zero at message end
add x2,x2,#1 // increment lenght bytes
add x4,x4,#8 // increment length in bits
b addZeroes
storeLength:
add x2,x2,#4 // add four bytes
rev w6,w6 // inversion bits initials message length
str w6,[x1,x2] // and store at end
ldr x7,qAdrtbConstHi // constantes H address
ldr x4,qAdrtbH // start area H
mov x5,#0
loopConst: // init array H with start constantes
ldr w6,[x7,x5,lsl #2] // load constante
str w6,[x4,x5,lsl #2] // and store
add x5,x5,#1
cmp x5,#8
blt loopConst
// split into block of 64 bytes
add x2,x2,#4 //
lsr x4,x2,#6 // blocks number
ldr x0,qAdrqNbBlocs
str x4,[x0] // save block maxi
mov x7,#0 // n° de block et x1 contient l adresse zone de travail
loopBlock: // begin loop of each block of 64 bytes
mov x0,x7
bl inversion // inversion each word because little indian
ldr x3,qAdrtbW // working area W address
mov x6,#0 // indice t
/* x2 address begin each block */
ldr x1,qAdrsZoneTrav
add x2,x1,x7,lsl #6 // compute block begin indice * 4 * 16
//mov x0,x2
//affmemtit verifBloc x0 10
loopPrep: // loop for expand 80 words
cmp x6,#15 //
bgt expand1
ldr w0,[x2,x6,lsl #2] // load word message
str w0,[x3,x6,lsl #2] // store in first 16 block
b expandEnd
expand1:
sub x8,x6,#2
ldr w9,[x3,x8,lsl #2]
ror w10,w9,#17 // fonction e1 (256)
ror w11,w9,#19
eor w10,w10,w11
lsr w11,w9,#10
eor w10,w10,w11
sub x8,x6,#7
ldr w9,[x3,x8,lsl #2]
add w9,w9,w10 // + w - 7
sub x8,x6,#15
ldr w10,[x3,x8,lsl #2]
ror w11,w10,#7 // fonction e0 (256)
ror w12,w10,#18
eor w11,w11,w12
lsr w12,w10,#3
eor w10,w11,w12
add w9,w9,w10
sub x8,x6,#16
ldr w11,[x3,x8,lsl #2]
add w9,w9,w11
str w9,[x3,x6,lsl #2]
expandEnd:
add x6,x6,#1
cmp x6,#64 // 64 words ?
blt loopPrep // and loop
/* COMPUTING THE MESSAGE DIGEST */
/* x1 area H constantes address */
/* x3 working area W address */
/* x5 address constantes K */
/* x6 counter t */
/* x7 block counter */
/* x8 addresse variables a b c d e f g h */
//ldr x0,qAdrtbW
//affmemtit verifW80 x0 20
// init variable a b c d e f g h
ldr x0,qAdrtbH
//affmemtit veriftbh x0 20
ldr x8,qAdrtbabcdefgh
mov x1,#0
loopInita:
ldr w9,[x0,x1,lsl #2]
str w9,[x8,x1,lsl #2]
add x1,x1,#1
cmp x1,#8
blt loopInita
ldr x1,qAdrtbConstHi
ldr x5,qAdrtbConstKt
mov x6,#0
loop64T: // begin loop 64 t
ldr w9,[x8,#var_h]
ldr w10,[x8,#var_e] // calcul T1
ror w11,w10,#6 // fonction sigma 1
ror w12,w10,#11
eor w11,w11,w12
ror w12,w10,#25
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e)
ldr w0,[x8,#var_f] // fonction ch x and y xor (non x and z)
ldr w4,[x8,#var_g]
and w11,w10,w0
mvn w12,w10
and w12,w12,w4
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e) + ch (e,f,g)
ldr w0,[x5,x6,lsl #2] // load constantes k0
add w9,w9,w0
ldr w0,[x3,x6,lsl #2] // Wt
add w9,w9,w0
// calcul T2
ldr w10,[x8,#var_a] // fonction sigma 0
ror w11,w10,#2
ror w12,w10,#13
eor w11,w11,w12
ror w12,w10,#22
eor w11,w11,w12
ldr w2,[x8,#var_b]
ldr w4,[x8,#var_c]
// fonction maj x and y xor x and z xor y and z
and w12,w10,w2
and w0,w10,w4
eor w12,w12,w0
and w0,w2,w4
eor w12,w12,w0 //
add w12,w12,w11 // T2
// compute variables
ldr w4,[x8,#var_g]
str w4,[x8,#var_h]
ldr w4,[x8,#var_f]
str w4,[x8,#var_g]
ldr w4,[x8,#var_e]
str w4,[x8,#var_f]
ldr w4,[x8,#var_d]
add w4,w4,w9 // add T1
str w4,[x8,#var_e]
ldr w4,[x8,#var_c]
str w4,[x8,#var_d]
ldr w4,[x8,#var_b]
str w4,[x8,#var_c]
ldr w4,[x8,#var_a]
str w4,[x8,#var_b]
add w4,w9,w12 // add T1 T2
str w4,[x8,#var_a]
add x6,x6,#1 // increment t
cmp x6,#64
blt loop64T
// End block
ldr x0,qAdrtbH // start area H
mov x10,#0
loopStoreH:
ldr w9,[x8,x10,lsl #2]
ldr w3,[x0,x10,lsl #2]
add w3,w3,w9
str w3,[x0,x10,lsl #2] // store variables in H0
add x10,x10,#1
cmp x10,#8
blt loopStoreH
// other bloc
add x7,x7,#1 // increment block
ldr x0,qAdrqNbBlocs
ldr x4,[x0] // restaur maxi block
cmp x7,x4 // maxi ?
blt loopBlock // loop other block
ldr x0,qAdrtbH // adresse resultat
//affmemtit resultat x0 3
mov x3,0
loopRes: // boucle de copie du hash
ldr w1,[x0,x3] // dans zone de retour
str w1,[x19,x3]
add x3,x3,4
cmp x3,28
ble loopRes
mov x0,x19
100:
ldp x19,x20,[sp],16 // restaur 2 registers
ldp x12,x13,[sp],16 // restaur 2 registers
ldp x10,x11,[sp],16 // restaur 2 registers
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneTrav: .quad sZoneTrav
qAdrtbConstHi: .quad tbConstHi
qAdrtbConstKt: .quad tbConstKt
qAdrtbH: .quad tbH
qAdrtbW: .quad tbW
qAdrtbabcdefgh: .quad tbabcdefgh
qAdrqNbBlocs: .quad qNbBlocs
/******************************************************************/
/* inversion des mots de 32 bits d un bloc */
/******************************************************************/
/* x0 contains N° block */
inversion:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
add x1,x1,x0,lsl #6 // debut du bloc
mov x2,#0
1: // start loop
ldr w3,[x1,x2,lsl #2]
rev w3,w3
str w3,[x1,x2,lsl #2]
add x2,x2,#1
cmp x2,#16
blt 1b
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* x0 contains the address of hash */
/* x1 contains the address of recept zone */
conversionSHA256:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0
mov x2,#0
1:
ldr w0,[x3,x2,lsl #2] // load 4 bytes
//rev x0,x0 // reverse bytes
bl conversion16_4W // conversion hexa
add x1,x1,8
add x2,x2,#1
cmp x2,#LGHASH / 4
blt 1b // and loop
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* x0 contains the address of hash */
displaySHA256:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0
mov x2,#0
1:
ldr w0,[x3,x2,lsl #2] // load 4 bytes
//rev x0,x0 // reverse bytes
ldr x1,qAdrsZoneConv
bl conversion16_4W // conversion hexa
ldr x0,qAdrsZoneConv
bl affichageMess
add x2,x2,#1
cmp x2,#LGHASH / 4
blt 1b // and loop
ldr x0,qAdrszCarriageReturn
bl affichageMess // display message
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* conversion hexadecimal register 32 bits */
/******************************************************************/
/* x0 contains value and x1 address zone receptrice */
conversion16_4W:
stp x0,lr,[sp,-48]! // save registres
stp x1,x2,[sp,32] // save registres
stp x3,x4,[sp,16] // save registres
mov x2,#28 // start bit position
mov x4,#0xF0000000 // mask
mov x3,x0 // save entry value
1: // start loop
and x0,x3,x4 // value register and mask
lsr x0,x0,x2 // right shift
cmp x0,#10 // >= 10 ?
bge 2f // yes
add x0,x0,#48 // no is digit
b 3f
2:
add x0,x0,#55 // else is a letter A-F
3:
strb w0,[x1],#1 // load result and + 1 in address
lsr x4,x4,#4 // shift mask 4 bits left
subs x2,x2,#4 // decrement counter 4 bits <= zero ?
bge 1b // no -> loop
100: // fin standard de la fonction
ldp x3,x4,[sp,16] // restaur des 2 registres
ldp x1,x2,[sp,32] // restaur des 2 registres
ldp x0,lr,[sp],48 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Arturo | Arturo | loop 32..127 'num [
k: ø
case [num]
when? [=32] -> k: "␠"
when? [=127] -> k: "␡"
else -> k: to :string to :char num
prints pad ~"|num|: |k|" 10
if 1 = num%6 -> print ""
] |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #Ruby | Ruby | require 'date'
require 'json'
require 'securerandom'
class SimpleDatabase
def initialize(dbname, *fields)
@dbname = dbname
@filename = @dbname + ".dat"
@fields = fields
@maxl = @fields.collect {|f| f.length}.max
@data = {
'fields' => fields,
'items' => {},
'history' => [],
'tags' => {},
}
end
attr_reader :dbname, :fields
def self.open(dbname)
db = new(dbname)
db.read
db
end
def read()
if not File.exists?(@filename)
raise ArgumentError, "Database #@dbname has not been created"
end
@data = JSON.parse(File.read(@filename))
@fields = @data['fields']
@maxl = @fields.collect {|f| f.length}.max
end
def write()
File.open(@filename, 'w') {|f| f.write(JSON.generate(@data))}
end
def add(*values)
id = SecureRandom.uuid
@data['items'][id] = Hash[ @fields.zip(values) ]
@data['history'] << [Time.now.to_f, id]
id
end
def tag(id, *tags)
tags.each do |tag|
if @data['tags'][tag].nil?
@data['tags'][tag] = [id]
else
@data['tags'][tag] << id
end
end
id
end
def latest
@data['history'].sort_by {|val| val[0]}.last.last
end
def get_item(id)
@data['items'][id]
end
def tags()
@data['tags'].keys.sort
end
def ids_for_tag(tag)
@data['tags'][tag]
end
def tags_for_id(id)
@data['tags'].keys.inject([]) do |tags, tag|
tags << tag if @data['tags'][tag].include?(id)
tags
end
end
def display(id)
item = get_item(id)
fmt = "%#{@maxl}s - %s\n"
puts fmt % ['id', id]
@fields.each {|f| print fmt % [f, item[f]]}
puts fmt % ['tags', tags_for_id(id).join(',')]
added = @data['history'].find {|x| x[1] == id}.first
puts fmt % ['date added', Time.at(added).ctime]
puts ""
end
def each()
@data['history'].each {|time, id| yield id}
end
def each_item_with_tag(tag)
@data['tags'][tag].each {|id| yield id}
end
end
def usage()
puts <<END
usage: #{$0} command args ...
commands:
help
create dbname field ...
fields dbname
add dbname value ...
tag dbname id tag ...
tags dbname
list dbname [tag ...]
latest dbname
latest_by_tag dbname
END
end
def open_database(args)
dbname = args.shift
begin
SimpleDatabase.open(dbname)
rescue ArgumentError => e
STDERR.puts e.message
exit 1
end
end
def process_command_line(command, *args)
case command
when 'help'
usage
when 'create'
db = SimpleDatabase.new(*args)
db.write
puts "Database #{args[0]} created"
when 'fields'
db = open_database(args)
puts "Database #{db.dbname} fields:"
puts db.fields.join(',')
when 'add'
db = open_database(args)
id = db.add(*args)
db.write
puts "Database #{db.dbname} added id #{id}"
when 'tag'
db = open_database(args)
id = args.shift
db.tag(id, *args)
db.write
db.display(id)
when 'tags'
db = open_database(args)
puts "Database #{db.dbname} tags:"
puts db.tags.join(',')
when 'list'
db = open_database(args)
if args.empty?
db.each {|id| db.display(id)}
else
args.each do |tag|
puts "Items tagged #{tag}"
db.each_item_with_tag(tag) {|id| db.display(id)}
end
end
when 'latest'
db = open_database(args)
db.display(db.latest)
when 'latest_by_tag'
db = open_database(args)
db.tags.each do |tag|
puts tag
db.display(db.ids_for_tag(tag).last)
end
else
puts "Error: unknown command '#{command}'"
usage
end
end
process_command_line *ARGV |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Groovy | Groovy | def stPoints;
stPoints = { order, base=[0,0] ->
def right = [base[0], base[1]+2**order]
def up = [base[0]+2**(order-1), base[1]+2**(order-1)]
(order == 0) \
? [base]
: (stPoints(order-1, base) + stPoints(order-1, right) + stPoints(order-1, up))
}
def stGrid = { order ->
def h = 2**order
def w = 2**(order+1) - 1
def grid = (0..<h).collect { (0..<w).collect { ' ' } }
stPoints(order).each { grid[it[0]][it[1]] = (order%10).toString() }
grid
} |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Common_Lisp | Common Lisp | (defun print-carpet (order)
(let ((size (expt 3 order)))
(flet ((trinary (x) (format nil "~3,vR" order x))
(ones (a b) (and (eql a #\1) (eql b #\1))))
(loop for i below size do
(fresh-line)
(loop for j below size do
(princ (if (some #'ones (trinary i) (trinary j))
" "
"#"))))))) |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Lua | Lua | function shoeArea(ps)
local function det2(i,j)
return ps[i][1]*ps[j][2]-ps[j][1]*ps[i][2]
end
local sum = #ps>2 and det2(#ps,1) or 0
for i=1,#ps-1 do sum = sum + det2(i,i+1)end
return math.abs(0.5 * sum)
end |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Maple | Maple |
with(ArrayTools):
module Point()
option object;
local x := 0;
local y := 0;
export getX::static := proc(self::Point, $)
return self:-x;
end proc;
export getY::static := proc(self::Point, $)
return self:-y
end proc;
export ModuleApply::static := proc()
Object(Point, _passed);
end proc;
export ModuleCopy::static := proc(new::Point, proto::Point, X, Y, $)
new:-x := X;
new:-y := Y;
end proc;
export ModulePrint::static := proc(self::Point)
return cat("(", self:-x, ",", self:-y, ")");
end proc;
end module:
module Polygon()
option object;
local vertices := Array([Point(0,0)]);
export getVertices::static := proc(self::Polygon)
return self:-vertices;
end proc;
export area::static := proc(self::Polygon)
local i, N := ArrayNumElems(self:-vertices);
local total := getX(self:-vertices[N]) * getY(self:-vertices[1]) - getX(self:-vertices[1]) * getY(self:-vertices[N]);
total += map(`+`, seq(getX(self:-vertices[i]) * getY(self:-vertices[i+1]), i = 1..(N-1))) - map(`+`, seq(getX(self:-vertices[i+1]) * getY(self:-vertices[i]), i = 1..(N-1)));
return abs(total / 2);
end proc;
export ModuleApply::static := proc()
Object(Polygon, _passed);
end proc;
export ModuleCopy::Static := proc(new::Polygon, proto::Polygon, Ps, $)
new:-vertices := Ps;
end proc;
export ModulePrint::static := proc(self::Polygon)
return self:-vertices;
end proc;
end module:
P1 := Polygon(Array([Point(3,4), Point(5,11), Point(12,8), Point(9,5), Point(5,6)])):
area(P1);
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #JavaScript | JavaScript | $ js -e 'print("hello")'
hello |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #jq | jq | $ jq -M -n 1+1
2 |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Julia | Julia | $ julia -e 'for x in ARGS; println(x); end' foo bar
foo
bar |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #C.23 | C# | using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
} |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program merkleRoot.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ READ, 3
.equ OPEN, 5
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ BUFFERSIZE, 65535 @ file buffer
.equ LGBLOCK, 1024 @ block length
.equ LGHASH, 32 @ hash length
.equ NBELEMENTS, 40 @ array size
.equ LGZONETRAV, 2048 @ process array size
/*******************************************/
/* Structures */
/********************************************/
/* structure variables hash compute */
.struct 0
var_a: @ a
.struct var_a + 4
var_b: @ b
.struct var_b + 4
var_c: @ c
.struct var_c + 4
var_d: @ d
.struct var_d + 4
var_e: @ e
.struct var_e + 4
var_f: @ f
.struct var_f + 4
var_g: @ g
.struct var_g + 4
var_h: @ h
.struct var_h + 4
/* structure linkedlist*/
.struct 0
@llist_next: @ next element
@ .struct llist_next + 4
@llist_value: @ element value
@ .struct llist_value + 4
@llist_fin:
/***********************************/
/* Initialized data */
/***********************************/
.data
szFileName: .asciz "title.png"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "Error detected.\n"
szMessNbHash: .asciz "Start hash number : @ \n"
.align 4
/* array constantes Hi */
tbConstHi: .int 0x6A09E667 @ H0
.int 0xBB67AE85 @ H1
.int 0x3C6EF372 @ H2
.int 0xA54FF53A @ H3
.int 0x510E527F @ H4
.int 0x9B05688C @ H5
.int 0x1F83D9AB @ H6
.int 0x5BE0CD19 @ H7
/* array 64 constantes Kt */
tbConstKt:
.int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
/***********************************/
/* UnInitialized data */
/***********************************/
.bss
sBuffer: .skip BUFFERSIZE @ file buffer
.align 4
iNbBlocs: .skip 4
iNbHash: .skip 4
sZoneConv: .skip 24
sZoneTrav: .skip LGZONETRAV
HashResult: .skip LGHASH + 4
HashProcess: .skip LGHASH * 2
.align 8
tbListHash: .skip LGHASH * NBELEMENTS
tbH: .skip 4 * 8 @ 8 variables H
tbabcdefgh: .skip 4 * 8
tbW: .skip 4 * 64 @ 64 words W
/***********************************/
/* code section */
/***********************************/
.text
.global main
main:
ldr r0,iAdrszFileName @ File name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ open file
svc #0
cmp r0,#0 @ error ?
ble error
mov r12,r0 @ save fd
ldr r1,iAdrsBuffer
mov r2,#BUFFERSIZE
mov r7,#READ @ call system read file
svc 0
cmp r0,#0 @ error read ?
ble error
mov r7,r0 @ number of read characters
ldr r6,iAdrsBuffer
mov r5,#0 @ counter characters block
1:
add r0,r6,r5 @ start address of each block
mov r1,#LGBLOCK
bl computeSHA256
bl storeHash @ store hash in start array
cmp r0,#-1
beq error
add r5,#LGBLOCK @ new buffer offset
sub r0,r7,r5 @
cmp r0,#LGBLOCK @ last block
bge 1b @ and loop
sub r1,r7,r5 @ length last block
add r0,r6,r5 @ address last block
bl computeSHA256
bl storeHash
cmp r0,#-1
beq error
ldr r0,iAdriNbHash
ldr r0,[r0]
ldr r1,iAdrsZoneConv
bl conversion10
ldr r0,iAdrszMessNbHash
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
ldr r0,iAdrtbListHash
ldr r1,iAdrHashResult
bl calculerMerkleRoot
ldr r0,iAdrHashResult
bl displaySHA256 @ display résult
end:
mov r0,r12 @ FD
mov r7, #CLOSE @ call system close file
svc #0
cmp r0,#0
blt error
mov r0,#0 @ return code
b 100f
error:
ldr r1,iAdrszMessErreur @ error message
bl displayError
mov r0,#1 @ return error code
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrsBuffer: .int sBuffer
iAdrszFileName: .int szFileName
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrHashResult: .int HashResult
iAdrszMessNbHash: .int szMessNbHash
/******************************************************************/
/* store hash in start array */
/******************************************************************/
/* r0 hash address */
storeHash:
push {r1-r5,lr}
ldr r2,iAdriNbHash @ number element counter
ldr r3,[r2]
ldr r1,iAdrtbListHash @ address array hash
mov r4,#LGHASH @ hash length
mla r5,r4,r3,r1 @ compute store address
mov r1,#0 @ counter
1:
ldr r4,[r0,r1] @ load four bytes
str r4,[r5,r1] @ store four bytes
add r1,#4
cmp r1,#LGHASH @ 32 bytes ?
blt 1b @ no -> loop
add r3,#1
cmp r3,#NBELEMENTS
movge r0,#-1 @ error ?
bge 100f
str r3,[r2] @ store new counter hash
100:
pop {r1-r5,lr} @ restaur registers
bx lr
iAdriNbHash: .int iNbHash
iAdrtbListHash: .int tbListHash
/******************************************************************/
/* compute hash root Merkle */
/******************************************************************/
@ r0 start array hash address
@ r1 result array address (32 bytes)
calculerMerkleRoot:
push {r1-r12,lr} @ save registers
mov r10,r1
mov r12,sp @ save stack adresse
ldr r3,iAdriNbHash
ldr r3,[r3]
cmp r3,#0 @ 0 hash ?
moveq r0,#-1 @ error
beq 100f
mov r4,#LGHASH * 2
mul r1,r3,r4 @ compute hash size * blocks number * 2
sub sp,sp,r1 @ reserve array
mov fp,sp @ address previousTreeLayer
lsr r1,#1 @ reserve size / 2
add r7,fp,r1 @ address TreeLayer
mov r2,#0 @ counter
mov r4,#LGHASH
1:
mul r1,r2,r4
add r6,r0,r1
add r8,fp,r1
mov r5,#0
2: @ loop copying 32 octets hash
ldr r9,[r6,r5]
str r9,[r8,r5]
add r5,r5,#4 @ count
cmp r5,#LGHASH
blt 2b
add r2,#1 @ next hash block
cmp r2,r3 @ maxi ?
blt 1b
mov r0,fp
mov r2,#0 @ indice TreeLayer
mov r5,#0 @ indice layer
3: @ loop
cmp r3,#1 @ one hash ?
beq 12f @ yes -> end
sub r3,#1
mov r4,#LGHASH
mla r8,r2,r4,fp @ address hash 1
mov r9,r7 @ raz TreeLayer
4:
cmp r2,r3
bgt 11f @ end loop ?
blt 5f
mov r0,r8 @ last odd hash
add r2,#1 @ no concatenation
b 9f
5: @ other hashes
add r6,r8,#LGHASH @ address hash N + 1
6:
add r2,#1
ldr r1,iAdrHashProcess @ address array hash concatenation
mov r0,#0
7: @ loop copy element N
ldr r4,[r8,r0]
rev r4,r4 @ inversion byte in word
str r4,[r1,r0]
add r0,r0,#4
cmp r0,#LGHASH
blt 7b
add r1,r1,#LGHASH
mov r0,#0
8: @ loop copy element N + 1
ldr r4,[r6,r0]
rev r4,r4 @ inversion byte in word
str r4,[r1,r0]
add r0,r0,#4
cmp r0,#LGHASH
blt 8b
ldr r0,iAdrHashProcess
mov r1,#LGHASH * 2
bl computeSHA256 @ calcul du hash complet
9:
mov r1,#0
10: @ loop copy hash in treelayer
ldr r4,[r0,r1]
str r4,[r9,r1]
add r1,r1,#4
cmp r1,#LGHASH
blt 10b
mov r1,r9
add r2,r2,#1 @ incremente counter previousTreeLayer
add r5,r5,#1 @ incremente counter treeLayer
add r9,#LGHASH @ next address treeLayer
add r8,r6,#LGHASH @ maj element N avec N + 2
b 4b
11:
mov r0,fp
mov fp,r7 @ treelayer in previous
mov r7,r0
mov r3,r5 @ counter previous = counter treelayer
mov r5,#0 @ raz treelayer
mov r2,#0 @ raz previousTreeLayer
b 3b @ and loop
12: @ end process
mov r1,fp
mov r2,#0
13: @ loop copy result
ldr r3,[r1,r2]
str r3,[r10,r2]
add r2,r2,#4
cmp r2,#LGHASH
blt 13b
mov r0,r10 @ return address result
b 100f
99: @ error
mov r0,#-1
100:
mov sp,r12 @ restaur stack
pop {r1-r12,lr} @ restaur registers
bx lr @ return
iAdrHashProcess: .int HashProcess
/******************************************************************/
/* compute SHA1 */
/******************************************************************/
/* r0 contains the address of the message */
/* r1 contains string length */
computeSHA256:
push {r1-r12,lr} @ save registres
mov r5,r1 @ counter length
ldr r1,iAdrtbH
mov r3,#0
mov r4,#0
razTB:
str r4,[r1,r3]
add r3,#4
cmp r3,#8 + 8 + 64
blt razTB
ldr r1,iAdrsZoneTrav
mov r3,#0
mov r4,#0
razZone:
str r4,[r1,r3]
add r3,#4
cmp r3,#LGZONETRAV
blt razZone
@vidregtit apresraz
mov r2,#0
debCopy: @ copy string in work area
ldrb r3,[r0,r2]
strb r3,[r1,r2]
cmp r2,r5
addne r2,r2,#1
bne debCopy
@vidregtit aprescopie
lsl r6,r2,#3 @ initial message length in bits
mov r3,#0b10000000 @ add bit 1 at end of string
strb r3,[r1,r2]
add r2,r2,#1 @ length in bytes
lsl r4,r2,#3 @ length in bits
mov r3,#0
addZeroes:
lsr r5,r2,#6
lsl r5,r5,#6
sub r5,r2,r5
cmp r5,#56
beq storeLength @ yes -> end add
strb r3,[r1,r2] @ add zero at message end
add r2,#1 @ increment lenght bytes
add r4,#8 @ increment length in bits
b addZeroes
storeLength:
add r2,#4 @ add four bytes
rev r6,r6 @ inversion bits initials message length
str r6,[r1,r2] @ and store at end
ldr r7,iAdrtbConstHi @ constantes H address
ldr r4,iAdrtbH @ start area H
mov r5,#0
loopConst: @ init array H with start constantes
ldr r6,[r7,r5,lsl #2] @ load constante
str r6,[r4,r5,lsl #2] @ and store
add r5,r5,#1
cmp r5,#8
blt loopConst
@ split into block of 64 bytes
add r2,#4 @ TODO : à revoir
lsr r4,r2,#6 @ blocks number
ldr r0,iAdriNbBlocs
str r4,[r0] @ save block maxi
mov r7,#0 @ n° de block et r1 contient l adresse zone de travail
loopBlock: @ begin loop of each block of 64 bytes
mov r0,r7
bl inversion @ inversion each word because little indian
ldr r3,iAdrtbW @ working area W address
mov r6,#0 @ indice t
/* r2 address begin each block */
ldr r1,iAdrsZoneTrav
add r2,r1,r7,lsl #6 @ compute block begin indice * 4 * 16
@vidregtit avantloop
@mov r0,r2
@vidmemtit verifBloc r0 10
loopPrep: @ loop for expand 80 words
cmp r6,#15 @
bgt expand1
ldr r0,[r2,r6,lsl #2] @ load byte message
str r0,[r3,r6,lsl #2] @ store in first 16 block
b expandEnd
expand1:
sub r8,r6,#2
ldr r9,[r3,r8,lsl #2]
ror r10,r9,#17 @ fonction e1 (256)
ror r11,r9,#19
eor r10,r10,r11
lsr r11,r9,#10
eor r10,r10,r11
sub r8,r6,#7
ldr r9,[r3,r8,lsl #2]
add r9,r9,r10 @ + w - 7
sub r8,r6,#15
ldr r10,[r3,r8,lsl #2]
ror r11,r10,#7 @ fonction e0 (256)
ror r12,r10,#18
eor r11,r12
lsr r12,r10,#3
eor r10,r11,r12
add r9,r9,r10
sub r8,r6,#16
ldr r11,[r3,r8,lsl #2]
add r9,r9,r11
str r9,[r3,r6,lsl #2]
expandEnd:
add r6,r6,#1
cmp r6,#64 @ 64 words ?
blt loopPrep @ and loop
/* COMPUTING THE MESSAGE DIGEST */
/* r1 area H constantes address */
/* r3 working area W address */
/* r5 address constantes K */
/* r6 counter t */
/* r7 block counter */
/* r8 addresse variables a b c d e f g h */
@ldr r0,iAdrtbW
@vidmemtit verifW80 r0 20
@ init variable a b c d e f g h
ldr r0,iAdrtbH
ldr r8,iAdrtbabcdefgh
mov r1,#0
loopInita:
ldr r9,[r0,r1,lsl #2]
str r9,[r8,r1,lsl #2]
add r1,r1,#1
cmp r1,#8
blt loopInita
ldr r1,iAdrtbConstHi
ldr r5,iAdrtbConstKt
mov r6,#0
loop64T: @ begin loop 64 t
ldr r9,[r8,#var_h]
ldr r10,[r8,#var_e] @ calcul T1
ror r11,r10,#6 @ fonction sigma 1
ror r12,r10,#11
eor r11,r12
ror r12,r10,#25
eor r11,r12
add r9,r9,r11 @ h + sigma1 (e)
ldr r0,[r8,#var_f] @ fonction ch x and y xor (non x and z)
ldr r4,[r8,#var_g]
and r11,r10,r0
mvn r12,r10
and r12,r12,r4
eor r11,r12
add r9,r9,r11 @ h + sigma1 (e) + ch (e,f,g)
ldr r0,[r5,r6,lsl #2] @ load constantes k0
add r9,r9,r0
ldr r0,[r3,r6,lsl #2] @ Wt
add r9,r9,r0
@ calcul T2
ldr r10,[r8,#var_a] @ fonction sigma 0
ror r11,r10,#2
ror r12,r10,#13
eor r11,r11,r12
ror r12,r10,#22
eor r11,r11,r12
ldr r2,[r8,#var_b]
ldr r4,[r8,#var_c]
@ fonction maj x and y xor x and z xor y and z
and r12,r10,r2
and r0,r10,r4
eor r12,r12,r0
and r0,r2,r4
eor r12,r12,r0 @
add r12,r12,r11 @ T2
@ compute variables
ldr r4,[r8,#var_g]
str r4,[r8,#var_h]
ldr r4,[r8,#var_f]
str r4,[r8,#var_g]
ldr r4,[r8,#var_e]
str r4,[r8,#var_f]
ldr r4,[r8,#var_d]
add r4,r4,r9 @ add T1
str r4,[r8,#var_e]
ldr r4,[r8,#var_c]
str r4,[r8,#var_d]
ldr r4,[r8,#var_b]
str r4,[r8,#var_c]
ldr r4,[r8,#var_a]
str r4,[r8,#var_b]
add r4,r9,r12 @ add T1 T2
str r4,[r8,#var_a]
mov r0,r8
add r6,r6,#1 @ increment t
cmp r6,#64
blt loop64T
@ End block
ldr r0,iAdrtbH @ start area H
mov r10,#0
loopStoreH:
ldr r9,[r8,r10,lsl #2]
ldr r3,[r0,r10,lsl #2]
add r3,r9
str r3,[r0,r10,lsl #2] @ store variables in H0
add r10,r10,#1
cmp r10,#8
blt loopStoreH
@ other bloc
add r7,#1 @ increment block
ldr r0,iAdriNbBlocs
ldr r4,[r0] @ restaur maxi block
cmp r7,r4 @ maxi ?
blt loopBlock @ loop other block
ldr r0,iAdrtbH @ return result area H
100:
pop {r1-r12,lr} @ restaur registers
bx lr @ return
iAdrtbConstHi: .int tbConstHi
iAdrtbConstKt: .int tbConstKt
iAdrtbH: .int tbH
iAdrtbW: .int tbW
iAdrtbabcdefgh: .int tbabcdefgh
iAdriNbBlocs: .int iNbBlocs
iAdrsZoneTrav: .int sZoneTrav
/******************************************************************/
/* inversion des mots de 32 bits d un bloc */
/******************************************************************/
/* r0 contains N° block */
inversion:
push {r1-r3,lr} @ save registers
ldr r1,iAdrsZoneTrav
add r1,r0,lsl #6 @ debut du bloc
mov r2,#0
1: @ start loop
ldr r3,[r1,r2,lsl #2]
rev r3,r3
str r3,[r1,r2,lsl #2]
add r2,r2,#1
cmp r2,#16
blt 1b
100:
pop {r1-r3,lr} @ restaur registres
bx lr @return
/******************************************************************/
/* display hash SHA256 */
/******************************************************************/
/* r0 contains the address of hash */
displaySHA256:
push {r1-r3,lr} @ save registres
mov r3,r0
mov r2,#0
1:
ldr r0,[r3,r2,lsl #2] @ load 4 bytes
@rev r0,r0 @ reverse bytes
ldr r1,iAdrsZoneConv
bl conversion16 @ conversion hexa
mov r4,#0
strb r4,[r1,r0] @ 0 final
ldr r0,iAdrsZoneConv
bl affichageMess
add r2,r2,#1
cmp r2,#LGHASH / 4
blt 1b @ and loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | AutoTrim,Off ;Allows for whitespace at end of variable to separate converted characters
MessageText := ;The text to display in the final message box.
CurrentASCII := 32 ;Current ASCII number to convert and add to MessageText
ConvertedCharacter := ;Stores the currently converted ASCII code
RowLength := 0 ;Keeps track of the number of converted ASCII numbers in each row
Loop { ;Loops through each ASCII character and makes a list in MessageText
if CurrentASCII > 127 ;When the current ASCII number goes over 127, terminate the loop
Break
if (RowLength = 6) { ;Checks if the row is 6 converted characters long, and if so, inserts a line break (`n)
MessageText = %MessageText%`n
RowLength := 0
}
if (CurrentASCII = 32) {
ConvertedCharacter = SPC
} else {
if (CurrentASCII = 127) {
ConvertedCharacter = DEL
}
else {
ConvertedCharacter := Chr(CurrentASCII) ;Converts CurrentASCII number using Chr() and stores it in ConvertedCharacter
}
}
MessageText = %MessageText%%CurrentASCII%: %ConvertedCharacter%`t ;Adds converted ASCII to end of MessageText
CurrentASCII := CurrentASCII + 1
RowLength := RowLength + 1
}
MsgBox, % MessageText ;Displays a message box with the ASCII conversion table, from the MessageText variable
return |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #Run_BASIC | Run BASIC | sqliteconnect #sql, "f:\client.db" ' Connect to the DB
' -------------------------------
' show user options
' -------------------------------
[sho]
cls ' clear screen
button #acd, "Add a new entry", [add]
button #acd, "Print the latest entry", [last]
button #acd, "Print the latest entry for each category", [lastCat]
button #acd, "Print all entries sorted by a date", [date]
button #ex, "Exit", [exit]
wait
' ------------------------------------
' add a new entry (user input screen)
' ------------------------------------
[add]
cls ' clear the screen
html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 bgcolor=wheat>"
html "<TR align=center BGCOLOR=tan><TD colspan=2>Client Maintenance</TD></TR><TR>"
html "<TD bgcolor=tan align=right>Client Num</TD><TD>"
textbox #clientNum,clientNum$,5
html "</TD></TR><TR><TD bgcolor=tan align=right>Name</TD><TD>"
textbox #name,name$,30
html "</TD></TR><TR><TD bgcolor=tan align=right>Client Date</TD><TD>"
textbox #clientDate,clientDate$,19
html "</TD></TR><TR><TD bgcolor=tan align=right>Category</TD><TD>"
textbox #category,category$,10
html "</TD></TR><TR><TR bgcolor=tan><TD colspan=2 ALIGN=CENTER>"
button #acd, "Add", [addIt]
button #ex, "Exit", [sho]
html "</TD></TR></TABLE>"
wait
' ---------------------------------------------
' Get data from the screen
' ---------------------------------------------
[addIt]
clientNum = #clientNum contents$()
name$ = trim$(#name contents$())
clientDate$ = trim$(#clientDate contents$())
category$ = trim$(#category contents$())
dbVals$ = clientNum;",'";name$;"','";clientDate$;"','";category$;"'"
sql$ = "INSERT into client VALUES ("; dbVals$ ; ")"
#sql execute(sql$)
goto [sho]
' ------------------------------------
' Select last entry
' ------------------------------------
[last]
sql$ = "SELECT *,client.rowid as rowid FROM client ORDER BY rowid desc LIMIT 1"
what$ = "---- Last Entry ----"
goto [shoQuery]
' ------------------------------------
' Select by category (Last date only)
' ------------------------------------
[lastCat]
sql$ = "SELECT * FROM client
WHERE client.clientDate = (SELECT max(c.clientDate)
FROM client as c WHERE c.category = client.category)
ORDER BY category"
what$ = "---- Last Category Sequence ----"
goto [shoQuery]
' ------------------------------------
' Select by date
' ------------------------------------
[date]
sql$ = "SELECT * FROM client ORDER BY clientDate"
what$ = "---- By Date ----"
[shoQuery]
cls
print what$
html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0>"
html "<TR align=center bgcolor=wheat><TD>Client<br>Num</TD><TD>Name</TD><TD>Client<br>Date</TD><TD>Category</TD></TR>" ' heading
#sql execute(sql$)
WHILE #sql hasanswer()
#row = #sql #nextrow()
clientNum = #row clientNum()
name$ = #row name$()
clientDate$ = #row clientDate$()
category$ = #row category$()
html "<TR><TD align=right>";clientNum;"</TD><TD>";name$;"</TD><TD>";clientDate$;"</TD><TD>";category$;"</TD></TR>"
WEND
html "</TABLE>"
button #c, "Continue", [sho]
wait
' ------ the end -------
[exit]
end |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Haskell | Haskell | sierpinski 0 = ["*"]
sierpinski n = map ((space ++) . (++ space)) down ++
map (unwords . replicate 2) down
where down = sierpinski (n - 1)
space = replicate (2 ^ (n - 1)) ' '
main = mapM_ putStrLn $ sierpinski 4 |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Crystal | Crystal | def sierpinski_carpet(n)
carpet = ["#"]
n.times do
carpet = carpet.map { |x| x + x + x } +
carpet.map { |x| x + x.tr("#"," ") + x } +
carpet.map { |x| x + x + x }
end
carpet
end
5.times{ |i| puts "\nN=#{i}"; sierpinski_carpet(i).each { |row| puts row } } |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Area[Polygon[{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}}]] |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #min | min | ((((first) map) ((last) map)) cleave) :dezip
(((first) (rest)) cleave append) :rotate
((0 <) (-1 *) when) :abs
(
=b =a a size :n 0 :i () =list
(i n <) (
a i get b i get ' prepend list append #list
i succ @i
) while list
) :rezip
(rezip (-> *) map sum) :cross-sum
(
((dezip rotate) (dezip swap rotate)) cleave
((id) (cross-sum) (id) (cross-sum)) spread
- abs 2 /
) :shoelace
((3 4) (5 11) (12 8) (9 5) (5 6)) shoelace print |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #MiniScript | MiniScript | shoelace = function(vertices)
sum = 0
points = vertices.len
for i in range(0,points-2)
sum = sum + vertices[i][0]*vertices[i+1][1]
end for
sum = sum + vertices[points-1][0]*vertices[0][1]
for i in range(points-1,1)
sum = sum - vertices[i][0]*vertices[i-1][1]
end for
sum = sum - vertices[0][0]*vertices[points-1][1]
return abs(sum)/2
end function
verts = [[3,4],[5,11],[12,8],[9,5],[5,6]]
print "The polygon area is " + shoelace(verts)
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #K | K | $ k -e "\`0: \"hello\\n\"" |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Kotlin | Kotlin | echo 'fun main(args: Array<String>) = println("Hello Kotlin!")' >X.kt;kotlinc X.kt -include-runtime -d X.jar && java -jar X.jar
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Lasso | Lasso | echo " 'The date and time is: ' + date " | lasso9 -- |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #C.2B.2B | C++ | #include <iostream>
bool a(bool in)
{
std::cout << "a" << std::endl;
return in;
}
bool b(bool in)
{
std::cout << "b" << std::endl;
return in;
}
void test(bool i, bool j) {
std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl;
std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl;
}
int main()
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
} |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #C | C | #include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
guchar* sha256_merkle_tree(FILE* in, size_t block_size) {
gchar* buffer = g_malloc(block_size);
GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);
gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);
size_t bytes;
while ((bytes = fread(buffer, 1, block_size, in)) > 0) {
g_checksum_reset(checksum);
g_checksum_update(checksum, (guchar*)buffer, bytes);
gsize len = digest_length;
guchar* digest = g_malloc(len);
g_checksum_get_digest(checksum, digest, &len);
g_ptr_array_add(hashes, digest);
}
g_free(buffer);
guint hashes_length = hashes->len;
if (hashes_length == 0) {
g_ptr_array_free(hashes, TRUE);
g_checksum_free(checksum);
return NULL;
}
while (hashes_length > 1) {
guint j = 0;
for (guint i = 0; i < hashes_length; i += 2, ++j) {
guchar* digest1 = g_ptr_array_index(hashes, i);
guchar* digest_out = g_ptr_array_index(hashes, j);
if (i + 1 < hashes_length) {
guchar* digest2 = g_ptr_array_index(hashes, i + 1);
g_checksum_reset(checksum);
g_checksum_update(checksum, digest1, digest_length);
g_checksum_update(checksum, digest2, digest_length);
gsize len = digest_length;
g_checksum_get_digest(checksum, digest_out, &len);
} else {
memcpy(digest_out, digest1, digest_length);
}
}
hashes_length = j;
}
guchar* result = g_ptr_array_steal_index(hashes, 0);
g_ptr_array_free(hashes, TRUE);
g_checksum_free(checksum);
return result;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return EXIT_FAILURE;
}
FILE* in = fopen(argv[1], "rb");
if (in) {
guchar* digest = sha256_merkle_tree(in, 1024);
fclose(in);
if (digest) {
gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
for (gssize i = 0; i < length; ++i)
printf("%02x", digest[i]);
printf("\n");
g_free(digest);
}
} else {
perror(argv[1]);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK | # syntax: GAWK -f SHOW_ASCII_TABLE.AWK
# syntax: MAWK -f SHOW_ASCII_TABLE.AWK
BEGIN {
for (i=0; i<16; i++) {
for (j=32+i; j<128; j+=16) {
if (j == 32) { x = "SPC" }
else if (j == 127) { x = "DEL" }
else { x = sprintf("%c",j) }
printf("%3d: %-5s",j,x)
}
print ""
}
} |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #Scala | Scala | object SimpleDatabase extends App {
type Entry = Array[String]
def asTSV(e: Entry) = e mkString "\t"
def fromTSV(s: String) = s split "\t"
val header = asTSV(Array("TIMESTAMP", "DESCRIPTION", "CATEGORY", "OTHER"))
def read(filename: String) = try {
scala.io.Source.fromFile(filename).getLines.drop(1).map(fromTSV)
} catch {
case e: java.io.FileNotFoundException => Nil
}
def write(filename: String, all: Seq[Entry]) = {
import java.nio.file.{Files,Paths}
import scala.collection.JavaConversions.asJavaIterable
Files.write(Paths.get(filename), asJavaIterable(header +: all.map(asTSV)))
all.size
}
def add(filename: String, description: String, category: String = "none", optional: Seq[String] = Nil) {
val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val e = Array(format.format(new java.util.Date), description, category) ++ optional
println(write(filename, read(filename).toBuffer :+ e) + " entries")
}
def print(filename: String, filter: Seq[Entry] => TraversableOnce[Entry]) =
filter(read(filename).toList.sortBy(_.headOption)) map(_ mkString ",") foreach println
args match {
case Array(f, "latest") => print(f, _ takeRight 1)
case Array(f, "latest", cat) => print(f, _ filter(_.lift(2) == Some(cat)) takeRight 1)
case Array(f, "all") => print(f, _.toSeq)
case Array(f, "all", "latest") => print(f, _ groupBy (_ lift 2 getOrElse "") map{case (_, cat) => cat.last})
case Array(f, "add", desc) => add(f, desc, category = "")
case Array(f, "add", desc, cat, opt @ _*) => add(f, desc, cat, opt)
case _ => println("Usage: SimpleDatabase filename.tsv [all [latest]| latest [CATEGORY] | add [DESCRIPTION [CATEGORY [OPTIONAL]...]]]")
}
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Haxe | Haxe | class Main
{
static function main()
{
triangle(3);
}
static inline var SPACE = ' ';
static inline var STAR = '*';
static function triangle(o) {
var n = 1 << o;
var line = new Array<String>();
for (i in 0...(n*2)) line[i] = SPACE;
line[n] = '*';
for (i in 0...n) {
Sys.println(line.join(''));
var u ='*';
var start = n - i;
var end = n + i + 1;
var t = SPACE;
for (j in start...end) {
t = (line[j-1] == line[j+1] ? SPACE : STAR);
line[j-1] = u;
u = t;
}
line[n+i] = t;
line[n+i+1] = STAR;
}
}
} |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #D | D | import std.stdio, std.string, std.algorithm, std.array;
auto sierpinskiCarpet(in int n) pure nothrow @safe {
auto r = ["#"];
foreach (immutable _; 0 .. n) {
const p = r.map!q{a ~ a ~ a}.array;
r = p ~ r.map!q{a ~ a.replace("#", " ") ~ a}.array ~ p;
}
return r.join('\n');
}
void main() {
3.sierpinskiCarpet.writeln;
} |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Modula-2 | Modula-2 | MODULE ShoelaceFormula;
FROM RealStr IMPORT RealToStr;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE
Point = RECORD
x,y : INTEGER;
END;
PROCEDURE PointToString(self : Point; VAR buf : ARRAY OF CHAR);
BEGIN
FormatString("(%i, %i)", buf, self.x, self.y);
END PointToString;
PROCEDURE ShoelaceArea(v : ARRAY OF Point) : REAL;
VAR
a : REAL;
i,n : INTEGER;
BEGIN
n := HIGH(v);
a := 0.0;
FOR i:=0 TO n-1 DO
a := a + FLOAT(v[i].x * v[i+1].y - v[i+1].x * v[i].y);
END;
RETURN ABS(a + FLOAT(v[n].x * v[0].y - v[0].x * v[n].y)) / 2.0;
END ShoelaceArea;
VAR
v : ARRAY[0..4] OF Point;
buf : ARRAY[0..63] OF CHAR;
area : REAL;
i : INTEGER;
BEGIN
v[0] := Point{3,4};
v[1] := Point{5,11};
v[2] := Point{12,8};
v[3] := Point{9,5};
v[4] := Point{5,6};
area := ShoelaceArea(v);
WriteString("Given a polygon with verticies ");
FOR i:=0 TO HIGH(v) DO
PointToString(v[i], buf);
WriteString(buf);
WriteString(" ");
END;
WriteLn;
RealToStr(area, buf);
WriteString("its area is ");
WriteString(buf);
WriteLn;
ReadChar;
END ShoelaceFormula. |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Liberty_BASIC | Liberty BASIC |
echo print "hello">oneLiner.bas & liberty -r oneLiner.bas echo print "hello">oneLiner.bas & liberty -r oneLiner.bas
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Lua | Lua | lua -e 'print "Hello World!"' |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Maple | Maple | maple -c'print(HELLO);' -cquit |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Clojure | Clojure | (letfn [(a [bool] (print "(a)") bool)
(b [bool] (print "(b)") bool)]
(doseq [i [true false] j [true false]]
(print i "OR" j "= ")
(println (or (a i) (b j)))
(print i "AND" j " = ")
(println (and (a i) (b j))))) |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sha1_64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ SHA_DIGEST_LENGTH, 20
//.include "../../ficmacros64.s"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRosetta: .asciz "Rosetta Code"
szMessTest1: .asciz "abc"
szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ascii "abcdefghijklmnopqrstuvwxyz"
.asciz "1234567890AZERTYUIOP"
szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
szMessFinPgm: .asciz "Program End ok.\n"
szMessResult: .asciz "Rosetta Code => "
szCarriageReturn: .asciz "\n"
/* array constantes Hi */
tbConstHi: .int 0x67452301 // H0
.int 0xEFCDAB89 // H1
.int 0x98BADCFE // H2
.int 0x10325476 // H3
.int 0xC3D2E1F0 // H4
/* array constantes Kt */
tbConstKt: .int 0x5A827999
.int 0x6ED9EBA1
.int 0x8F1BBCDC
.int 0xCA62C1D6
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
iNbBlocs: .skip 8
sZoneConv: .skip 24
sZoneResult: .skip 24
sZoneTrav: .skip 1000
tbH: .skip 4 * 5 // 5 variables H
tbW: .skip 4 * 80 // 80 words W
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRosetta
//ldr x0,qAdrszMessTest1
//ldr x0,qAdrszMessTest2
//ldr x0,qAdrszMessSup64
bl computeSHA1 // call routine SHA1
ldr x0,qAdrszMessResult
bl affichageMess // display message
ldr x0, qAdrsZoneResult
bl displaySHA1
ldr x0,qAdrszMessFinPgm
bl affichageMess // display message
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrszMessRosetta: .quad szMessRosetta
qAdrszMessTest1: .quad szMessTest1
qAdrszMessTest2: .quad szMessTest2
qAdrsZoneTrav: .quad sZoneTrav
qAdrsZoneConv: .quad sZoneConv
qAdrszMessFinPgm: .quad szMessFinPgm
qAdrszMessSup64: .quad szMessSup64
/******************************************************************/
/* compute SHA1 */
/******************************************************************/
/* x0 contains the address of the message */
computeSHA1:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
mov x2,#0 // counter length
debCopy: // copy string in work area
ldrb w3,[x0,x2]
strb w3,[x1,x2]
cmp x3,#0
add x4,x2,1
csel x2,x4,x2,ne
bne debCopy
lsl x6,x2,#3 // initial message length in bits
mov x3,#0b10000000 // add bit 1 at end of string
strb w3,[x1,x2]
add x2,x2,#1 // length in bytes
lsl x4,x2,#3 // length in bits
mov x3,#0
addZeroes:
lsr x5,x2,#6
lsl x5,x5,#6
sub x5,x2,x5
cmp x5,#56
beq storeLength // yes -> end add
strb w3,[x1,x2] // add zero at message end
add x2,x2,#1 // increment lenght bytes
add x4,x4,#8 // increment length in bits
b addZeroes
storeLength:
add x2,x2,#4 // add four bytes
rev w6,w6 // inversion bits initials message length
str w6,[x1,x2] // and store at end
ldr x7,qAdrtbConstHi // constantes H address
ldr x4,qAdrtbH // start area H
mov x5,#0
loopConst: // init array H with start constantes
ldr w6,[x7,x5,lsl #2] // load constante
str w6,[x4,x5,lsl #2] // and store
add x5,x5,#1
cmp x5,#5
blt loopConst
// split into block of 64 bytes
add x2,x2,#4 // TODO : à revoir
lsr x4,x2,#6 // blocks number
ldr x0,qAdriNbBlocs
str x4,[x0] // save block maxi
mov x7,#0 // n° de block et x1 contient l'adresse zone de travail
loopBlock: // begin loop of each block of 64 bytes
mov x0,x7
bl inversion // inversion each word because little indian
ldr x3,qAdrtbW // working area W address
mov x6,#0 // indice t
/* x2 address begin each block */
ldr x1,qAdrsZoneTrav
add x2,x1,x7,lsl #6 // compute block begin indice * 4 * 16
loopPrep: // loop for expand 80 words
cmp x6,#15 //
bgt expand1
ldr w0,[x2,x6,lsl #2] // load four byte message
str w0,[x3,x6,lsl #2] // store in first 16 block
b expandEnd
expand1:
sub x8,x6,#3
ldr w9,[x3,x8,lsl #2]
sub x8,x6,#8
ldr w10,[x3,x8,lsl #2]
eor x9,x9,x10
sub x8,x6,#14
ldr w10,[x3,x8,lsl #2]
eor x9,x9,x10
sub x8,x6,#16
ldr w10,[x3,x8,lsl #2]
eor x9,x9,x10
ror w9,w9,#31
str w9,[x3,x6,lsl #2]
expandEnd:
add x6,x6,#1
cmp x6,#80 // 80 words ?
blt loopPrep // and loop
/* COMPUTING THE MESSAGE DIGEST */
/* x1 area H constantes address */
/* x3 working area W address */
/* x5 address constantes K */
/* x6 counter t */
/* x7 block counter */
/* x8 a, x9 b, x10 c, x11 d, x12 e */
// init variable a b c d e
ldr x0,qAdrtbH
ldr w8,[x0]
ldr w9,[x0,#4]
ldr w10,[x0,#8]
ldr w11,[x0,#12]
ldr w12,[x0,#16]
ldr x1,qAdrtbConstHi
ldr x5,qAdrtbConstKt
mov x6,#0
loop80T: // begin loop 80 t
cmp x6,#19
bgt T2
ldr w0,[x5] // load constantes k0
and x2,x9,x10 // b and c
mvn w4,w9 // not b
and x4,x4,x11 // and d
orr x2,x2,x4
b T_fin
T2:
cmp x6,#39
bgt T3
ldr w0,[x5,#4] // load constantes k1
eor x2,x9,x10
eor x2,x2,x11
b T_fin
T3:
cmp x6,#59
bgt T4
ldr w0,[x5,#8] // load constantes k2
and x2,x9,x10
and x4,x9,x11
orr x2,x2,x4
and x4,x10,x11
orr x2,x2,x4
b T_fin
T4:
ldr w0,[x5,#12] // load constantes k3
eor x2,x9,x10
eor x2,x2,x11
b T_fin
T_fin:
ror w4,w8,#27 // left rotate a to 5
add w2,w2,w4
//affregtit Tfin 0
//affregtit Tfin 8
add w2,w2,w12
ldr w4,[x3,x6,lsl #2] // Wt
add w2,w2,w4
add w2,w2,w0 // Kt
mov x12,x11 // e = d
mov x11,x10 // d = c
ror w10,w9,#2 // c
mov x9,x8 // b = a
mov x8,x2 // nouveau a
add x6,x6,#1 // increment t
cmp x6,#80
blt loop80T
// other bloc
add x7,x7,1 // increment block
ldr x0,qAdriNbBlocs
ldr w4,[x0] // restaur maxi block
cmp x7,x4 // maxi ?
bge End
// End block
ldr x0,qAdrtbH // start area H
ldr w3,[x0]
add w3,w3,w8
str w3,[x0] // store a in H0
ldr w3,[x0,#4]
add w3,w3,w9
str w3,[x0,#4] // store b in H1
ldr w3,[x0,#8]
add w3,w3,w10
str w3,[x0,#8] // store c in H2
ldr w3,[x0,#12]
add w3,w3,w11
str w3,[x0,#12] // store d in H3
ldr w3,[x0,#16]
add w3,w3,w12
str w3,[x0,#16] // store e in H4
b loopBlock // loop
End:
// compute final result
ldr x0,qAdrtbH // start area H
ldr x2,qAdrsZoneResult
ldr w1,[x0]
add x1,x1,x8
rev w1,w1
str w1,[x2]
ldr w1,[x0,#4]
add x1,x1,x9
rev w1,w1
str w1,[x2,#4]
ldr w1,[x0,#8]
add x1,x1,x10
rev w1,w1
str w1,[x2,#8]
ldr w1,[x0,#12]
add x1,x1,x11
rev w1,w1
str w1,[x2,#12]
ldr w1,[x0,#16]
add x1,x1,x12
rev w1,w1
str w1,[x2,#16]
mov x0,#0 // routine OK
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrtbConstHi: .quad tbConstHi
qAdrtbConstKt: .quad tbConstKt
qAdrtbH: .quad tbH
qAdrtbW: .quad tbW
qAdrsZoneResult: .quad sZoneResult
qAdriNbBlocs: .quad iNbBlocs
/******************************************************************/
/* inversion des mots de 32 bits d'un bloc */
/******************************************************************/
/* x0 contains N° block */
inversion:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
add x1,x1,x0,lsl 6 // debut du bloc
mov x2,#0
1: // start loop
ldr w3,[x1,x2,lsl #2]
rev w3,w3
str w3,[x1,x2,lsl #2]
add x2,x2,#1
cmp x2,#16
blt 1b
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* x0 contains the address of hash */
displaySHA1:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0
mov x2,#0
1:
ldr w0,[x3,x2,lsl #2] // load 4 bytes
rev w0,w0 // reverse bytes
ldr x1,qAdrsZoneConv
bl conversion16_4W // conversion hexa
ldr x0,qAdrsZoneConv
bl affichageMess
add x2,x2,#1
cmp x2,#SHA_DIGEST_LENGTH / 4
blt 1b // and loop
ldr x0,qAdrszCarriageReturn
bl affichageMess // display message
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* conversion hexadecimal register 32 bits */
/******************************************************************/
/* x0 contains value and x1 address zone receptrice */
conversion16_4W:
stp x0,lr,[sp,-48]! // save registres
stp x1,x2,[sp,32] // save registres
stp x3,x4,[sp,16] // save registres
mov x2,#28 // start bit position
mov x4,#0xF0000000 // mask
mov x3,x0 // save entry value
1: // start loop
and x0,x3,x4 // value register and mask
lsr x0,x0,x2 // right shift
cmp x0,#10 // >= 10 ?
bge 2f // yes
add x0,x0,#48 // no is digit
b 3f
2:
add x0,x0,#55 // else is a letter A-F
3:
strb w0,[x1],#1 // load result and + 1 in address
lsr x4,x4,#4 // shift mask 4 bits left
subs x2,x2,#4 // decrement counter 4 bits <= zero ?
bge 1b // no -> loop
100: // fin standard de la fonction
ldp x3,x4,[sp,16] // restaur des 2 registres
ldp x1,x2,[sp,32] // restaur des 2 registres
ldp x0,lr,[sp],48 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #11l | 11l | V LIMIT = 1'000'000
F get_primes(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
V primes = get_primes(LIMIT)
V primeset = Set(primes)
V s = [[[Int]]()] * 4
[Int] unsexy
L(p) primes
I p + 6 C primeset
s[0].append([p, p + 6])
E
I p - 6 !C primeset
unsexy.append(p)
L.continue
I p + 12 C primeset
s[1].append([p, p + 6, p + 12])
E
L.continue
I p + 18 C primeset
s[2].append([p, p + 6, p + 12, p + 18])
E
L.continue
I p + 24 C primeset
s[3].append([p, p + 6, p + 12, p + 18, p + 24])
print(‘"SEXY" PRIME GROUPINGS:’)
L(sexy, name) zip(s, ‘pairs triplets quadruplets quintuplets’.split(‘ ’))
print(‘ #. #. ending with ...’.format(sexy.len, name))
L(sx) sexy[(len)-5..]
print(‘ ’sx)
print("\nThere are #. unsexy primes ending with ...".format(unsexy.len))
L(usx) unsexy[(len)-10..]
print(‘ ’usx) |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #C.2B.2B | C++ | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <openssl/sha.h>
class sha256_exception : public std::exception {
public:
const char* what() const noexcept override {
return "SHA-256 error";
}
};
class sha256 {
public:
sha256() { reset(); }
sha256(const sha256&) = delete;
sha256& operator=(const sha256&) = delete;
void reset() {
if (SHA256_Init(&context_) == 0)
throw sha256_exception();
}
void update(const void* data, size_t length) {
if (SHA256_Update(&context_, data, length) == 0)
throw sha256_exception();
}
std::vector<unsigned char> digest() {
std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
if (SHA256_Final(digest.data(), &context_) == 0)
throw sha256_exception();
return digest;
}
private:
SHA256_CTX context_;
};
std::string digest_to_string(const std::vector<unsigned char>& digest) {
std::ostringstream out;
out << std::hex << std::setfill('0');
for (size_t i = 0; i < digest.size(); ++i)
out << std::setw(2) << static_cast<int>(digest[i]);
return out.str();
}
std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {
std::vector<std::vector<unsigned char>> hashes;
std::vector<char> buffer(block_size);
sha256 md;
while (in) {
in.read(buffer.data(), block_size);
size_t bytes = in.gcount();
if (bytes == 0)
break;
md.reset();
md.update(buffer.data(), bytes);
hashes.push_back(md.digest());
}
if (hashes.empty())
return {};
size_t length = hashes.size();
while (length > 1) {
size_t j = 0;
for (size_t i = 0; i < length; i += 2, ++j) {
auto& digest1 = hashes[i];
auto& digest_out = hashes[j];
if (i + 1 < length) {
auto& digest2 = hashes[i + 1];
md.reset();
md.update(digest1.data(), digest1.size());
md.update(digest2.data(), digest2.size());
digest_out = md.digest();
} else {
digest_out = digest1;
}
}
length = j;
}
return hashes[0];
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " filename\n";
return EXIT_FAILURE;
}
std::ifstream in(argv[1], std::ios::binary);
if (!in) {
std::cerr << "Cannot open file " << argv[1] << ".\n";
return EXIT_FAILURE;
}
try {
std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n';
} catch (const std::exception& ex) {
std::cerr << ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | 10 DEFINT I,J: DEFSTR S: DIM S(2)
20 S(0)="* "
30 S(1)="Spc"
40 S(2)="Del"
50 FOR I=32 TO 47
60 FOR J=I TO 127 STEP 16
70 MID$(S(0),1,1) = CHR$(J)
80 PRINT USING "###: \ \ ";J;S(-(J=32)-2*(J=127));
90 NEXT J
100 PRINT
110 NEXT I |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #Tcl | Tcl | #!/usr/bin/env tclsh8.6
package require Tcl 8.6
namespace eval udb {
variable db {}
proc Load {filename} {
variable db
if {[catch {set f [open $filename]}]} {
set db {}
return
}
set db [read $f]
close $f
}
proc Store {filename} {
variable db
if {[catch {set f [open $filename w]}]} return
dict for {nm inf} $db {
puts $f [list $nm $inf]
}
close $f
}
proc add {title category {date "now"} args} {
variable db
if {$date eq "now"} {
set date [clock seconds]
} else {
set date [clock scan $date]
}
dict set db $title [list $category $date $args]
return
}
proc Rec {nm cat date xtra} {
dict create description $nm category $cat date [clock format $date] \
{*}$xtra _names [dict keys $xtra]
}
proc latest {{category ""}} {
variable db
if {$category eq ""} {
set d [lsort -stride 2 -index {1 1} -integer -decreasing $db]
dict for {nm inf} $d break
return [list [Rec $nm {*}$inf]]
}
set latestbycat {}
dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] {
dict set latestbycat [lindex $inf 0] [list $nm {*}$inf]
}
return [list [Rec {*}[dict get $latestbycat $category]]]
}
proc latestpercategory {} {
variable db
set latestbycat {}
dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] {
dict set latestbycat [lindex $inf 0] [list $nm {*}$inf]
}
set result {}
dict for {- inf} $latestbycat {
lappend result [Rec {*}$inf]
}
return $result
}
proc bydate {} {
variable db
set result {}
dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] {
lappend result [Rec $nm {*}$inf]
}
return $result
}
namespace export add latest latestpercategory bydate
namespace ensemble create
}
if {$argc < 2} {
puts stderr "wrong # args: should be \"$argv0 dbfile subcommand ?args...?\""
exit 1
}
udb::Load [lindex $argv 0]
set separator ""
if {[catch {udb {*}[lrange $argv 1 end]} msg]} {
puts stderr [regsub "\"udb " $msg "\"$argv0 dbfile "]
exit 1
}
foreach row $msg {
puts -nonewline $separator
apply {row {
dict with row {
puts "Title: $description"
puts "Category: $category"
puts "Date: $date"
foreach v $_names {
puts "${v}: [dict get $row $v]"
}
}
}} $row
set separator [string repeat - 70]\n
}
udb::Store [lindex $argv 0] |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Hoon | Hoon | |= n=@ud
=+ m=0
=+ o=(reap 1 '*')
|^ ?: =(m n) o
$(m +(m), o (weld top bot))
++ gap (fil 3 (pow 2 m) ' ')
++ top (turn o |=(l=@t (rap 3 gap l gap ~)))
++ bot (turn o |=(l=@t (rap 3 l ' ' l ~)))
-- |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #Delphi | Delphi | function InCarpet(x, y : Integer) : Boolean;
begin
while (x<>0) and (y<>0) do begin
if ((x mod 3)=1) and ((y mod 3)=1) then
Exit(False);
x := x div 3;
y := y div 3;
end;
Result := True;
end;
procedure Carpet(n : Integer);
var
i, j, p : Integer;
begin
p := Round(IntPower(3, n));
for i:=0 to p-1 do begin
for j:=0 to p-1 do begin
if InCarpet(i, j) then
Print('#')
else Print(' ');
end;
PrintLn('');
end;
end;
Carpet(3); |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Nim | Nim | type
Point = tuple
x: float
y: float
func shoelace(points: openArray[Point]): float =
var leftSum, rightSum = 0.0
for i in 0..<len(points):
var j = (i + 1) mod len(points)
leftSum += points[i].x * points[j].y
rightSum += points[j].x * points[i].y
0.5 * abs(leftSum - rightSum)
var points = [(3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)]
echo shoelace(points) |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub area_by_shoelace {
my $area;
our @p;
$#_ > 0 ? @p = @_ : (local *p = shift);
$area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1;
$area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1;
return abs $area/2;
}
my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] );
say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] );
say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] );
say area_by_shoelace( @poly );
say area_by_shoelace( \@poly ); |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | echo Print[2+2] > file & math.exe -script file |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #min | min | min -e:"\"hi from min\" puts!" |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Nanoquery | Nanoquery | nq -e "println \"Hello Nanoquery!\"" |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #NetLogo | NetLogo | let x 15 ask turtles [ set xcor x set x x + 1 ] |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #Common_Lisp | Common Lisp | (defun a (F)
(print 'a)
F )
(defun b (F)
(print 'b)
F )
(dolist (x '((nil nil) (nil T) (T T) (T nil)))
(format t "~%(and ~S)" x)
(and (a (car x)) (b (car(cdr x))))
(format t "~%(or ~S)" x)
(or (a (car x)) (b (car(cdr x))))) |
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #Ada | Ada | with Ada.Text_IO;
with GNAT.SHA1;
procedure Main is
begin
Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " &
GNAT.SHA1.Digest ("Rosetta Code"));
end Main; |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #ALGOL_W | ALGOL W | begin
% find some sexy primes - primes that differ from another prime by 6 %
% implements the sieve of Eratosthenes %
procedure sieve( logical array s ( * ); integer value n ) ;
begin
% start with everything flagged as prime %
for i := 1 until n do s( i ) := true;
% sieve out the non-primes %
s( 1 ) := false;
for i := 2 until truncate( sqrt( n ) ) do begin
if s( i ) then for p := i * i step i until n do s( p ) := false
end for_i ;
end sieve ;
% adds a prime to list of sexy/unsexy primes %
procedure addPrime ( integer value p
; integer array list ( * )
; integer value len
) ;
begin
% increment count, shuffle down the primes and add the new one %
list( 0 ) := list( 0 ) + 1;
for i := 1 until len - 1 do list( i ) := list( i + 1 );
list( len ) := p
end addPrime ;
% counts the number of pairs of sexy primes, triplets, quadruplest and %
% quintuplets up to n %
% the counts of each kind are returned in the 0 element of the arrays %
% the last 5 ( or less if there are less than 5 ) of each type of sexy %
% prime is returned in the array elements 1 to 5 %
procedure countSexyPrimes ( logical array s ( * )
; integer value n
; integer array pairs, triplets, quadruplets, quintuplets ( * )
) ;
begin
integer pos2, pos3, pos4, pos5;
for i := 0 until 5 do pairs( i ) := triplets( i ) := quadruplets( i ) := quintuplets( i ) := 0;
% look for pairs etc. up to n %
% 2 cannot be a sexy prime as it is the only even prime, thus: %
% pairs can start at 7, triplets at 13, quadruplets at 19 and %
% quintuplets at 25 %
for p := 7 step 2 until 11 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 )
end for_p ;
for p := 13 step 2 until 17 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) then addPrime( p, triplets, 5 )
end for_p ;
for p := 19 step 2 until 23 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) then addPrime( p, triplets, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) and s( p - 18 )
then addPrime( p, quadruplets, 5 )
end for_p ;
pos5 := 1;
pos4 := pos5 + 6;
pos3 := pos4 + 6;
pos2 := pos3 + 6;
for p := pos2 + 6 step 2 until n do begin
if s( p ) then begin
if s( pos2 ) then begin % sexy pair %
addPrime( p, pairs, 5 );
if s( pos3 ) then begin % sexy triplet %
addPrime( p, triplets, 5 );
if s( pos4 ) then begin % sexy quadruplet %
addPrime( p, quadruplets, 5 );
if s( pos5 ) then begin % sexy quintuplet %
addPrime( p, quintuplets, 5 )
end if_s_pos5
end if_s_pos4
end if_s_pos3
end if_s_pos2
end if_s_p ;
pos2 := pos2 + 2;
pos3 := pos3 + 2;
pos4 := pos4 + 2;
pos5 := pos5 + 2
end for_p
end countSexyPrimes ;
% counts the number of unsexy primes up to n %
% the count is returned in the 0 element of the array %
% the last 5 ( or less if there are less than 5 ) unsexy prime is %
% returned in the array elements 1 to 10 %
procedure countUnsexyPrimes ( logical array s ( * )
; integer value n
; integer array unsexy ( * )
) ;
begin
for i := 0 until 10 do unsexy( i ) := 0;
for p := 2, 3, 5 do begin % handle primes below 7 separately %
if s( p ) and not s( p + 6 ) then addPrime( p, unsexy, 10 )
end for_p ;
for p := 7 step 2 until n do begin
if s( p ) and not s( p - 6 ) and not s( p + 6 ) then addPrime( p, unsexy, 10 )
end for_p
end countUnsexyPrimes ;
% shows sexy prime pairs %
procedure showPrimes ( integer value elements
; integer array primes ( * )
; integer value arrayMax
; string(24) value title
; integer value maxPrime
) ;
begin
write( i_w := 8, s_w := 0, "Found ", primes( 0 ), " ", title, " below ", maxPrime + 1
, i_w := 2, "; last ", ( if primes( 0 ) > arrayMax then arrayMax else primes( 0 ) ), ":"
);
write( i_w := 1, s_w := 0, " " );
for p := 1 until arrayMax do begin
if primes( p ) not = 0 then begin
integer pn;
if elements > 1 then writeon( "(" );
pn := primes( p ) - ( ( elements - 1 ) * 6 );
for i := 1 until elements do begin
writeon( i_w := 1, s_w := 0, " ", pn );
pn := pn + 6
end for_i ;
if elements > 1 then writeon( " ) " );
end if_primes_p_ne_0
end for_p
end showPrimes ;
integer MAX_SEXY, MAX_PRIME;
% for the task, we need to consider primes up to 1 000 035 %
% however we must still recognise sexy primes up that limit, so we sieve %
% up to 1 000 035 + 6 %
MAX_SEXY := 1000000 + 35;
MAX_PRIME := MAX_SEXY + 6;
begin
logical array s ( 1 :: MAX_PRIME );
integer array pairs, triplets, quadruplets, quintuplets ( 0 :: 5 );
integer array unsexy ( 0 :: 10 );
sieve( s, MAX_PRIME );
countSexyPrimes( s, MAX_SEXY, pairs, triplets, quadruplets, quintuplets );
countUnsexyPrimes( s, MAX_SEXY, unsexy );
showPrimes( 2, pairs, 5, "sexy prime pairs", MAX_SEXY );
showPrimes( 3, triplets, 5, "sexy prime triplets", MAX_SEXY );
showPrimes( 4, quadruplets, 5, "sexy prime quadruplets", MAX_SEXY );
showPrimes( 5, quintuplets, 5, "sexy prime quintuplets", MAX_SEXY );
showPrimes( 1, unsexy, 10, "unsexy primes", MAX_SEXY )
end
end. |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #AWK | AWK |
# syntax: GAWK -f SEXY_PRIMES.AWK
BEGIN {
cutoff = 1000034
for (i=1; i<=cutoff; i++) {
n1 = i
if (is_prime(n1)) {
total_primes++
if ((n2 = n1 + 6) > cutoff) { continue }
if (is_prime(n2)) {
save(2,5,n1 FS n2)
if ((n3 = n2 + 6) > cutoff) { continue }
if (is_prime(n3)) {
save(3,5,n1 FS n2 FS n3)
if ((n4 = n3 + 6) > cutoff) { continue }
if (is_prime(n4)) {
save(4,5,n1 FS n2 FS n3 FS n4)
if ((n5 = n4 + 6) > cutoff) { continue }
if (is_prime(n5)) {
save(5,5,n1 FS n2 FS n3 FS n4 FS n5)
}
}
}
}
if ((s[2] s[3] s[4] s[5]) !~ (n1 "")) { # check for unsexy
save(1,10,n1)
}
}
}
printf("%d primes less than %s\n\n",total_primes,cutoff+1)
printf("%d unsexy primes\n%s\n\n",c[1],s[1])
printf("%d sexy prime pairs\n%s\n\n",c[2],s[2])
printf("%d sexy prime triplets\n%s\n\n",c[3],s[3])
printf("%d sexy prime quadruplets\n%s\n\n",c[4],s[4])
printf("%d sexy prime quintuplets\n%s\n\n",c[5],s[5])
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
function save(key,nbr_to_keep,str) {
c[key]++
str = s[key] str ", "
if (gsub(/,/,"&",str) > nbr_to_keep) {
str = substr(str,index(str,",")+2)
}
s[key] = str
}
|
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in a nibble gets changed:
n = 2; Width e = 4:
Input b: 1000
Result: 1110
Input b: 0100
Result: 0111
Input b: 0010
Result: 0011
Input b: 0000
Result: 0000
Set of examples with the same input with set bits of varying distance apart:
n = 0; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 010000000000100000000010000000010000000100000010000010000100010010
n = 1; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011000000000110000000011000000011000000110000011000011000110011011
n = 2; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011100000000111000000011100000011100000111000011100011100111011111
n = 3; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011110000000111100000011110000011110000111100011110011110111111111
Task:
Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.
Use it to show, here, the results for the input examples above.
Print the output aligned in a way that allows easy checking by eye of the binary input vs output. | #Ada | Ada | with Ada.Text_IO;
procedure Set_Right_Bits is
type Bit_Number is new Positive range 1 .. 10_000;
type Bit is new Boolean;
type Bit_Collection is array (Bit_Number range <>) of Bit
with Pack;
function Right_Adjacent (B : Bit_Collection;
N : Natural) return Bit_Collection
is
Result : Bit_Collection := B;
Mask : Bit_Collection := B;
begin
for A in 1 .. N loop
Mask := False & Mask (Mask'First .. Mask'Last - 1);
-- Shift Mask by appending False/0 in front of slice.
Result := Result or Mask;
end loop;
return Result;
end Right_Adjacent;
procedure Put (Collection : Bit_Collection) is
use Ada.Text_IO;
begin
for Bit of Collection loop
Put ((if Bit then '1' else '0'));
end loop;
end Put;
function Value (Item : String) return Bit_Collection
is
Length : constant Bit_Number := Item'Length;
Result : Bit_Collection (1 .. Length);
Index : Natural := Item'First;
begin
for R of Result loop
R := (case Item (Index) is
when '0' | 'F' | 'f' => False,
when '1' | 'T' | 't' => True,
when others =>
raise Constraint_Error with "invalid input");
Index := Index + 1;
end loop;
return Result;
end Value;
procedure Show (Bit_String : String; N : Natural)
is
B : constant Bit_Collection := Value (Bit_String);
R : constant Bit_Collection := Right_Adjacent (B, N);
Prefix : constant String := " ";
use Ada.Text_IO;
begin
Put ("n ="); Put (N'Image);
Put ("; Width e ="); Put (Bit_String'Length'Image);
Put (":"); New_Line;
Put (Prefix); Put ("Input B: "); Put (B); New_Line;
Put (Prefix); Put ("Result : "); Put (R); New_Line;
New_Line;
end Show;
begin
Show ("1000", 2);
Show ("0100", 2);
Show ("0010", 2);
Show ("0000", 2);
Show ("010000000000100000000010000000010000000100000010000010000100010010", 0);
Show ("010000000000100000000010000000010000000100000010000010000100010010", 1);
Show ("010000000000100000000010000000010000000100000010000010000100010010", 2);
Show ("010000000000100000000010000000010000000100000010000010000100010010", 3);
end Set_Right_Bits; |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Delphi | Delphi |
program SHA256_Merkle_tree;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes,
DCPsha256;
function SHA256(const Input: TArray<Byte>; Len: Integer = -1): TArray<Byte>;
var
Hasher: TDCP_sha256;
l: Integer;
begin
if Len < 0 then
l := length(Input)
else
l := Len;
Hasher := TDCP_sha256.Create(nil);
try
Hasher.Init;
Hasher.Update(Input[0], l);
SetLength(Result, Hasher.HashSize div 8);
Hasher.final(Result[0]);
finally
Hasher.Free;
end;
end;
function Merkle_tree(FileName: TFileName): string;
const
blockSize = 1024;
var
f: TMemoryStream;
hashes: TArray<TArray<byte>>;
bytesRead: Cardinal;
buffer: TArray<byte>;
i, index: Integer;
begin
Result := '';
if not FileExists(FileName) then
exit;
SetLength(buffer, blockSize);
FillChar(buffer[0], blockSize, 0);
f := TMemoryStream.Create;
f.LoadFromFile(FileName);
index := 0;
repeat
bytesRead := f.Read(buffer, blockSize);
if 0 = bytesRead then
Break;
Insert(SHA256(buffer, bytesRead), hashes, index);
inc(index);
until false;
f.Free;
SetLength(buffer, 64);
while Length(hashes) > 1 do
begin
var hashes2: TArray<TArray<byte>>;
index := 0;
i := 0;
while i < length(hashes) do
begin
if i < length(hashes) - 1 then
begin
buffer := copy(hashes[i], 0, length(hashes[i]));
buffer := concat(buffer, copy(hashes[i + 1], 0, length(hashes[i])));
Insert(SHA256(buffer), hashes2, index);
inc(index);
end
else
begin
Insert(hashes[i], hashes2, index);
inc(index);
end;
inc(i, 2);
end;
hashes := hashes2;
end;
Result := '';
for var b in hashes[0] do
begin
Result := Result + b.ToHexString(2);
end;
end;
begin
writeln(Merkle_tree('title.png'));
readln;
end. |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BaCon | BaCon | FOR j = 0 TO 15
FOR i = 32+j TO 127 STEP 16
PRINT i FORMAT " %3d - ";
SELECT i
CASE 32
PRINT "Spc";
CASE 127
PRINT "Del";
DEFAULT
PRINT i FORMAT "%c "
ENDSELECT
NEXT
PRINT
NEXT |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #ToffeeScript | ToffeeScript | #!/usr/local/bin/toffee
prog = require 'commander'
fs = require 'fs-extra'
if not fs.exists! 'data.json'
fs.outputJson! 'data.json', {}
prog
.command('add <name> <category> [date]')
.description('Add a new entry')
.option('-n <text>', 'notes')
.option('-t <tags>', 'tags')
.action addentry
prog
.command('latest')
.description('Print the latest entry')
.action latest
prog
.command('catlatest')
.description('Print the latest entry for each category')
.action catlatestout
prog
.command('list')
.description('Print all entries sorted by date')
.action bydate
addentry = (name, category, dt, options) ->
if dt? then dat = new Date(dt) else dat = new Date()
update =
name: name
category: category
tags: options?.T
notes: options?.N
date: dat.getTime()
e, data = fs.readJson! 'data.json'
if not data[category]?
data[category] = []
data[category].push update
fs.outputJson 'data.json', data
byDateNew = (a, b) ->
if a.date<b.date then return 1
if b.date>a.date then return -1
return 0
catlatest = (cb) ->
e, data = fs.readJson! 'data.json'
ret = []
for cat, list of data
list.sort byDateNew
ret.push list[0]
cb ret
printFormatted = (entry) ->
tmp = entry.date
entry.date = new Date(entry.date).toDateString()
console.log entry
entry.date = tmp
latest = ->
newpercat = catlatest!
newpercat.sort byDateNew
printFormatted newpercat[0]
catlatestout = ->
items = catlatest!
for item in items
printFormatted item
bydate = ->
e, data = fs.readJson! 'data.json'
entries = []
for cat, list of data
for item in list
entries.push item
entries.sort byDateNew
for entry in entries
printFormatted entry
prog.parse process.argv |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Icon_and_Unicon | Icon and Unicon | # text based adaptaion of
procedure main(A)
width := 2 ^ ( 1 + (order := 0 < integer(\A[1]) | 4)) # order of arg[1] or 4
write("Triangle order= ",order)
every !(canvas := list(width)) := list(width," ") # prime the canvas
every y := 1 to width & x := 1 to width do # traverse it
if iand(x - 1, y - 1) = 0 then canvas[x,y] := "*" # fill
every x := 1 to width & y := 1 to width do
writes((y=1,"\n")|"",canvas[x,y]," ") # print
end |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #DWScript | DWScript | function InCarpet(x, y : Integer) : Boolean;
begin
while (x<>0) and (y<>0) do begin
if ((x mod 3)=1) and ((y mod 3)=1) then
Exit(False);
x := x div 3;
y := y div 3;
end;
Result := True;
end;
procedure Carpet(n : Integer);
var
i, j, p : Integer;
begin
p := Round(IntPower(3, n));
for i:=0 to p-1 do begin
for j:=0 to p-1 do begin
if InCarpet(i, j) then
Print('#')
else Print(' ');
end;
PrintLn('');
end;
end;
Carpet(3); |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Phix | Phix | with javascript_semantics
enum X, Y
function shoelace(sequence s)
atom t = 0
if length(s)>2 then
s = append(deep_copy(s),s[1])
for i=1 to length(s)-1 do
t += s[i][X]*s[i+1][Y] - s[i+1][X]*s[i][Y]
end for
end if
return abs(t)/2
end function
constant test = {{3,4},{5,11},{12,8},{9,5},{5,6}}
?shoelace(test)
|
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
FUNCTION ShoelaceArea(x() AS DOUBLE, y() AS DOUBLE) AS DOUBLE
LOCAL i, j AS LONG
LOCAL Area AS DOUBLE
j = UBOUND(x())
FOR i = LBOUND(x()) TO UBOUND(x())
Area += (y(j) + y(i)) * (x(j) - x(i))
j = i
NEXT i
FUNCTION = ABS(Area) / 2
END FUNCTION
FUNCTION PBMAIN () AS LONG
REDIM x(0 TO 4) AS DOUBLE, y(0 TO 4) AS DOUBLE
ARRAY ASSIGN x() = 3, 5, 12, 9, 5
ARRAY ASSIGN y() = 4, 11, 8, 5, 6
CON.PRINT STR$(ShoelaceArea(x(), y()))
CON.WAITKEY$
END FUNCTION |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #NetRexx | NetRexx |
$ TNRX=`mktemp T_XXXXXXXXXXXX` && test ! -e $TNRX.* && (echo 'say "Goodbye, World!"' >$TNRX; nrc -exec $TNRX; rm $TNRX $TNRX.*; unset TNRX)
|
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #NewLISP | NewLISP | newlisp -e "\"Hello\"
->"Hello" |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Nim | Nim | $ echo 'for i in 0..10: echo "Hello World"[0..i]' >/tmp/oneliner.nim; nim r oneliner
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimized.
If we needed to compute the conjunction (and):
x = a() and b()
Then it would be best to not compute the value of b() if the value of a() is computed as false, as the value of x can then only ever be false.
Similarly, if we needed to compute the disjunction (or):
y = a() or b()
Then it would be best to not compute the value of b() if the value of a() is computed as true, as the value of y can then only ever be true.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called short-circuit evaluation of boolean expressions
Task
Create two functions named a and b, that take and return the same boolean value.
The functions should also print their name whenever they are called.
Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary:
x = a(i) and b(j)
y = a(i) or b(j)
If the language does not have short-circuit evaluation, this might be achieved with nested if statements.
| #D | D | import std.stdio, std.algorithm;
T a(T)(T answer) {
writefln(" # Called function a(%s) -> %s", answer, answer);
return answer;
}
T b(T)(T answer) {
writefln(" # Called function b(%s) -> %s", answer, answer);
return answer;
}
void main() {
foreach (immutable x, immutable y;
[false, true].cartesianProduct([false, true])) {
writeln("\nCalculating: r1 = a(x) && b(y)");
immutable r1 = a(x) && b(y);
writeln("Calculating: r2 = a(x) || b(y)");
immutable r2 = a(x) || b(y);
}
} |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sha256_64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ LGHASH, 32 // result length
/*******************************************/
/* Structures */
/********************************************/
/* example structure variables */
.struct 0
var_a: // a
.struct var_a + 4
var_b: // b
.struct var_b + 4
var_c: // c
.struct var_c + 4
var_d: // d
.struct var_d + 4
var_e: // e
.struct var_e + 4
var_f: // f
.struct var_f + 4
var_g: // g
.struct var_g + 4
var_h: // h
.struct var_h + 4
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRosetta: .asciz "Rosetta code"
szMessTest1: .asciz "abc"
szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ascii "abcdefghijklmnopqrstuvwxyz"
.asciz "1234567890AZERTYUIOP"
szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
szMessFinPgm: .asciz "Program End ok.\n"
szMessResult: .asciz "Rosetta code => "
szCarriageReturn: .asciz "\n"
/* array constantes Hi */
tbConstHi: .int 0x6A09E667 // H0
.int 0xBB67AE85 // H1
.int 0x3C6EF372 // H2
.int 0xA54FF53A // H3
.int 0x510E527F // H4
.int 0x9B05688C // H5
.int 0x1F83D9AB // H6
.int 0x5BE0CD19 // H7
/* array 64 constantes Kt */
tbConstKt:
.int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
qNbBlocs: .skip 8
sZoneConv: .skip 24
sZoneTrav: .skip 1000
.align 8
tbH: .skip 4 * 8 // 8 variables H
tbabcdefgh: .skip 4 * 8
tbW: .skip 4 * 64 // 64 words W
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRosetta
//ldr x0,qAdrszMessTest1
//ldr x0,qAdrszMessTest2
//ldr x0,qAdrszMessSup64
bl computeSHA256 // call routine SHA1
ldr x0,qAdrszMessResult
bl affichageMess // display message
ldr x0, qAdrtbH
bl displaySHA1
ldr x0,qAdrszMessFinPgm
bl affichageMess // display message
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrszMessRosetta: .quad szMessRosetta
qAdrszMessTest1: .quad szMessTest1
qAdrszMessTest2: .quad szMessTest2
qAdrsZoneTrav: .quad sZoneTrav
qAdrsZoneConv: .quad sZoneConv
qAdrszMessFinPgm: .quad szMessFinPgm
qAdrszMessSup64: .quad szMessSup64
/******************************************************************/
/* compute SHA1 */
/******************************************************************/
/* x0 contains the address of the message */
computeSHA256:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
mov x2,#0 // counter length
debCopy: // copy string in work area
ldrb w3,[x0,x2]
strb w3,[x1,x2]
cmp x3,#0
add x4,x2,1
csel x2,x4,x2,ne
bne debCopy
lsl x6,x2,#3 // initial message length in bits
mov x3,#0b10000000 // add bit 1 at end of string
strb w3,[x1,x2]
add x2,x2,#1 // length in bytes
str xzr,[x1,x2] // zeroes in end of array
lsl x4,x2,#3 // length in bits
addZeroes:
lsr x5,x2,#6
lsl x5,x5,#6
sub x5,x2,x5
cmp x5,#56
beq storeLength // yes -> end add
str xzr,[x1,x2] // add zero at message end
add x2,x2,#1 // increment lenght bytes
add x4,x4,#8 // increment length in bits
b addZeroes
storeLength:
add x2,x2,#4 // add four bytes
rev w6,w6 // inversion bits initials message length
str w6,[x1,x2] // and store at end
ldr x7,qAdrtbConstHi // constantes H address
ldr x4,qAdrtbH // start area H
mov x5,#0
loopConst: // init array H with start constantes
ldr w6,[x7,x5,lsl #2] // load constante
str w6,[x4,x5,lsl #2] // and store
add x5,x5,#1
cmp x5,#8
blt loopConst
// split into block of 64 bytes
add x2,x2,#4 //
lsr x4,x2,#6 // blocks number
ldr x0,qAdrqNbBlocs
str x4,[x0] // save block maxi
mov x7,#0 // n° de block et x1 contient l adresse zone de travail
loopBlock: // begin loop of each block of 64 bytes
mov x0,x7
bl inversion // inversion each word because little indian
ldr x3,qAdrtbW // working area W address
mov x6,#0 // indice t
/* x2 address begin each block */
ldr x1,qAdrsZoneTrav
add x2,x1,x7,lsl #6 // compute block begin indice * 4 * 16
loopPrep: // loop for expand 80 words
cmp x6,#15 //
bgt expand1
ldr w0,[x2,x6,lsl #2] // load word message
str w0,[x3,x6,lsl #2] // store in first 16 block
b expandEnd
expand1:
sub x8,x6,#2
ldr w9,[x3,x8,lsl #2]
ror w10,w9,#17 // fonction e1 (256)
ror w11,w9,#19
eor w10,w10,w11
lsr w11,w9,#10
eor w10,w10,w11
sub x8,x6,#7
ldr w9,[x3,x8,lsl #2]
add w9,w9,w10 // + w - 7
sub x8,x6,#15
ldr w10,[x3,x8,lsl #2]
ror w11,w10,#7 // fonction e0 (256)
ror w12,w10,#18
eor w11,w11,w12
lsr w12,w10,#3
eor w10,w11,w12
add w9,w9,w10
sub x8,x6,#16
ldr w11,[x3,x8,lsl #2]
add w9,w9,w11
str w9,[x3,x6,lsl #2]
expandEnd:
add x6,x6,#1
cmp x6,#64 // 64 words ?
blt loopPrep // and loop
/* COMPUTING THE MESSAGE DIGEST */
/* x1 area H constantes address */
/* x3 working area W address */
/* x5 address constantes K */
/* x6 counter t */
/* x7 block counter */
/* x8 addresse variables a b c d e f g h */
// init variable a b c d e f g h
ldr x0,qAdrtbH
ldr x8,qAdrtbabcdefgh
mov x1,#0
loopInita:
ldr w9,[x0,x1,lsl #2]
str w9,[x8,x1,lsl #2]
add x1,x1,#1
cmp x1,#8
blt loopInita
ldr x1,qAdrtbConstHi
ldr x5,qAdrtbConstKt
mov x6,#0
loop64T: // begin loop 64 t
ldr w9,[x8,#var_h]
ldr w10,[x8,#var_e] // calcul T1
ror w11,w10,#6 // fonction sigma 1
ror w12,w10,#11
eor w11,w11,w12
ror w12,w10,#25
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e)
ldr w0,[x8,#var_f] // fonction ch x and y xor (non x and z)
ldr w4,[x8,#var_g]
and w11,w10,w0
mvn w12,w10
and w12,w12,w4
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e) + ch (e,f,g)
ldr w0,[x5,x6,lsl #2] // load constantes k0
add w9,w9,w0
ldr w0,[x3,x6,lsl #2] // Wt
add w9,w9,w0
// calcul T2
ldr w10,[x8,#var_a] // fonction sigma 0
ror w11,w10,#2
ror w12,w10,#13
eor w11,w11,w12
ror w12,w10,#22
eor w11,w11,w12
ldr w2,[x8,#var_b]
ldr w4,[x8,#var_c]
// fonction maj x and y xor x and z xor y and z
and w12,w10,w2
and w0,w10,w4
eor w12,w12,w0
and w0,w2,w4
eor w12,w12,w0 //
add w12,w12,w11 // T2
// compute variables
ldr w4,[x8,#var_g]
str w4,[x8,#var_h]
ldr w4,[x8,#var_f]
str w4,[x8,#var_g]
ldr w4,[x8,#var_e]
str w4,[x8,#var_f]
ldr w4,[x8,#var_d]
add w4,w4,w9 // add T1
str w4,[x8,#var_e]
ldr w4,[x8,#var_c]
str w4,[x8,#var_d]
ldr w4,[x8,#var_b]
str w4,[x8,#var_c]
ldr w4,[x8,#var_a]
str w4,[x8,#var_b]
add w4,w9,w12 // add T1 T2
str w4,[x8,#var_a]
add x6,x6,#1 // increment t
cmp x6,#64
blt loop64T
// End block
ldr x0,qAdrtbH // start area H
mov x10,#0
loopStoreH:
ldr w9,[x8,x10,lsl #2]
ldr w3,[x0,x10,lsl #2]
add w3,w3,w9
str w3,[x0,x10,lsl #2] // store variables in H0
add x10,x10,#1
cmp x10,#8
blt loopStoreH
// other bloc
add x7,x7,#1 // increment block
ldr x0,qAdrqNbBlocs
ldr x4,[x0] // restaur maxi block
cmp x7,x4 // maxi ?
blt loopBlock // loop other block
ldr x0,qAdrtbH // return result address
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrtbConstHi: .quad tbConstHi
qAdrtbConstKt: .quad tbConstKt
qAdrtbH: .quad tbH
qAdrtbW: .quad tbW
qAdrtbabcdefgh: .quad tbabcdefgh
qAdrqNbBlocs: .quad qNbBlocs
/******************************************************************/
/* inversion des mots de 32 bits d un bloc */
/******************************************************************/
/* x0 contains N° block */
inversion:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
add x1,x1,x0,lsl #6 // debut du bloc
mov x2,#0
1: // start loop
ldr w3,[x1,x2,lsl #2]
rev w3,w3
str w3,[x1,x2,lsl #2]
add x2,x2,#1
cmp x2,#16
blt 1b
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* x0 contains the address of hash */
displaySHA1:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0
mov x2,#0
1:
ldr w0,[x3,x2,lsl #2] // load 4 bytes
//rev x0,x0 // reverse bytes
ldr x1,qAdrsZoneConv
bl conversion16_4W // conversion hexa
ldr x0,qAdrsZoneConv
bl affichageMess
add x2,x2,#1
cmp x2,#LGHASH / 4
blt 1b // and loop
ldr x0,qAdrszCarriageReturn
bl affichageMess // display message
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* conversion hexadecimal register 32 bits */
/******************************************************************/
/* x0 contains value and x1 address zone receptrice */
conversion16_4W:
stp x0,lr,[sp,-48]! // save registres
stp x1,x2,[sp,32] // save registres
stp x3,x4,[sp,16] // save registres
mov x2,#28 // start bit position
mov x4,#0xF0000000 // mask
mov x3,x0 // save entry value
1: // start loop
and x0,x3,x4 // value register and mask
lsr x0,x0,x2 // right shift
cmp x0,#10 // >= 10 ?
bge 2f // yes
add x0,x0,#48 // no is digit
b 3f
2:
add x0,x0,#55 // else is a letter A-F
3:
strb w0,[x1],#1 // load result and + 1 in address
lsr x4,x4,#4 // shift mask 4 bits left
subs x2,x2,#4 // decrement counter 4 bits <= zero ?
bge 1b // no -> loop
100: // fin standard de la fonction
ldp x3,x4,[sp,16] // restaur des 2 registres
ldp x1,x2,[sp,32] // restaur des 2 registres
ldp x0,lr,[sp],48 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/SHA-1 | SHA-1 | SHA-1 or SHA1 is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
Warning: SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program sha1-1.s */
/* use with library openssl */
/* link with gcc option -lcrypto -lssl */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ SHA_DIGEST_LENGTH, 20
/*******************************************/
/* Fichier des macros */
/********************************************/
.include "../../ficmacros.s"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRosetta: .asciz "Rosetta Code"
.equ LGMESSROSETTA, . - szMessRosetta - 1
szCarriageReturn: .asciz "\n"
szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ascii "abcdefghijklmnopqrstuvwxyz"
.asciz "1234567890AZERTYUIOP"
.equ LGMESSSUP64, . - szMessSup64 - 1
szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
.equ LGMESSTEST2, . - szMessTest2 - 1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
szMessResult: .skip 24
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessRosetta
mov r1,#LGMESSROSETTA
ldr r2,iAdrszMessResult
bl SHA1 @ appel fonction openssl
ldr r0,iAdrszMessResult
bl displaySHA1
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszMessRosetta: .int szMessRosetta
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResult: .int szMessResult
iAdrsZoneConv: .int sZoneConv
iAdrszMessSup64: .int szMessSup64
iAdrszMessTest2: .int szMessTest2
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* r0 contains the address of hash */
displaySHA1:
push {r1-r3,lr} @ save registres
mov r3,r0
mov r2,#0
1:
ldr r0,[r3,r2,lsl #2] @ load 4 bytes
rev r0,r0 @ reverse bytes
ldr r1,iAdrsZoneConv
bl conversion16 @ conversion hexa
ldr r0,iAdrsZoneConv
bl affichageMess
add r2,r2,#1
cmp r2,#SHA_DIGEST_LENGTH / 4
blt 1b @ and loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, sexy primes are prime numbers that differ from each other by six.
For example, the numbers 5 and 11 are both sexy primes, because 11 minus 6 is 5.
The term "sexy prime" is a pun stemming from the Latin word for six: sex.
Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117
Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120
Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124
Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)
Task
For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (1,000,035).
Display at most the last 5, less than one million thirty-five, of each sexy prime group type.
Find and display the count of the unsexy primes less than one million thirty-five.
Find and display the last 10 unsexy primes less than one million thirty-five.
Note that 1000033 SHOULD NOT be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also SHOULD NOT be listed in the unsexy primes since it is sexy.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
// TRUE denotes composite, FALSE denotes prime.
c[0] = TRUE;
c[1] = TRUE;
// no need to bother with even numbers over 2 for this task
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;
}
for (i = p2; i < limit; i += 2*p) {
c[i] = TRUE;
}
for (;;) {
p += 2;
if (!c[p]) {
break;
}
}
}
}
void printHelper(const char *cat, int len, int lim, int n) {
const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : "";
const char *verb = (len == 1) ? "is" : "are";
printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len);
printf("The last %d %s:\n", n, verb);
}
void printArray(int *a, int len) {
int i;
printf("[");
for (i = 0; i < len; ++i) printf("%d ", a[i]);
printf("\b]");
}
int main() {
int i, ix, n, lim = 1000035;
int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;
int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;
int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;
int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];
int last_un[10];
bool *sv = calloc(lim - 1, sizeof(bool)); // all FALSE by default
setlocale(LC_NUMERIC, "");
sieve(sv, lim);
// get the counts first
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy++;
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs++;
} else continue;
if (i < lim-12 && !sv[i+12]) {
trips++;
} else continue;
if (i < lim-18 && !sv[i+18]) {
quads++;
} else continue;
if (i < lim-24 && !sv[i+24]) {
quins++;
}
}
if (pairs < lpr) lpr = pairs;
if (trips < ltr) ltr = trips;
if (quads < lqd) lqd = quads;
if (quins < lqn) lqn = quins;
if (unsexy < lun) lun = unsexy;
// now get the last 'x' for each category
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
un++;
if (un > unsexy - lun) {
last_un[un + lun - 1 - unsexy] = i;
}
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pr++;
if (pr > pairs - lpr) {
ix = pr + lpr - 1 - pairs;
last_pr[ix][0] = i; last_pr[ix][1] = i + 6;
}
} else continue;
if (i < lim-12 && !sv[i+12]) {
tr++;
if (tr > trips - ltr) {
ix = tr + ltr - 1 - trips;
last_tr[ix][0] = i; last_tr[ix][1] = i + 6;
last_tr[ix][2] = i + 12;
}
} else continue;
if (i < lim-18 && !sv[i+18]) {
qd++;
if (qd > quads - lqd) {
ix = qd + lqd - 1 - quads;
last_qd[ix][0] = i; last_qd[ix][1] = i + 6;
last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;
}
} else continue;
if (i < lim-24 && !sv[i+24]) {
qn++;
if (qn > quins - lqn) {
ix = qn + lqn - 1 - quins;
last_qn[ix][0] = i; last_qn[ix][1] = i + 6;
last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;
last_qn[ix][4] = i + 24;
}
}
}
printHelper("pairs", pairs, lim, lpr);
printf(" [");
for (i = 0; i < lpr; ++i) {
printArray(last_pr[i], 2);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("triplets", trips, lim, ltr);
printf(" [");
for (i = 0; i < ltr; ++i) {
printArray(last_tr[i], 3);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quadruplets", quads, lim, lqd);
printf(" [");
for (i = 0; i < lqd; ++i) {
printArray(last_qd[i], 4);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quintuplets", quins, lim, lqn);
printf(" [");
for (i = 0; i < lqn; ++i) {
printArray(last_qn[i], 5);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("unsexy primes", unsexy, lim, lun);
printf(" [");
printArray(last_un, lun);
printf("\b]\n");
free(sv);
return 0;
} |
http://rosettacode.org/wiki/Set_right-adjacent_bits | Set right-adjacent bits | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
Some examples:
Set of examples showing how one bit in a nibble gets changed:
n = 2; Width e = 4:
Input b: 1000
Result: 1110
Input b: 0100
Result: 0111
Input b: 0010
Result: 0011
Input b: 0000
Result: 0000
Set of examples with the same input with set bits of varying distance apart:
n = 0; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 010000000000100000000010000000010000000100000010000010000100010010
n = 1; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011000000000110000000011000000011000000110000011000011000110011011
n = 2; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011100000000111000000011100000011100000111000011100011100111011111
n = 3; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011110000000111100000011110000011110000111100011110011110111111111
Task:
Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.
Use it to show, here, the results for the input examples above.
Print the output aligned in a way that allows easy checking by eye of the binary input vs output. | #F.23 | F# |
// Set right-adjacent bits. Nigel Galloway: December 21st., 2021
let fN g l=let rec fG n g=[|match n,g with ('0'::t,0)->yield '0'; yield! fG t 0
|('0'::t,n)->yield '1'; yield! fG t (n-1)
|(_::t,_) ->yield '1'; yield! fG t l
|_ ->()|]
fG (g|>List.ofSeq) 0|>System.String
[("1000",2);("0100",2);("0010",2);("0001",2);("0000",2);("010000000000100000000010000000010000000100000010000010000100010010",0);("010000000000100000000010000000010000000100000010000010000100010010",1);("010000000000100000000010000000010000000100000010000010000100010010",2);("010000000000100000000010000000010000000100000010000010000100010010",3)]|>List.iter(fun(n,g)->printfn "%s\n%s" n (fN n g))
|
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Factor | Factor | USING: checksums checksums.sha fry grouping io
io.encodings.binary io.files kernel make math math.parser
namespaces sequences ;
: each-block ( ... size quot: ( ... block -- ... ) -- ... )
input-stream get spin (each-stream-block) ; inline
: >sha-256 ( seq -- newseq ) sha-256 checksum-bytes ;
: (hash-read) ( path encoding chunk-size -- )
'[ _ [ >sha-256 , ] each-block ] with-file-reader ;
! Read a file in chunks as a sequence of sha-256 hashes, so as
! not to store a potentially large file in memory all at once.
: hash-read ( path chunk-size -- seq )
binary swap [ (hash-read) ] { } make ;
: hash-combine ( seq -- newseq )
2 <groups>
[ dup length 1 > [ concat >sha-256 ] [ first ] if ] map ;
: merkle-hash ( path chunk-size -- str )
hash-read [ dup length 1 = ] [ hash-combine ] until first
bytes>hex-string ;
"title.png" 1024 merkle-hash print |
http://rosettacode.org/wiki/SHA-256_Merkle_tree | SHA-256 Merkle tree | As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.
Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).
Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
| #Go | Go | package main
import (
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)
func main() {
const blockSize = 1024
f, err := os.Open("title.png")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var hashes [][]byte
buffer := make([]byte, blockSize)
h := sha256.New()
for {
bytesRead, err := f.Read(buffer)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
h.Reset()
h.Write(buffer[:bytesRead])
hashes = append(hashes, h.Sum(nil))
}
buffer = make([]byte, 64)
for len(hashes) > 1 {
var hashes2 [][]byte
for i := 0; i < len(hashes); i += 2 {
if i < len(hashes)-1 {
copy(buffer, hashes[i])
copy(buffer[32:], hashes[i+1])
h.Reset()
h.Write(buffer)
hashes2 = append(hashes2, h.Sum(nil))
} else {
hashes2 = append(hashes2, hashes[i])
}
}
hashes = hashes2
}
fmt.Printf("%x", hashes[0])
fmt.Println()
} |
http://rosettacode.org/wiki/Show_ASCII_table | Show ASCII table | Task
Show the ASCII character set from values 32 to 127 (decimal) in a table format.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BCPL | BCPL | get "libhdr"
let str(n) =
n=32 -> "%I3: Spc ",
n=127 -> "%I3: Del ",
"%I3: %C "
let start() be
for i=32 to 47 do
$( for j=i to 127 by 16 do
writef(str(j), j, j)
wrch('*N')
$) |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #UNIX_Shell | UNIX Shell | #!/bin/sh
db_create() {
mkdir ./"$1" && mkdir "./$1/.tag" && echo "Create DB \`$1'"
}
db_delete() {
rm -r ./"$1" && echo "Delete DB \`$1'"
}
db_show() {
if [ -z "$2" ]; then show_help; fi
for x in "./$1/$2/"*; do
echo "$x:" | sed "s/.*\///"
cat "$x" | sed "s/^/ /"
echo
done
printf "Tags: "
ls "./$1/$2/.tag"
}
db_tag() {
local db="$1" item="$2"
shift
shift
for tag in $@; do
mkdir "./$db/.tag/$tag"
ln -s "$PWD/$db/$item" "./$db/.tag/$tag/"
touch "./$db/$item/.tag/$tag"
done
}
show_help() {
echo "Usage: $0 command [args]"
echo "Commands:"
cat $0 | grep ") ##" | grep -v grep | sed 's/) ## /:\t/'
exit
}
if [ -z "$1" ]; then show_help; fi
action=$1 it=database
shift
case $action in
create) ## db -- create $it
db_create "$@" ;;
drop) ## db -- delete $it
db_delete "$@" ;;
add) ## db item -- add new item to $it
mkdir -p "./$1/$2/.tag" && touch "./$1/$2/Description" ;;
rem) ## db item -- delete item from $it
rm -r "./$1/$2"
rm "./$1/.tag/"*"/$2"
;;
show) ## db item -- show item
db_show "$@" ;;
newtag) ## db new-tag-name -- create new tag name
mkdir "./$1/.tag/$2" ;;
prop) ## db item property-name property-content -- add property to item
echo "$4" > "./$1/$2/$3" ;;
tag) ## db item tag [more-tags...] -- mark item with tags
db_tag "$@" ;;
last) ## db -- show latest item
ls "$1" --sort=time | tail -n 1
;;
list) ## db -- list all items
ls "$1" -1 --sort=time
;;
last-all) ## db -- list items in each category
for x in "$1/.tag/"*; do
echo "$x" | sed 's/.*\//Tag: /'
printf " "
ls "$x" --sort=time | tail -n 1
echo
done
;;
help) ## this message
show_help
;;
*) echo Bad DB command: $1
show_help
;;
esac |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #IDL | IDL | pro sierp,n
s = (t = bytarr(3+2^(n+1))+32b)
t[2^n+1] = 42b
for lines = 1,2^n do begin
print,string( (s = t) )
for i=1,n_elements(t)-2 do if s[i-1] eq s[i+1] then t[i]=32b else t[i]=42b
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.