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/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.
|
#Bc
|
Bc
|
$ echo 'print "Hello "; var=99; ++var + 20 + 3' | bc
|
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.
|
#Bracmat
|
Bracmat
|
bracmat "put$tay$(e^x,x,20)&"
|
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.
|
#Burlesque
|
Burlesque
|
Burlesque.exe --no-stdin "5 5 .+"
|
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
|
#8080_Assembly
|
8080 Assembly
|
org 100h
mvi a,32 ; Start with space
mvi d,16 ; 16 lines
dochar: mov c,a ; Print number
call putnum
mov a,c
lxi h,spc ; Is it space?
cpi 32
jz print
lxi h,del
cpi 127 ; Is it del?
jz print
lxi h,chr ; Character
mov m,a
print: call puts
adi 16 ; Next column
jp dochar ; Done with this line?
lxi h,nl
call puts
sui 95 ; Next line
dcr d
jnz dochar
ret
;;; Print number in A. C, D preserved.
putnum: lxi h,num ; Set number string to spaces
push h
mvi b,' '
mov m,b
inx h
mov m,b
inx h
mov m,b
dgts: mvi b,-1
divmod: sui 10 ; B = A/10, A = (A mod 10)-10
inr b
jnc divmod
adi 58 ; Make digit
mov m,a ; Store digit
dcx h
mov a,b ; Next digit
ana a
jnz dgts
pop h ; Print number
;;; Print zero-terminated (...ish) string
puts: mov e,m
call putch
inx h
dcr e
jp puts
ret
;;; Output character in E using CP/M call,
;;; preserving registers
putch: push psw
push b
push d
push h
mvi c,2
call 5
pop h
pop d
pop b
pop psw
ret
nl: db 13,10,0 ; Newline
num: db ' : ',0 ; Placeholder for number string
spc: db 'Spc ',0 ; Space
del: db 'Del ',0 ; Del
chr: db '* ',0 ; Placeholder for character
|
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
|
#Nim
|
Nim
|
import algorithm, json, os, strformat, strutils, times
const FileName = "simdb.json"
type
Item = object
name: string
date: string
category: string
Database = seq[Item]
DbError = object of CatchableError
proc load(): Database =
if fileExists(FileName):
let node = try: FileName.parseFile()
except JsonParsingError:
raise newException(DbError, getCurrentExceptionMsg())
result = node.to(DataBase)
proc store(db: Database) =
try:
FileName.writeFile $(%* db)
except IOError:
quit "Unable to save database.", QuitFailure
proc addItem(args: seq[string]) =
var db = try: load()
except DbError: quit getCurrentExceptionMsg(), QuitFailure
let date = now().format("yyyy-MM-dd HH:mm:ss")
let cat = if args.len == 2: args[1] else: "none"
db.add Item(name: args[0], date: date, category: cat)
db.store()
proc printLatest(args: seq[string]) =
let db = try: load()
except DbError: quit getCurrentExceptionMsg(), QuitFailure
if db.len == 0:
echo "No entries in database."
return
# No need to sort db as items are added chronologically.
if args.len == 1:
var found = false
for item in reversed(db):
if item.category == args[0]:
echo item
found = true
break
if not found:
echo &"There are no items for category '{args[0]}'"
else:
echo db[^1]
proc printAll() =
let db = try: load()
except DbError: quit getCurrentExceptionMsg(), QuitFailure
if db.len == 0:
echo "No entries in database."
return
for item in db:
echo item
proc printUsage() =
echo &"""
Usage:
{getAppFilename().splitPath().tail} cmd [categoryName]
add add item, followed by optional category
latest print last added item(s), followed by optional category
all print all
For instance: add "some item name" "some category name"
"""
quit QuitFailure
if paramCount() notin 1..3: printUsage()
var params = commandLineParams()
let command = params[0].toLowerAscii
params.delete(0)
case command
of "add":
if params.len == 0: printUsage()
addItem(params)
of "latest":
if params.len > 1: printUsage()
printLatest(params)
of "all":
if params.len != 0: printUsage()
printAll()
|
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
|
#Perl
|
Perl
|
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use JSON::PP;
use Time::Piece;
use constant {
NAME => 0,
CATEGORY => 1,
DATE => 2,
DB => 'simple-db',
};
my $operation = shift // "";
my %dispatch = (
n => \&add_new,
l => \&print_latest,
L => \&print_latest_for_categories,
a => \&print_all,
);
if ($dispatch{$operation}) {
$dispatch{$operation}->(@ARGV);
} else {
die "Invalid option. Use one of n, l, L, a.\n"
}
sub add_new {
my ($name, $category, $date) = @_;
my $db = eval { load() } || {};
if (defined $date) {
eval { 'Time::Piece'->strptime($date, '%Y-%m-%d'); 1 }
or die "Invalid date format: YYYY-MM-DD.\n";
} else {
$date //= localtime->ymd;
}
my @ids = keys %{ $db->{by_id} };
my $max_id = max(num => @ids) || 0;
$db->{by_id}{ ++$max_id } = [ $name, $category, $date ];
save($db);
}
sub print_latest {
build_indexes( my $db = load(), 0, 1 );
_print_latest($db);
}
sub _print_latest {
my ($db, $category) = @_;
my @dates = keys %{ $db->{by_date} };
@dates = grep {
grep $db->{by_id}{$_}[CATEGORY] eq $category,
@{ $db->{by_date}{$_} };
} @dates if defined $category;
my $last_date = max(str => @dates);
say for map $db->{by_id}{$_}[NAME],
grep ! defined $category
|| $db->{by_id}{$_}[CATEGORY] eq $category,
@{ $db->{by_date}{$last_date} };
}
sub max {
my $type = shift;
my $max = $_[0];
{ num => sub { $_ > $max },
str => sub { $_ gt $max},
}->{$type}->() and $max = $_
for @_[ 1 .. $#_ ];
return $max
}
sub print_latest_for_categories {
build_indexes( my $db = load(), 1, 1 );
for my $category (sort keys %{ $db->{by_category} }){
say "* $category";
_print_latest($db, $category);
}
}
sub print_all {
build_indexes( my $db = load(), 0, 1 );
for my $date (sort keys %{ $db->{by_date} }) {
for my $id (@{ $db->{by_date}{$date} }) {
say $db->{by_id}{$id}[NAME];
}
}
}
sub load {
open my $in, '<', DB or die "Can't open database: $!\n";
local $/;
return { by_id => decode_json(<$in>) };
}
sub save {
my ($db) = @_;
open my $out, '>', DB or die "Can't save database: $!\n";
print {$out} encode_json($db->{by_id});
close $out;
}
sub build_indexes {
my ($db, $by_category, $by_date) = @_;
for my $id (keys %{ $db->{by_id} }) {
push @{ $db->{by_category}{ $db->{by_id}{$id}[CATEGORY] } }, $id
if $by_category;
push @{ $db->{by_date}{ $db->{by_id}{$id}[DATE] } }, $id
if $by_date;
}
}
|
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
|
#PicoLisp
|
PicoLisp
|
: (date 1)
-> (0 3 1) # Year zero, March 1st
|
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
|
#Pike
|
Pike
|
object cal = Calendar.ISO->set_timezone("UTC");
write( cal.Second(0)->format_iso_short() );
|
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
|
#PL.2FI
|
PL/I
|
*process source attributes xref;
epoch: Proc Options(main);
/*********************************************************************
* 20.08.2013 Walter Pachl shows that PL/I uses 15 Oct 1582 as epoch
* DAYS returns a FIXED BINARY(31,0) value which is the number of days
* (in Lilian format) corresponding to the date d.
*********************************************************************/
Dcl d Char(17);
Put Edit(datetime(),days(datetime()))
(Skip,a,f(15));
d='15821015000000000';
Put Edit(d ,days(d))
(Skip,a,f(15));
d='15821014000000000';
Put Edit(d ,days(d))
(Skip,a,f(15));
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
|
#F.23
|
F#
|
let sierpinski n =
let rec loop down space n =
if n = 0 then
down
else
loop (List.map (fun x -> space + x + space) down @
List.map (fun x -> x + " " + x) down)
(space + space)
(n - 1)
in loop ["*"] " " n
let () =
List.iter (fun (i:string) -> System.Console.WriteLine(i)) (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
|
#BASIC256
|
BASIC256
|
function in_carpet(x, y)
while x <> 0 and y <> 0
if(x mod 3) = 1 and (y mod 3) = 1 then return False
y = int(y / 3): x = int(x / 3)
end while
return True
end function
Subroutine carpet(n)
k = (3^n)-1
for i = 0 to k
for j = 0 to k
if in_carpet(i, j) then print("#"); else print(" ");
next j
print
next i
end subroutine
for k = 0 to 3
print "N = "; k
call carpet(k)
print
next k
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.
|
#F.23
|
F#
|
// Shoelace formula for area of polygon. Nigel Galloway: April 11th., 2018
let fN(n::g) = abs(List.pairwise(n::g@[n])|>List.fold(fun n ((nα,gα),(nβ,gβ))->n+(nα*gβ)-(gα*nβ)) 0.0)/2.0
printfn "%f" (fN [(3.0,4.0); (5.0,11.0); (12.0,8.0); (9.0,5.0); (5.0,6.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.
|
#Factor
|
Factor
|
USING: circular kernel math prettyprint sequences ;
IN: rosetta-code.shoelace
CONSTANT: input { { 3 4 } { 5 11 } { 12 8 } { 9 5 } { 5 6 } }
: align-pairs ( pairs-seq -- seq1 seq2 )
<circular> dup clone [ 1 ] dip
[ change-circular-start ] keep ;
: shoelace-sum ( seq1 seq2 -- n )
[ [ first ] [ second ] bi* * ] 2map sum ;
: shoelace-area ( pairs-seq -- area )
[ align-pairs ] [ align-pairs swap ] bi
[ shoelace-sum ] 2bi@ - abs 2 / ;
input shoelace-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.
|
#C
|
C
|
$ echo 'main() {printf("Hello\n");}' | gcc -w -x c -; ./a.out
|
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.
|
#C.23
|
C#
|
> Add-Type -TypeDefinition "public class HelloWorld { public static void SayHi() { System.Console.WriteLine(""Hi!""); } }"
> [HelloWorld]::SayHi()
Hi!
|
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.
|
#Clojure
|
Clojure
|
$ clj-env-dir -e "(defn add2 [x] (inc (inc x))) (add2 40)"
#'user/add2
42
|
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.
|
#11l
|
11l
|
F a(v)
print(‘ ## Called function a(#.)’.format(v))
R v
F b(v)
print(‘ ## Called function b(#.)’.format(v))
R v
L(i) (0B, 1B)
L(j) (0B, 1B)
print("\nCalculating: x = a(i) and b(j)")
V x = a(i) & b(j)
print(‘Calculating: y = a(i) or b(j)’)
V y = a(i) | b(j)
|
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
|
#8086_Assembly
|
8086 Assembly
|
cpu 8086
bits 16
putch: equ 2h
section .text
org 100h
mov cx,16 ; 16 lines
mov bh,32 ; Start at 32
dochar: mov al,bh ; Print number
call putnum
cmp bh,32 ; Space?
je .spc
cmp bh,127 ; Del?
je .del
mov [chr],bh ; Otherwise, print character
mov di,chr
jmp .out
.spc: mov di,spc
jmp .out
.del: mov di,del
.out: call putstr
add bh,16 ; Next column
cmp bh,128 ; Done with this line?
jb dochar
mov di,nl ; Print newline
call putstr
sub bh,95 ; Do next line
loop dochar
ret
;;; Print number in AL as ASCII, right-aligned in 3 characters
putnum: mov dx,2020h ; Put spaces in number
mov di,num ; Two spaces
mov [di],dx
inc di
inc di
mov [di],dh ; Third space
mov bl,10 ; Divisor
.div: xor ah,ah ; Write digits
div bl
add ah,'0'
mov [di],ah
dec di
test al,al
jnz .div
mov di,num ; Print number
putstr: mov ah,putch ; Use zero-terminated strings
.loop: mov dl,[di]
test dl,dl
jz .done
int 21h
inc di
jmp .loop
.done: ret
section .data
num: db ' : ',0 ; Placeholder for number string
nl: db 13,10,0 ; Newline
spc: db 'Spc ',0 ; Space
del: db 'Del ',0 ; Del
chr: db '* ',0 ; Placeholder for character
|
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
|
#Phix
|
Phix
|
--
-- demo\rosetta\Simple_db.exw
-- ==========================
--
without js -- (file i/o, gets(0), getenv)
include timedate.e
constant filename = getenv(iff(platform()=WINDOWS?"APPDATA":"HOME"))&"/simple_db.csv"
procedure add(sequence cmd)
if length(cmd)=0
or length(cmd)>2 then
printf(1,"usage: add name [cat]\n")
else
string name = cmd[1],
cat = iff(length(cmd)=2?cmd[2]:"none")
datestr = format_timedate(date(),"YYYY/MM/DD h:mmpm")
integer fn = open(filename,"a")
printf(fn,"%s,%s,%s\n",{name,cat,datestr})
close(fn)
end if
end procedure
procedure last(sequence cmd)
integer fn = open(filename,"r")
if fn=-1 then
puts(1,"file not found\n")
return
end if
integer lc = length(cmd)
string last = iff(lc?"<no entries for that category>\n":"<empty>\n")
while 1 do
object line = gets(fn)
if atom(line) then exit end if
if lc=0 or split(line,',')[2]=cmd[1] then
last = line
end if
end while
puts(1,last)
close(fn)
end procedure
sequence dates
function by_date(integer d1, integer d2)
return compare(dates[d1],dates[d2])
end function
procedure sort_by_date()
-- (simple_db.csv should be edited manually to prove the date sort works)
integer fn = open(filename,"r")
if fn=-1 then
puts(1,"file not found\n")
return
end if
sequence lines = {}
dates = {}
while 1 do
object line = gets(fn)
if atom(line) then exit end if
lines = append(lines,line)
dates = append(dates,split(line,',')[3])
end while
close(fn)
sequence tags = custom_sort(by_date,tagset(length(lines)))
for i=1 to length(tags) do
puts(1,lines[tags[i]])
end for
end procedure
procedure process(sequence cmd)
switch cmd[1] do
case "add": add(cmd[2..$])
case "last": last(cmd[2..$])
case "sort": sort_by_date()
default: printf(1,"unknown command: %s\n",{cmd[1]})
end switch
end procedure
constant helptext = """
p demo\rosetta\Simple_db -- interactive mode, commands as below
p demo\rosetta\Simple_db add name [cat] -- add entry
p demo\rosetta\Simple_db last [cat] -- show last entry [in specified category]
p demo\rosetta\Simple_db sort -- show full list sorted by date
"""
sequence cl = command_line()
if length(cl)<3 then
-- interactive mode
puts(1,helptext)
while 1 do
puts(1,">")
object line = trim(gets(0))
if atom(line) or length(line)=0 then exit end if
puts(1,"\n")
process(split(line))
end while
else
process(cl[3..$])
end if
|
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
|
#PowerShell
|
PowerShell
|
[datetime] 0
|
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
|
#PureBasic
|
PureBasic
|
If OpenConsole()
PrintN(FormatDate("Y = %yyyy M = %mm D = %dd, %hh:%ii:%ss", 0))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
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
|
#Python
|
Python
|
>>> import time
>>> time.asctime(time.gmtime(0))
'Thu Jan 1 00:00:00 1970'
>>>
|
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
|
#Factor
|
Factor
|
USING: io kernel math sequences ;
IN: sierpinski
: iterate-triangle ( triange spaces -- triangle' )
[ [ dup surround ] curry map ]
[ drop [ dup " " glue ] map ] 2bi append ;
: (sierpinski) ( triangle spaces n -- triangle' )
dup 0 = [ 2drop "\n" join ] [
[
[ iterate-triangle ]
[ nip dup append ] 2bi
] dip 1 - (sierpinski)
] if ;
: sierpinski ( n -- )
[ { "*" } " " ] dip (sierpinski) print ;
|
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
|
#BBC_BASIC
|
BBC BASIC
|
Order% = 3
side% = 3^Order%
VDU 23,22,8*side%;8*side%;64,64,16,128
FOR Y% = 0 TO side%-1
FOR X% = 0 TO side%-1
IF FNincarpet(X%,Y%) PLOT X%*16,Y%*16+15
NEXT
NEXT Y%
REPEAT WAIT 1 : UNTIL FALSE
END
DEF FNincarpet(X%,Y%)
REPEAT
IF X% MOD 3 = 1 IF Y% MOD 3 = 1 THEN = FALSE
X% DIV= 3
Y% DIV= 3
UNTIL X%=0 AND Y%=0
= TRUE
|
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.
|
#Fortran
|
Fortran
|
DOUBLE PRECISION FUNCTION AREA(N,P) !Calculates the area enclosed by the polygon P.
C Uses the mid-point rule for integration. Consider the line joining (x1,y1) to (x2,y2)
C The area under that line (down to the x-axis) is the y-span midpoint (y1 + y2)/2 times the width (x2 - x1)
C This is the trapezoidal rule for a single interval, and follows from simple geometry.
C Now consider a sequence of such points heading in the +x direction: each successive interval's area is positive.
C Follow with a sequence of points heading in the -x direction, back to the first point: their areas are all negative.
C The resulting sum is the area below the +x sequence and above the -x sequence: the area of the polygon.
C The point sequence can wobble as it wishes and can meet the other side, but it must not cross itself
c as would be done in a figure 8 drawn with a crossover instead of a meeting.
C A clockwise traversal (as for an island) gives a positive area; use anti-clockwise for a lake.
INTEGER N !The number of points.
DOUBLE COMPLEX P(N) !The points.
DOUBLE COMPLEX PP,PC !Point Previous and Point Current.
DOUBLE COMPLEX W !Polygon centre. Map coordinates usually have large offsets.
DOUBLE PRECISION A !The area accumulator.
INTEGER I !A stepper.
IF (N.LT.3) STOP "Area: at least three points are needed!" !Good grief.
W = (P(1) + P(N/3) + P(2*N/3))/3 !An initial working average.
W = SUM(P(1:N) - W)/N + W !A good working average is the average itself.
A = 0 !The area enclosed by the point sequence.
PC = P(N) - W !The last point is implicitly joined to the first.
DO I = 1,N !Step through the positions.
PP = PC !Previous position.
PC = P(I) - W !Current position.
A = (DIMAG(PC) + DIMAG(PP))*(DBLE(PC) - DBLE(PP)) + A !Area integral component.
END DO !On to the next position.
AREA = A/2 !Divide by two once.
END FUNCTION AREA !The units are those of the points.
DOUBLE PRECISION FUNCTION AREASL(N,P) !Area enclosed by polygon P, by the "shoelace" method.
INTEGER N !The number of points.
DOUBLE COMPLEX P(N) !The points.
DOUBLE PRECISION A !A scratchpad.
A = SUM(DBLE(P(1:N - 1)*DIMAG(P(2:N)))) + DBLE(P(N))*DIMAG(P(1))
1 - SUM(DBLE(P(2:N)*DIMAG(P(1:N - 1)))) - DBLE(P(1))*DIMAG(P(N))
AREASL = A/2 !The midpoint formula requires a halving.
END FUNCTION AREASL !Negative for clockwise, positive for anti-clockwise.
INTEGER ENUFF
DOUBLE PRECISION AREA,AREASL !The default types are not correct.
DOUBLE PRECISION A1,A2 !Scratchpads, in case of a debugging WRITE within the functions.
PARAMETER (ENUFF = 5) !The specification.
DOUBLE COMPLEX POINT(ENUFF) !Could use X and Y arrays instead.
DATA POINT/(3D0,4D0),(5D0,11D0),(12D0,8D0),(9D0,5D0),(5D0,6D0)/ !"D" for double precision.
WRITE (6,*) POINT
A1 = AREA(5,POINT)
A2 = AREASL(5,POINT)
WRITE (6,*) "A=",A1,A2
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.
|
#CMake
|
CMake
|
echo 'message(STATUS "Goodbye, World!")' | cmake -P /dev/stdin
|
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.
|
#COBOL
|
COBOL
|
echo 'display "hello".' | cobc -xFj -frelax -
|
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.
|
#6502_Assembly
|
6502 Assembly
|
;DEFINE 0 AS FALSE, $FF as true.
False equ 0
True equ 255
Func_A:
;input: accumulator = value to check. 0 = false, nonzero = true.
;output: 0 if false, 255 if true. Also prints the truth value to the screen.
;USAGE: LDA val JSR Func_A
BEQ .falsehood
load16 z_HL,BoolText_A_True ;lda #<BoolText_A_True sta z_L lda #>BoolText_A_True sta z_H
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_A_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_B:
;input: Y = value to check. 0 = false, nonzero = true.
;output: 0 if false, 255 if true. Also prints the truth value to the screen.
;USAGE: LDY val JSR Func_B
TYA
BEQ .falsehood ;return false
load16 z_HL,BoolText_B_True
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_B_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_A_and_B:
;input:
; z_B = input for Func_A
; z_C = input for Func_B
;output:
;0 if false, 255 if true
LDA z_B
jsr Func_A
BEQ .falsehood
LDY z_C
jsr Func_B
BEQ .falsehood
;true
load16 z_HL,BoolText_A_and_B_True
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_A_and_B_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_A_or_B:
;input:
; z_B = input for Func_A
; z_C = input for Func_B
;output:
;0 if false, 255 if true
LDA z_B
jsr Func_A
BNE .truth
LDY z_C
jsr Func_B
BNE .truth
;false
load16 z_HL,BoolText_A_or_B_False
jsr PrintString
LDA #False
rts
.truth:
load16 z_HL,BoolText_A_or_B_True
jsr PrintString
LDA #True
rts
BoolText_A_True:
db "A IS TRUE",0
BoolText_A_False:
db "A IS FALSE",0
BoolText_B_True:
db "B IS TRUE",0
BoolText_B_False:
db "B IS FALSE",0
BoolText_A_and_B_True:
db "A AND B IS TRUE",0
BoolText_A_and_B_False:
db "A AND B IS FALSE",0
BoolText_A_or_B_True:
db "A OR B IS TRUE",0
BoolText_A_or_B_False:
db "A OR B IS FALSE",0
|
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.
|
#Action.21
|
Action!
|
BYTE FUNC a(BYTE x)
PrintF(" a(%B)",x)
RETURN (x)
BYTE FUNC b(BYTE x)
PrintF(" b(%B)",x)
RETURN (x)
PROC Main()
BYTE i,j
FOR i=0 TO 1
DO
FOR j=0 TO 1
DO
PrintF("Calculating %B AND %B: call",i,j)
IF a(i)=1 AND b(j)=1 THEN
FI
PutE()
OD
OD
PutE()
FOR i=0 TO 1
DO
FOR j=0 TO 1
DO
PrintF("Calculating %B OR %B: call",i,j)
IF a(i)=1 OR b(j)=1 THEN
FI
PutE()
OD
OD
RETURN
|
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
|
#Action.21
|
Action!
|
PROC Main()
BYTE
count=[96],rows=[16],
first=[32],last=[127],
i,j
Put(125) ;clear screen
FOR i=0 TO rows-1
DO
Position(2,3+i)
FOR j=first+i TO last STEP rows
DO
IF j>=96 AND j<=99 THEN
Put(' )
FI
PrintB(j)
Put(' )
IF j=32 THEN
Print("SP ")
ELSEIF j=125 THEN
Print("CL")
ELSEIF j=126 THEN
Print("DL")
ELSEIF j=127 THEN
Print("TB")
ELSE
PrintF("%C ",j)
FI
OD
PutE()
OD
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
|
#PicoLisp
|
PicoLisp
|
#!/usr/bin/pil
(de usage ()
(prinl
"Usage:^J\
sdb <file> add <title> <cat> <date> ... Add a new entry^J\
sdb <file> get <title> Retrieve an entry^J\
sdb <file> latest Print the latest entry^J\
sdb <file> categories Print the latest for each cat^J\
sdb <file> Print all, sorted by date" ) )
(de printEntry (E)
(apply println (cdddr E) (car E) (cadr E) (datStr (caddr E))) )
(ifn (setq *File (opt))
(usage)
(case (opt)
(add
(let (Ttl (opt) Cat (opt))
(if (strDat (opt))
(rc *File Ttl (cons Cat @ (argv)))
(prinl "Bad date") ) ) )
(get
(let Ttl (opt)
(when (rc *File Ttl)
(printEntry (cons Ttl @)) ) ) )
(latest
(printEntry (maxi caddr (in *File (read)))) )
(categories
(for Cat (by cadr group (in *File (read)))
(printEntry (maxi caddr Cat)) ) )
(NIL
(mapc printEntry (by caddr sort (in *File (read)))) )
(T (usage)) ) )
(bye)
|
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
|
#R
|
R
|
> epoch <- 0
> class(epoch) <- class(Sys.time())
> format(epoch, "%Y-%m-%d %H:%M:%S %Z")
[1] "1970-01-01 00:00:00 UTC"
|
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
|
#Racket
|
Racket
|
#lang racket
(require racket/date)
(date->string (seconds->date 0 #f))
|
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
|
#Raku
|
Raku
|
say DateTime.new(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
|
#FALSE
|
FALSE
|
[[$][$1&["*"]?$~1&[" "]?2/]#%"
"]s: { stars }
[$@$@|@@&~&]x: { xor }
[1\[$][1-\2*\]#%]e: { 2^n }
[e;!1\[$][\$s;!$2*x;!\1-]#%%]t:
4t;!
|
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
|
#Befunge
|
Befunge
|
311>*#3\>#-:#1_$:00p00g-#@_010p0>:20p10g30v
>p>40p"#"30g40g*!#v_$48*30g3%1-v^ >$55+,1v>
0 ^p03/3g03/3g04$_v#!*!-1%3g04!<^_^#- g00 <
^3g01p02:0p01_@#-g>#0,#02#:0#+g#11#g+#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.
|
#FreeBASIC
|
FreeBASIC
|
' version 18-08-2017
' compile with: fbc -s console
Type _point_
As Double x, y
End Type
Function shoelace_formula(p() As _point_ ) As Double
Dim As UInteger i
Dim As Double sum
For i = 1 To UBound(p) -1
sum += p(i ).x * p(i +1).y
sum -= p(i +1).x * p(i ).y
Next
sum += p(i).x * p(1).y
sum -= p(1).x * p(i).y
Return Abs(sum) / 2
End Function
' ------=< MAIN >=------
Dim As _point_ p_array(1 To ...) = {(3,4), (5,11), (12,8), (9,5), (5,6)}
Print "The area of the polygon ="; shoelace_formula(p_array())
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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.
|
#Common_Lisp
|
Common Lisp
|
sbcl --noinform --eval '(progn (princ "Hello") (terpri) (quit))'
|
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.
|
#D
|
D
|
rdmd --eval="writeln(q{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.
|
#Dc
|
Dc
|
dc -e '22 7/p'
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Short_Circuit is
function A (Value : Boolean) return Boolean is
begin
Put (" A=" & Boolean'Image (Value));
return Value;
end A;
function B (Value : Boolean) return Boolean is
begin
Put (" B=" & Boolean'Image (Value));
return Value;
end B;
begin
for I in Boolean'Range loop
for J in Boolean'Range loop
Put (" (A and then B)=" & Boolean'Image (A (I) and then B (J)));
New_Line;
end loop;
end loop;
for I in Boolean'Range loop
for J in Boolean'Range loop
Put (" (A or else B)=" & Boolean'Image (A (I) or else B (J)));
New_Line;
end loop;
end loop;
end Test_Short_Circuit;
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Ascii_Table is
N : Integer;
begin
for R in 0 .. 15 loop
for C in 0 .. 5 loop
N := 32 + 16 * C + R;
Put (N, 3);
Put (" : ");
case N is
when 32 =>
Put ("Spc ");
when 127 =>
Put ("Del ");
when others =>
Put (Character'Val (N) & " ");
end case;
end loop;
New_Line;
end loop;
end Ascii_Table;
|
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
|
#Pike
|
Pike
|
mapping db = ([]);
mapping make_episode(string series, string title, string episode, array date)
{
return ([ "series":series, "episode":episode, "title":title, "date":date ]);
}
void print_episode(mapping episode)
{
write(" %-30s %10s %-30s (%{%d.%})\n",
episode->series, episode->episode, episode->title, episode->date);
}
void print_series(mapping series)
{
write("%-30s %-10s\n", series->series, series->status);
map(series->episodes, print_episode);
}
void dump_db(mapping database)
{
foreach(database; string name; mapping series)
{
print_series(series);
}
}
array get_latest(mapping database)
{
array latest = ({});
foreach(database; string name; mapping series)
{
latest += ({ series->episodes[0] });
}
return latest;
}
int(0..1) compare_date(array a, array b)
{
if (!arrayp(a) && !arrayp(b)) return false;
if (!arrayp(a) || !sizeof(a)) return arrayp(b) && sizeof(b);
if (!arrayp(b) || !sizeof(b)) return arrayp(a) && sizeof(a);
if (a[0] == b[0]) return compare_date(a[1..], b[1..]);
return a[0] < b[0];
}
int(0..1) compare_by_date(mapping a, mapping b)
{
return compare_date(reverse(a->date), reverse(b->date));
}
void watch_list(mapping database)
{
map(Array.sort_array(get_latest(database), compare_by_date),
print_episode);
}
string prompt_read(string prompt)
{
write("%s: ", prompt);
return Stdio.stdin.gets();
}
array parse_date(string date)
{
return (array(int))(date/".");
}
mapping prompt_for_episode()
{
return make_episode(prompt_read("Series"),
prompt_read("Title"),
prompt_read("Episode"),
parse_date(prompt_read("Date watched")));
}
// pike offers encode_value() and decode_value() as standard ways
// to save and read data, but that is not a human readable format.
// therefore we are instead printing the structure as debug-output
// which is a readable form as long as it only contains integers,
// strings, mappings, arrays and multisets this format can be read by pike.
// to read it we are creating a class that contains the data as a value,
// which is then compiled and instantiated to allow us to pull the data out.
void save_db(string filename, mapping database)
{
Stdio.write_file(filename, sprintf("%O", database));
}
void watch_save()
{
save_db("pwatch", db);
}
mapping load_db(string filename)
{
if (file_stat(filename))
return compile_string("mixed data = " +
Stdio.read_file(filename) + ";")()->data;
else return ([]);
}
mapping get_series(string name, mapping database)
{
return database[name];
}
array get_episode_list(string series, mapping database)
{
return database[series]->episodes;
}
void watch_new_series(string name, string status, mapping database)
{
database[name] = (["series":name, "status":status, "episodes":({}) ]);
}
mapping get_or_add_series(string name, mapping database)
{
if (!database[name])
{
string answer = prompt_read("Add new series? [y/n]: ");
if (answer == "y")
watch_new_series(name, "active", database);
}
return database[name];
}
void watch_add(mapping database)
{
mapping episode = prompt_for_episode();
string series_name = episode->series;
mapping series = get_or_add_series(series_name, database);
if (!series)
watch_add(database);
else
series->episodes = Array.unshift(series->episodes, episode);
}
void watch_load()
{
db = load_db("pwatch");
}
int main(int argc, array argv)
{
watch_load();
if (argc>1 && argv[1] == "add")
{
watch_add(db);
watch_save();
}
else
watch_list(db);
}
|
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
|
#REXX
|
REXX
|
/*REXX program displays the number of days since the epoch for the DATE function (BIF). */
say ' today is: ' date() /*today's is format: mm MON YYYY */
days=date('Basedate') /*only the first char of option is used*/
say right(days, 40) " days since the REXX base date of January 1st, year 1"
say ' and today is: ' date(, days, "B") /*it should still be today (µSec later)*/
/* ↑ ┌───◄─── This BIF (Built-In Function) is only */
/* └─────────◄──────┘ for newer versions of REXX that */
/* support the 2nd and 3rd arguments. */
|
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
|
#Ring
|
Ring
|
load "guilib.ring"
New qApp {
win1 = new qMainWindow() {
setwindowtitle("Using QDateEdit")
setGeometry(100,100,250,100)
oDate = new qdateedit(win1) {
setGeometry(20,40,220,30)
oDate.minimumDate()
}
show()
}
exec()
}
|
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
|
#FOCAL
|
FOCAL
|
01.10 A "ORDER",O;S S=2^(O+1)
01.20 F X=0,S;S L(X)=0
01.30 S L(S/2)=1
01.40 F I=1,S/2;D 2;D 3
01.90 Q
02.10 F X=1,S-1;D 2.3
02.20 T !;R
02.30 I (L(X)),2.4,2.5
02.40 T " "
02.50 T "*"
03.10 F X=0,S;S K(X)=FABS(L(X-1)-L(X+1))
03.20 F X=0,S;S L(X)=K(X)
|
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
|
#BQN
|
BQN
|
_decode ← {⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Carpet ← { # 2D Array method using ∾.
{∾(3‿3⥊4≠↕9)⊏⟨(≢𝕩)⥊0,𝕩⟩}⍟(𝕩-1) 1‿1⥊1
}
Carpet1 ← { # base conversion method, works in a single step.
¬{∨´𝕨∧○((-𝕨⌈○≠𝕩)⊸↑)𝕩}⌜˜2|3 _decode¨↕3⋆𝕩-1
}
•Show " #"⊏˜Carpet 4
•Show (Carpet ≡ Carpet1) 4
|
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.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
package main
import "fmt"
type point struct{ x, y float64 }
func shoelace(pts []point) float64 {
sum := 0.
p0 := pts[len(pts)-1]
for _, p1 := range pts {
sum += p0.y*p1.x - p0.x*p1.y
p0 = p1
}
return sum / 2
}
func main() {
fmt.Println(shoelace([]point{{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.
|
#Go
|
Go
|
package main
import "fmt"
type point struct{ x, y float64 }
func shoelace(pts []point) float64 {
sum := 0.
p0 := pts[len(pts)-1]
for _, p1 := range pts {
sum += p0.y*p1.x - p0.x*p1.y
p0 = p1
}
return sum / 2
}
func main() {
fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}}))
}
|
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.
|
#Delphi
|
Delphi
|
echo program Prog;begin writeln('Hi');end. >> "./a.dpt" & dcc32 -Q -CC -W- "./a.dpt" & a.exe
|
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.
|
#E
|
E
|
rune --src.e 'println("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.
|
#Elixir
|
Elixir
|
$ elixir -e "IO.puts 'Hello, World!'"
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.
|
#Emacs_Lisp
|
Emacs Lisp
|
emacs -batch -eval '(princ "Hello World!\n")'
|
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.
|
#ALGOL_68
|
ALGOL 68
|
PRIO ORELSE = 2, ANDTHEN = 3; # user defined operators #
OP ORELSE = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ),
ANDTHEN = (BOOL a, PROC BOOL b)BOOL: ( a | b | a );
# user defined Short-circuit_evaluation procedures #
PROC or else = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ),
and then = (BOOL a, PROC BOOL b)BOOL: ( a | b | a );
test:(
PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a),
b = (BOOL b)BOOL: ( print(("b=",b,", ")); b);
CO
# Valid for Algol 68 Rev0: using "user defined" operators #
# Note: here BOOL is being automatically "procedured" to PROC BOOL #
print(("T ORELSE F = ", a(TRUE) ORELSE b(FALSE), new line));
print(("F ANDTHEN T = ", a(FALSE) ANDTHEN b(TRUE), new line));
print(("or else(T, F) = ", or else(a(TRUE), b(FALSE)), new line));
print(("and then(F, T) = ", and then(a(FALSE), b(TRUE)), new line));
END CO
# Valid for Algol68 Rev1: using "user defined" operators #
# Note: BOOL must be manually "procedured" to PROC BOOL #
print(("T ORELSE F = ", a(TRUE) ORELSE (BOOL:b(FALSE)), new line));
print(("T ORELSE T = ", a(TRUE) ORELSE (BOOL:b(TRUE)), new line));
print(("F ANDTHEN F = ", a(FALSE) ANDTHEN (BOOL:b(FALSE)), new line));
print(("F ANDTHEN T = ", a(FALSE) ANDTHEN (BOOL:b(TRUE)), new line));
print(("F ORELSE F = ", a(FALSE) ORELSE (BOOL:b(FALSE)), new line));
print(("F ORELSE T = ", a(FALSE) ORELSE (BOOL:b(TRUE)), new line));
print(("T ANDTHEN F = ", a(TRUE) ANDTHEN (BOOL:b(FALSE)), new line));
print(("T ANDTHEN T = ", a(TRUE) ANDTHEN (BOOL:b(TRUE)), new line))
)
|
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
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
# generate an ascii table for characters 32 - 127 #
INT char count := 1;
FOR c FROM 32 TO 127 DO
print( ( whole( c, -4 )
, ": "
, IF c = 32 THEN "SPC"
ELIF c = 127 THEN "DEL"
ELSE " " + REPR c + " "
FI
)
);
IF char count = 0 THEN print( ( newline ) ) FI;
( char count PLUSAB 1 ) MODAB 6
OD
END
|
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
|
#PowerShell
|
PowerShell
|
function db
{
[CmdletBinding(DefaultParameterSetName="None")]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$false,
Position=0,
ParameterSetName="Add a new entry")]
[string]
$Path = ".\SimpleDatabase.csv",
[Parameter(Mandatory=$true,
ParameterSetName="Add a new entry")]
[string]
$Name,
[Parameter(Mandatory=$true,
ParameterSetName="Add a new entry")]
[string]
$Category,
[Parameter(Mandatory=$true,
ParameterSetName="Add a new entry")]
[datetime]
$Birthday,
[Parameter(ParameterSetName="Print the latest entry")]
[switch]
$Latest,
[Parameter(ParameterSetName="Print the latest entry for each category")]
[switch]
$LatestByCategory,
[Parameter(ParameterSetName="Print all entries sorted by a date")]
[switch]
$SortedByDate
)
if (-not (Test-Path -Path $Path))
{
'"Name","Category","Birthday"' | Out-File -FilePath $Path
}
$db = Import-Csv -Path $Path | Foreach-Object {
$_.Birthday = $_.Birthday -as [datetime]
$_
}
switch ($PSCmdlet.ParameterSetName)
{
"Add a new entry"
{
[PSCustomObject]@{Name=$Name; Category=$Category; Birthday=$Birthday} | Export-Csv -Path $Path -Append
}
"Print the latest entry"
{
$db[-1]
}
"Print the latest entry for each category"
{
($db | Group-Object -Property Category).Name | ForEach-Object {($db | Where-Object -Property Category -Contains $_)[-1]}
}
"Print all entries sorted by a date"
{
$db | Sort-Object -Property Birthday
}
Default
{
$db
}
}
}
db -Name Bev -Category friend -Birthday 3/3/1983
db -Name Bob -Category family -Birthday 7/19/1987
db -Name Gill -Category friend -Birthday 12/9/1986
db -Name Gail -Category family -Birthday 2/11/1986
db -Name Vince -Category family -Birthday 3/10/1960
db -Name Wayne -Category coworker -Birthday 5/29/1962
|
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
|
#Ruby
|
Ruby
|
irb(main):001:0> Time.at(0).utc
=> 1970-01-01 00:00:00 UTC
|
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
|
#Run_BASIC
|
Run BASIC
|
eDate$ = date$("01/01/0001")
cDate$ = date$(0) ' 01/01/1901
sDate$ = date$("01/01/1970")
|
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
|
#Rust
|
Rust
|
extern crate time;
use time::{at_utc, Timespec};
fn main() {
let epoch = at_utc(Timespec::new(0, 0));
println!("{}", epoch.asctime());
}
|
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
|
#Scala
|
Scala
|
import java.util.{Date, TimeZone, Locale}
import java.text.DateFormat
val df=DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH)
df.setTimeZone(TimeZone.getTimeZone("UTC"))
println(df.format(new Date(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
|
#Forth
|
Forth
|
: stars ( mask -- )
begin
dup 1 and if [char] * else bl then emit
1 rshift dup
while space repeat drop ;
: triangle ( order -- )
1 swap lshift ( 2^order )
1 over 0 do
cr over i - spaces dup stars
dup 2* xor
loop 2drop ;
5 triangle
|
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
|
#Brainf.2A.2A.2A
|
Brainf***
|
input order and print the associated Sierpinski carpet
orders over 5 require larger cell sizes
+++>>+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+
>>]<+>]]]<]<<[>>+<<-]+>[>>[-]>[-]<<<<[>>>>+<<<<-]>>>>[<<[<<+>>>+<-]>[<+>-]>-]<<<
-]>[-]<<[>+>+<<-]>>[<<+>>-]<[<[>>+>+<<<-]>>>[<<<+>>>-]<[<[>>+>>>+<<<<<-]>>[<<+>>
-]<[>>+>>>+<<<<<-]>>[<<+>>-]>>->-<<<<+[[>+>+<<-]>[<+>-]>[>[>>+>+<<<-]>>>[<<<+>>>
-]+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<->+<[>-]>[<<<+>>>->]<<[-]<<<[>>+>+
<<<-]>>>[<<<+>>>-]+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<->+<[>-]>[<<<+>>>-
>]<<[-]<<<[>[>+<-]<-]>[-]>[<<+>>-]<<[>>++++[<++++++++>-]<.[-]<<[-]<[-]<<<->>>>>-
]<<<-]<<[>+>+<<-]>[<+>-]>[>[>>+<<-]>>>+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]
>[<<<<<+>>>>>-]<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]>[<<<+>>>-]<<<<[>>+>
+<<<-]>>>[<<<+>>>-]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>[>+<-]<-]>[-]+>[[-]<->]<[->+<]>
[<<+>>-]<<[>>+++++[<+++++++>-]<.[-]<<[-]<[-]<<<->>>>>-]<<<-]<<]<-]++++++++++.[-]
<-]
|
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.
|
#Haskell
|
Haskell
|
import Data.Bifunctor (bimap)
----------- SHOELACE FORMULA FOR POLYGONAL AREA ----------
-- The area of a polygon formed by
-- the list of (x, y) coordinates.
shoelace :: [(Double, Double)] -> Double
shoelace =
let calcSums ((x, y), (a, b)) = bimap (x * b +) (a * y +)
in (/ 2)
. abs
. uncurry (-)
. foldr calcSums (0, 0)
. (<*>) zip (tail . cycle)
--------------------------- TEST -------------------------
main :: IO ()
main =
print $
shoelace [(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.
|
#J
|
J
|
shoelace=:verb define
0.5*|+/((* 1&|.)/ - (* _1&|.)/)|: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.
|
#Erlang
|
Erlang
|
$ erl -noshell -eval 'io:format("hello~n").' -s erlang halt
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.
|
#F.23
|
F#
|
> echo printfn "Hello from F#" | fsi --quiet
Hello from F#
|
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.
|
#Factor
|
Factor
|
$ factor -run=none -e="USE: io \"hi\" print"
|
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.
|
#ALGOL_W
|
ALGOL W
|
begin
logical procedure a( logical value v ) ; begin write( "a: ", v ); v end ;
logical procedure b( logical value v ) ; begin write( "b: ", v ); v end ;
write( "and: ", a( true ) and b( true ) );
write( "---" );
write( "or: ", a( true ) or b( true ) );
write( "---" );
write( "and: ", a( false ) and b( true ) );
write( "---" );
write( "or: ", a( false ) or b( true ) );
write( "---" );
end.
|
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.
|
#AppleScript
|
AppleScript
|
on run
map(test, {|and|, |or|})
end run
-- test :: ((Bool, Bool) -> Bool) -> (Bool, Bool, Bool, Bool)
on test(f)
map(f, {{true, true}, {true, false}, {false, true}, {false, false}})
end test
-- |and| :: (Bool, Bool) -> Bool
on |and|(tuple)
set {x, y} to tuple
a(x) and b(y)
end |and|
-- |or| :: (Bool, Bool) -> Bool
on |or|(tuple)
set {x, y} to tuple
a(x) or b(y)
end |or|
-- a :: Bool -> Bool
on a(bool)
log "a"
return bool
end a
-- b :: Bool -> Bool
on b(bool)
log "b"
return bool
end b
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
script mf
property lambda : f
end script
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to mf's lambda(item i of xs, i, xs)
end repeat
return lst
end map
|
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
|
#ALGOL_W
|
ALGOL W
|
begin
% generate an ascii table for chars 32 - 127 %
integer cPos;
cPos := 0;
for i := 32 until 127 do begin
if cPos = 0 then write();
cPos := ( cPos + 1 ) rem 6;
writeon( i_w := 3, s_w := 0, i, ": " );
if i = 32 then writeon( "Spc ")
else if i = 127 then writeon( "Del " )
else writeon( code( i ), " " )
end for_i
end.
|
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
|
#Python
|
Python
|
#!/usr/bin/python3
'''\
Simple database for: http://rosettacode.org/wiki/Simple_database
'''
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help='''\
add: Add a new entry
pl: Print the latest entry
plc: Print the latest entry for each category/tag
pa: Print all entries sorted by a date''')
parser.add_argument('-d', '--description',
help='A description of the item. (e.g., title, name)')
parser.add_argument('-t', '--tag',
help=('''A category or tag (genre, topic, relationship '''
'''such as “friend” or “family”)'''))
parser.add_argument('-f', '--field', nargs=2, action='append',
help='Other optional fields with value (can be repeated)')
return parser
def do_add(args, dbname):
'Add a new entry'
if args.description is None:
args.description = ''
if args.tag is None:
args.tag = ''
del args.command
print('Writing record to %s' % dbname)
with open(dbname, 'a') as db:
db.write('%r\n' % args)
def do_pl(args, dbname):
'Print the latest entry'
print('Getting last record from %s' % dbname)
with open(dbname, 'r') as db:
for line in db: pass
record = eval(line)
del record._date
print(str(record))
def do_plc(args, dbname):
'Print the latest entry for each category/tag'
print('Getting latest record for each tag from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
tags = set(record.tag for record in records)
records.reverse()
for record in records:
if record.tag in tags:
del record._date
print(str(record))
tags.discard(record.tag)
if not tags: break
def do_pa(args, dbname):
'Print all entries sorted by a date'
print('Getting all records by date from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
for record in records:
del record._date
print(str(record))
def test():
import time
parser = parse_args()
for cmdline in [
"""-d Book -f title 'Windy places' -f type hardback --tag DISCOUNT add""",
"""-d Book -f title 'RC spammers' -f type paperback -t DISCOUNT add""",
"""-d Book -f title 'Splat it' -f type hardback -f special 'first edition' -t PREMIUM add""",
"""pl""",
"""plc""",
]:
args = parser.parse_args(shlex.split(cmdline))
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
time.sleep(0.5)
do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)
dbname = '_simple_db_db.py'
if __name__ == '__main__':
if 0:
test()
else:
parser = parse_args()
args = parser.parse_args()
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
|
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
|
#Scheme
|
Scheme
|
; Display date at Time Zero in UTC.
(printf "~s~%" (time-utc->date (make-time 'time-utc 0 0) 0))
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
begin
writeln(time.value);
end func;
|
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
|
#Sidef
|
Sidef
|
say Time.new(0).gmtime.ctime;
|
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
|
#Fortran
|
Fortran
|
program Sierpinski_triangle
implicit none
call Triangle(4)
contains
subroutine Triangle(n)
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer, intent(in) :: n
integer :: i, k
integer(i64) :: c
do i = 0, n*4-1
c = 1
write(*, "(a)", advance="no") repeat(" ", 2 * (n*4 - 1 - i))
do k = 0, i
if(mod(c, 2) == 0) then
write(*, "(a)", advance="no") " "
else
write(*, "(a)", advance="no") " * "
end if
c = c * (i - k) / (k + 1)
end do
write(*,*)
end do
end subroutine Triangle
end program Sierpinski_triangle
|
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
|
C
|
#include <stdio.h>
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? " " : "##");
}
printf("\n");
}
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.
|
#Java
|
Java
|
import java.util.List;
public class ShoelaceFormula {
private static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
private static double shoelaceArea(List<Point> v) {
int n = v.size();
double a = 0.0;
for (int i = 0; i < n - 1; i++) {
a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y;
}
return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0;
}
public static void main(String[] args) {
List<Point> v = List.of(
new Point(3, 4),
new Point(5, 11),
new Point(12, 8),
new Point(9, 5),
new Point(5, 6)
);
double area = shoelaceArea(v);
System.out.printf("Given a polygon with vertices %s,%n", v);
System.out.printf("its area is %f,%n", 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.
|
#Forth
|
Forth
|
$ gforth -e ".( Hello) cr bye"
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.
|
#Fortran
|
Fortran
|
$ gawk 'BEGIN{print"write(6,\"(2(g12.3,x))\")(i/10.0,besj1(i/10.0), i=0,1000)\nend";exit(0)}'|gfortran -ffree-form -x f95 - | gnuplot -p -e 'plot "<./a.out" t "Bessel function of 1st kind" w l'
|
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.
|
#Free_Pascal
|
Free Pascal
|
echo "begin writeLn('Hi'); end." | ifpc /dev/stdin
|
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.
|
#AutoHotkey
|
AutoHotkey
|
i = 1
j = 1
x := a(i) and b(j)
y := a(i) or b(j)
a(p)
{
MsgBox, a() was called with the parameter "%p%".
Return, p
}
b(p)
{
MsgBox, b() was called with the parameter "%p%".
Return, p
}
|
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.
|
#AWK
|
AWK
|
#!/usr/bin/awk -f
BEGIN {
print (a(1) && b(1))
print (a(1) || b(1))
print (a(0) && b(1))
print (a(0) || b(1))
}
function a(x) {
print " x:"x
return x
}
function b(y) {
print " y:"y
return y
}
|
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
|
#APL
|
APL
|
{(¯3↑⍕⍵),': ',∊('Spc' 'Del'(⎕UCS ⍵))[32 127⍳⍵]}¨⍉6 16⍴31+⍳96
|
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
|
#Racket
|
Racket
|
#!/usr/bin/env racket
#lang racket
(define (*write file data) ; write data in human readable format (sexpr/line)
(with-output-to-file file #:exists 'replace
(lambda () (for ([x data]) (printf "~s\n" x)))))
(define *read file->list) ; read our "human readable format"
(command-line
#:once-any
[("-a") file title category date "Add an entry"
(*write file `(,@(*read file) (,title ,category ,date)))]
[("-d") file title "Delete an entry (all matching)"
(*write file (filter-not (lambda (x) (equal? (car x) title)) (*read file)))]
[("-p") file mode "Print entries, mode = latest, latest/cat, all, by-date"
(define data (*read file))
(define (show item)
(match item [(list title cat date) (printf "[~a] ~a; ~a\n" cat title date)]))
(case (string->symbol mode)
[(all) (for-each show data)]
[(by-date) (for-each show (sort data string<? #:key cadr))]
[(latest) (show (last data))]
[(latest/cat)
(define (last/cat c) (for/last ([x data] #:when (equal? c (cadr x))) x))
(for-each (compose1 show last/cat) (remove-duplicates (map cadr data)))]
[else (error 'sdb "bad printout mode")])])
|
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
|
#Standard_ML
|
Standard ML
|
- Date.toString (Date.fromTimeUniv Time.zeroTime);
val it = "Thu Jan 1 00:00:00 1970" : string
|
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
|
#Stata
|
Stata
|
. di %td 0
01jan1960
. di %tc 0
01jan1960 00:00:00
|
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
|
#Tcl
|
Tcl
|
% clock format 0 -gmt 1
Thu Jan 01 00:00:00 GMT 1970
|
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
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
- epoch
number=1
dayofweeknr=DATE (date,day,month,year,number)
epoch=JOIN(year,"-",month,day)
PRINT "epoch: ", epoch," (daynumber ",number,")"
- today's daynumber
dayofweeknr=DATE (today,day,month,year,number)
date=JOIN (year,"-",month,day)
PRINT "today's date: ", date," (daynumber ", number,")"
|
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
|
#GAP
|
GAP
|
# Using parity of binomial coefficients
SierpinskiTriangle := function(n)
local i, j, s, b;
n := 2^n - 1;
b := " ";
while Size(b) < n do
b := Concatenation(b, b);
od;
for i in [0 .. n] do
s := "";
for j in [0 .. i] do
if IsEvenInt(Binomial(i, j)) then
Append(s, " ");
else
Append(s, "* ");
fi;
od;
Print(b{[1 .. n - i]}, s, "\n");
od;
end;
SierpinskiTriangle(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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> NextCarpet(List<string> carpet)
{
return carpet.Select(x => x + x + x)
.Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
.Concat(carpet.Select(x => x + x + x)).ToList();
}
static List<string> SierpinskiCarpet(int n)
{
return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
}
static void Main(string[] args)
{
foreach (string s in SierpinskiCarpet(3))
Console.WriteLine(s);
}
}
|
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.
|
#JavaScript
|
JavaScript
|
(() => {
"use strict";
// ------- SHOELACE FORMULA FOR POLYGONAL AREA -------
// shoelaceArea :: [(Float, Float)] -> Float
const shoeLaceArea = vertices => abs(
uncurry(subtract)(
ap(zip)(compose(tail, cycle))(
vertices
)
.reduce(
(a, x) => [0, 1].map(b => {
const n = Number(b);
return a[n] + (
x[0][n] * x[1][Number(!b)]
);
}),
[0, 0]
)
)
) / 2;
// ----------------------- TEST -----------------------
const main = () => {
const ps = [
[3, 4],
[5, 11],
[12, 8],
[9, 5],
[5, 6]
];
return [
"Polygonal area by shoelace formula:",
`${JSON.stringify(ps)} -> ${shoeLaceArea(ps)}`
]
.join("\n");
};
// ---------------- GENERIC FUNCTIONS -----------------
// abs :: Num -> Num
const abs = x =>
// Absolute value of a given number
// without the sign.
0 > x ? -x : x;
// ap :: (a -> b -> c) -> (a -> b) -> (a -> c)
const ap = f =>
// Applicative instance for functions.
// f(x) applied to g(x).
g => x => f(x)(
g(x)
);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// cycle :: [a] -> Generator [a]
const cycle = function* (xs) {
// An infinite repetition of xs,
// from which an arbitrary prefix
// may be taken.
const lng = xs.length;
let i = 0;
while (true) {
yield xs[i];
i = (1 + i) % lng;
}
};
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// subtract :: Num -> Num -> Num
const subtract = x =>
y => y - x;
// tail :: [a] -> [a]
const tail = xs =>
// A new list consisting of all
// items of xs except the first.
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
Boolean(xs.length) ? (
xs.slice(1)
) : undefined
) : (take(1)(xs), xs);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}).flat();
// uncurry :: (a -> b -> c) -> ((a, b) -> c)
const uncurry = f =>
// A function over a pair, derived
// from a curried function.
(...args) => {
const [x, y] = Boolean(args.length % 2) ? (
args[0]
) : args;
return f(x)(y);
};
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs => ys => {
const
n = Math.min(length(xs), length(ys)),
vs = take(n)(ys);
return take(n)(xs)
.map((x, i) => [x, vs[i]]);
};
// MAIN ---
return main();
})();
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Shell "echo For i As Integer = 1 To 10 : Print i : Next > zzz.bas && fbc zzz.bas && zzz"
Sleep
|
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.
|
#Frink
|
Frink
|
$ frink -e "factorFlat[2^67-1]"
|
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.
|
#FutureBasic
|
FutureBasic
|
window 1,,(0,0,160,120):Str255 a:open "Unix",1,"cal 10 2018":do:line input #1,a:print a:until eof(1):close 1:HandleEvents
|
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.
|
#Axe
|
Axe
|
TEST(0,0)
TEST(0,1)
TEST(1,0)
TEST(1,1)
Return
Lbl TEST
r₁→X
r₂→Y
Disp X▶Hex+3," and ",Y▶Hex+3," = ",(A(X)?B(Y))▶Hex+3,i
Disp X▶Hex+3," or ",Y▶Hex+3," = ",(A(X)??B(Y))▶Hex+3,i
.Wait for keypress
getKeyʳ
Return
Lbl A
r₁
Return
Lbl B
r₁
Return
|
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.
|
#BaCon
|
BaCon
|
' Short-circuit evaluation
FUNCTION a(f)
PRINT "FUNCTION a"
RETURN f
END FUNCTION
FUNCTION b(f)
PRINT "FUNCTION b"
RETURN f
END FUNCTION
PRINT "FALSE and TRUE"
x = a(FALSE) AND b(TRUE)
PRINT x
PRINT "TRUE and TRUE"
x = a(TRUE) AND b(TRUE)
PRINT x
PRINT "FALSE or FALSE"
y = a(FALSE) OR b(FALSE)
PRINT y
PRINT "TRUE or FALSE"
y = a(TRUE) OR b(FALSE)
PRINT y
|
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
|
#AppleScript
|
AppleScript
|
-- asciiTable :: () -> String
on asciiTable()
script row
on |λ|(x)
concat(map(justifyLeft(12, space), x))
end |λ|
end script
unlines(map(row, ¬
transpose(chunksOf(16, map(my asciiEntry, ¬
enumFromTo(32, 127))))))
end asciiTable
-------------------------- TEST ---------------------------
on run
asciiTable()
end run
------------------------- DISPLAY -------------------------
-- asciiEntry :: Int -> String
on asciiEntry(n)
set k to asciiName(n)
if "" ≠ k then
justifyRight(4, space, n as string) & " : " & k
else
k
end if
end asciiEntry
-- asciiName :: Int -> String
on asciiName(n)
if 32 > n or 127 < n then
""
else if 32 = n then
"Spc"
else if 127 = n then
"Del"
else
chr(n)
end if
end asciiName
-------------------- GENERIC FUNCTIONS --------------------
-- chr :: Int -> Char
on chr(n)
character id n
end chr
-- chunksOf :: Int -> [a] -> [[a]]
on chunksOf(k, xs)
script
on go(ys)
set ab to splitAt(k, ys)
set a to |1| of ab
if {} ≠ a then
{a} & go(|2| of ab)
else
a
end if
end go
end script
result's go(xs)
end chunksOf
-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to lng
set acc to acc & item i of xs
end repeat
acc
end concat
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
if 0 < lng and class of xs is string then
set acc to ""
else
set acc to {}
end if
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & |λ|(item i of xs, i, xs)
end repeat
end tell
return acc
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller)
script
on |λ|(strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end |λ|
end script
end justifyLeft
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- splitAt :: Int -> [a] -> ([a],[a])
on splitAt(n, xs)
if n > 0 and n < length of xs then
if class of xs is text then
Tuple(items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text)
else
Tuple(items 1 thru n of xs, items (n + 1) thru -1 of xs)
end if
else
if n < 1 then
Tuple({}, xs)
else
Tuple(xs, {})
end if
end if
end splitAt
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- Simplified version - assuming rows of unvarying length.
-- transpose :: [[a]] -> [[a]]
on transpose(rows)
script cols
on |λ|(_, iCol)
script cell
on |λ|(row)
item iCol of row
end |λ|
end script
concatMap(cell, rows)
end |λ|
end script
map(cols, item 1 of rows)
end transpose
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
|
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
|
#Raku
|
Raku
|
#!/usr/bin/env raku
use JSON::Fast ;
sub MAIN( :$server='0.0.0.0', :$port=3333, :$dbfile='db' ) {
my %db;
my %index;
my $dbdata = slurp "$dbfile.json" ;
my $indexdata = slurp "{$dbfile}_index.json" ;
%db = from-json($dbdata) if $dbdata ;
%index = from-json($indexdata) if $indexdata ;
react {
whenever IO::Socket::Async.listen( $server , $port ) -> $conn {
whenever $conn.Supply.lines -> $line {
my %response = 'status' => '' ;
my $msg = from-json $line ;
say $msg.perl ;
given $msg<function> {
when 'set' {
%db{ $msg<topic> } = $msg<message> ;
%response<status> = 'ok' ;
%index<last_> = $msg<topic> ;
for %index<keys_>.keys -> $key {
if $msg<message>{$key} {
%index<lastkey_>{ $key }{ $msg<message>{$key} } = $msg<topic> ;
%index<idx_>{ $key }{ $msg<message>{$key} }{ $msg<topic> } = 1 ;
}
}
spurt "$dbfile.json", to-json(%db);
spurt "{$dbfile}_index.json", to-json(%index);
}
when 'get' {
%response<topic> = $msg<topic> ;
%response<message> = %db{ $msg<topic> } ;
%response<status> = 'ok' ;
}
when 'dump' {
%response{'data'} = %db ;
%response<status> = 'ok' ;
}
when 'dumpindex' {
%response{'data'} = %index ;
%response<status> = 'ok' ;
}
when 'delete' {
%db{ $msg<topic> }:delete;
%response<status> = 'ok' ;
spurt "$dbfile.json", to-json(%db);
reindex();
}
when 'addindex' {
%response<status> = 'ok' ;
%index<keys_>{ $msg<key>} =1 ;
reindex();
}
when 'reportlast' {
%response{'data'} = %db{%index<last_>} ;
%response<status> = 'ok' ;
}
when 'reportlastindex' {
%response<key> = $msg<key> ;
for %index<lastkey_>{$msg<key>}.keys -> $value {
#%response{'data'}.push: %db{ %index<lastkey_>{ $msg<key> }{ $value } } ;
%response{'data'}{$value} = %db{ %index<lastkey_>{ $msg<key> }{ $value } } ;
}
%response<status> = 'ok' ;
}
when 'reportindex' {
%response<status> = 'ok' ;
for %index<idx_>{$msg<key>}.keys.sort -> $value {
for %index<idx_>{ $msg<key> }{ $value }.keys.sort -> $topic {
%response<data>.push: %db{ $topic } ;
#%response<data>{$value} = %db{ $topic } ;
}
}
}
when 'commit' {
spurt "$dbfile.json", to-json(%db);
spurt "{$dbfile}_index.json", to-json(%index);
%response<status> = 'ok' ;
}
default {
%response<status> = 'error';
%response<error> = 'no function or not supported';
}
}
$conn.print( to-json(%response, :!pretty) ~ "\n" ) ;
LAST { $conn.close ; }
QUIT { default { $conn.close ; say "oh no, $_";}}
CATCH { default { say .^name, ': ', .Str , " handled in $?LINE";}}
}
}
}
sub reindex {
%index<idx_>:delete;
for %db.keys -> $topic {
my $msg = %db{$topic} ;
for %index<keys_>.keys -> $key {
if $msg{$key} {
%index<idx_>{ $key }{ $msg{$key} }{ $topic } = 1 ;
}
}
}
spurt "{$dbfile}_index.json", to-json(%index) ;
}
}
|
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
|
#UNIX_Shell
|
UNIX Shell
|
$ date -ur 0
Thu Jan 1 00:00:00 UTC 1970
|
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
|
#Visual_Basic
|
Visual Basic
|
Sub Main()
Debug.Print Format(0, "dd mmm yyyy hh:mm")
End Sub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.