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/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Julia | Julia | using Memoize
@memoize function scs(x, y)
if x == ""
return y
elseif y == ""
return x
elseif x[1] == y[1]
return "$(x[1])$(scs(x[2:end], y[2:end]))"
elseif length(scs(x, y[2:end])) <= length(scs(x[2:end], y))
return "$(y[1])$(scs(x, y[2:end]))"
else
return "$(x[1])$(scs(x[2:end], y))"
end
end
println(scs("abcbdab", "bdcaba"))
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Kotlin | Kotlin | // version 1.1.2
fun lcs(x: String, y: String): String {
if (x.length == 0 || y.length == 0) return ""
val x1 = x.dropLast(1)
val y1 = y.dropLast(1)
if (x.last() == y.last()) return lcs(x1, y1) + x.last()
val x2 = lcs(x, y1)
val y2 = lcs(x1, y)
return if (x2.length > y2.length) x2 else y2
}
fun scs(u: String, v: String): String{
val lcs = lcs(u, v)
var ui = 0
var vi = 0
val sb = StringBuilder()
for (i in 0 until lcs.length) {
while (ui < u.length && u[ui] != lcs[i]) sb.append(u[ui++])
while (vi < v.length && v[vi] != lcs[i]) sb.append(v[vi++])
sb.append(lcs[i])
ui++; vi++
}
if (ui < u.length) sb.append(u.substring(ui))
if (vi < v.length) sb.append(v.substring(vi))
return sb.toString()
}
fun main(args: Array<String>) {
val u = "abcbdab"
val v = "bdcaba"
println(scs(u, v))
} |
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
| #Kotlin | Kotlin | // version 1.1.2
import java.util.Date
import java.util.TimeZone
import java.text.DateFormat
fun main( args: Array<String>) {
val epoch = Date(0)
val format = DateFormat.getDateTimeInstance()
format.timeZone = TimeZone.getTimeZone("UTC")
println(format.format(epoch))
} |
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
| #Lasso | Lasso | date(0.00)
date(0) |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #VBA | VBA | Private Sub sierpinski(Order_ As Integer, Side As Double)
Dim Circumradius As Double, Inradius As Double
Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
Dim Pi As Double, p(5) As String, Shp As Shape
Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
Inradius = Sqr(25 + 10 * Sqr(5)) / 10
Height = Circumradius + Inradius
Diagonal = (1 + Sqr(5)) / 2
HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
Pi = WorksheetFunction.Pi
Ratio = Height / (2 * Height + HeightDiagonal)
'Get a base figure
Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
p(0) = Shp.Name
Shp.Rotation = 180
Shp.Line.Weight = 0
For j = 1 To Order_
'Place 5 copies of the figure in a circle around it
For i = 0 To 4
'Copy the figure
Set Shp = Shp.Duplicate
p(i + 1) = Shp.Name
If i = 0 Then Shp.Rotation = 0
'Place around in a circle
Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
Shp.Visible = msoTrue
Next i
'Group the 5 figures
Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
p(0) = Shp.Name
If j < Order_ Then
'Shrink the figure
Shp.ScaleHeight Ratio, False
Shp.ScaleWidth Ratio, False
'Flip vertical and place in the center
Shp.Rotation = 180
Shp.Left = 2 * Side
Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
End If
Next j
End Sub
Public Sub main()
sierpinski Order_:=5, Side:=200
End Sub |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
var Deg72 = 72 * Num.pi / 180 // 72 degrees in radians
var ScaleFactor = 1 / (2 + Math.cos(Deg72) * 2)
var Palette = [Color.red, Color.blue, Color.green, Color.indigo, Color.brown]
var ColorIndex = 0
var OldX = 0
var OldY = 0
class SierpinskiPentagon {
construct new(width, height) {
Window.title = "Sierpinksi Pentagon"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
}
init() {
var order = 5 // can also set this to 1, 2, 3, or 4
var hw = _w / 2
var margin = 20
var radius = hw - 2 * margin
var side = radius * Math.sin(Num.pi/5) * 2
drawPentagon(hw, 3 * margin, side, order - 1)
}
drawPentagon(x, y, side, depth) {
var angle = 3 * Deg72
if (depth == 0) {
var col = Palette[ColorIndex]
OldX = x
OldY = y
for (i in 0..4) {
x = x + Math.cos(angle) * side
y = y - Math.sin(angle) * side
Canvas.line(OldX, OldY, x, y, col, 2)
OldX = x
OldY = y
angle = angle + Deg72
}
ColorIndex = (ColorIndex + 1) % 5
} else {
side = side * ScaleFactor
var dist = side * (1 + Math.cos(Deg72) * 2)
for (i in 0..4) {
x = x + Math.cos(angle) * dist
y = y - Math.sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle = angle + Deg72
}
}
}
update() {}
draw(alpha) {}
}
var Game = SierpinskiPentagon.new(640, 640) |
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
| #Draco | Draco | word SIZE = 1 << 4;
proc nonrec main() void:
unsigned SIZE x, y;
for y from SIZE-1 downto 0 do
for x from 1 upto y do write(' ') od;
for x from 0 upto SIZE - y - 1 do
write(if x & y ~= 0 then " " else "* " fi)
od;
writeln()
od
corp |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Racket | Racket |
#lang racket
(require 2htdp/image)
(define (sierpinski n)
(if (zero? n)
(triangle 2 'solid 'red)
(let ([t (sierpinski (- n 1))])
(freeze (above t (beside t t))))))
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Raku | Raku | my $levels = 8;
my $side = 512;
my $height = get_height($side);
sub get_height ($side) { $side * 3.sqrt / 2 }
sub triangle ( $x1, $y1, $x2, $y2, $x3, $y3, $fill?, $animate? ) {
my $svg;
$svg ~= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"};
$svg ~= qq{ style="fill: $fill; stroke-width: 0;"} if $fill;
$svg ~= $animate
?? qq{>\n <animate attributeType="CSS" attributeName="opacity"\n values="1;0;1" keyTimes="0;.5;1" dur="20s" repeatCount="indefinite" />\n</polygon>}
!! ' />';
return $svg;
}
sub fractal ( $x1, $y1, $x2, $y2, $x3, $y3, $r is copy ) {
my $svg;
$svg ~= triangle( $x1, $y1, $x2, $y2, $x3, $y3 );
return $svg unless --$r;
my $side = abs($x3 - $x2) / 2;
my $height = get_height($side);
$svg ~= fractal( $x1, $y1-$height*2, $x1-$side/2, $y1-3*$height, $x1+$side/2, $y1-3*$height, $r);
$svg ~= fractal( $x2, $y1, $x2-$side/2, $y1-$height, $x2+$side/2, $y1-$height, $r);
$svg ~= fractal( $x3, $y1, $x3-$side/2, $y1-$height, $x3+$side/2, $y1-$height, $r);
}
my $fh = open('sierpinski_triangle.svg', :w) orelse .die;
$fh.print: qq:to/EOD/,
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<radialGradient id="basegradient" cx="50%" cy="65%" r="50%" fx="50%" fy="65%">
<stop offset="10%" stop-color="#ff0" />
<stop offset="60%" stop-color="#f00" />
<stop offset="99%" stop-color="#00f" />
</radialGradient>
</defs>
EOD
triangle( $side/2, 0, 0, $height, $side, $height, 'url(#basegradient)' ),
triangle( $side/2, 0, 0, $height, $side, $height, '#000', 'animate' ),
'<g style="fill: #fff; stroke-width: 0;">',
fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ),
'</g></svg>'; |
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
| #ALGOL_W | ALGOL W | begin
for depth := 3 do begin
integer dim;
dim := 1;
for i := 0 until depth - 1 do dim := dim * 3;
for i := 0 until dim - 1 do begin
for j := 0 until dim - 1 do begin
integer d;
d := dim div 3;
while d not = 0
and not ( ( i rem ( d * 3 ) ) div d = 1 and ( j rem ( d * 3 ) ) div d = 1 )
do d := d div 3;
writeon( if d not = 0 then " " else "##" )
end for_j;
write()
end for_i;
write()
end for_depth
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.
| #360_Assembly | 360 Assembly | * SHOELACE 25/02/2019
SHOELACE CSECT
USING SHOELACE,R15 base register
MVC SUPS(8),POINTS x(nt+1)=x(1); y(nt+1)=y(1)
LA R9,0 area=0
LA R7,POINTS @x(1)
LA R6,NT do i=1 to nt
LOOP L R3,0(R7) x(i)
M R2,12(R7) *y(i+1)
L R5,8(R7) x(i+1)
M R4,4(R7) *y(i)
SR R3,R5 x(i)*y(i+1)-x(i+1)*y(i)
AR R9,R3 area=area+x(i)*y(i+1)-x(i+1)*y(i)
LA R7,8(R7) @x(i++)
BCT R6,LOOP enddo
LPR R9,R9 area=abs(area)
SRA R9,1 area=area/2
XDECO R9,PG edit area
XPRNT PG,L'PG print area
BR R14 return to caller
NT EQU (SUPS-POINTS)/8 nt number of points
POINTS DC F'3',F'4',F'5',F'11',F'12',F'8',F'9',F'5',F'5',F'6'
SUPS DS 2F x(nt+1),y(nt+1)
PG DC CL12' ' buffer
REGEQU
END SHOELACE |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC Area(INT ARRAY xs,ys BYTE count REAL POINTER res)
BYTE i,next
REAL x1,y1,x2,y2,tmp1,tmp2
IntToReal(0,res)
IntToReal(xs(0),x1) IntToReal(ys(0),y1)
FOR i=0 TO count-1
DO
next=i+1
IF next=count THEN
next=0
FI
IntToReal(xs(next),x2) IntToReal(ys(next),y2)
RealMult(x1,y2,tmp1)
RealAdd(res,tmp1,tmp2)
RealMult(x2,y1,tmp1)
RealSub(tmp2,tmp1,res)
RealAssign(x2,x1) RealAssign(y2,y1)
OD
RealAbs(res,tmp1)
IntToReal(2,tmp2)
RealDiv(tmp1,tmp2,res)
RETURN
PROC PrintPolygon(INT ARRAY xs,ys BYTE count)
BYTE i
FOR i=0 TO count-1
DO
PrintF("(%I,%I)",xs(i),ys(i))
IF i<count-1 THEN
Print(", ")
ELSE
PutE()
FI
OD
RETURN
PROC Test(INT ARRAY xs,ys BYTE count)
REAL res
Area(xs,ys,count,res)
Print("Polygon: ")
PrintPolygon(xs,ys,count)
Print("Area: ")
PrintRE(res) PutE()
RETURN
PROC Main()
INT ARRAY
xs(5)=[3 5 12 9 5],
ys(5)=[4 11 8 5 6]
Put(125) PutE() ;clear screen
Test(xs,ys,5)
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
| #Forth | Forth | +: betty 1974.03.03;coworker;reading;
+: geea 1980.01.01;friend;sketch writer;
+: tom 1991.03.07;family member;reading;
+: alice 1987.09.01;coworker;classical music;
+: gammaQ3.14 3045.09.09;friend;watch movies, star walking;
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[RosettaShortestCommonSuperSequence]
RosettaShortestCommonSuperSequence[aa_String, bb_String] :=
Module[{lcs, scs, a = aa, b = bb},
lcs = LongestCommonSubsequence[aa, bb];
scs = "";
While[StringLength[lcs] > 0,
If[StringTake[a, 1] == StringTake[lcs, 1] \[And] StringTake[b, 1] == StringTake[lcs, 1],
scs = StringJoin[scs, StringTake[lcs, 1]];
lcs = StringDrop[lcs, 1];
a = StringDrop[a, 1];
b = StringDrop[b, 1];
,
If[StringTake[a, 1] == StringTake[lcs, 1],
scs = StringJoin[scs, StringTake[b, 1]];
b = StringDrop[b, 1];
,
scs = StringJoin[scs, StringTake[a, 1]];
a = StringDrop[a, 1];
]
]
];
StringJoin[scs, a, b]
]
RosettaShortestCommonSuperSequence["abcbdab", "bdcaba"]
RosettaShortestCommonSuperSequence["WEASELS", "WARDANCE"] |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Nim | Nim | proc lcs(x, y: string): string =
if x.len == 0 or y.len == 0: return
let x1 = x[0..^2]
let y1 = y[0..^2]
if x[^1] == y[^1]: return lcs(x1, y1) & x[^1]
let x2 = lcs(x, y1)
let y2 = lcs(x1, y)
result = if x2.len > y2.len: x2 else: y2
proc scs(u, v: string): string =
let lcs = lcs(u, v)
var ui, vi = 0
for ch in lcs:
while ui < u.len and u[ui] != ch:
result.add u[ui]
inc ui
while vi < v.len and v[vi] != ch:
result.add v[vi]
inc vi
result.add ch
inc ui
inc vi
if ui < u.len: result.add u.substr(ui)
if vi < v.len: result.add v.substr(vi)
when isMainModule:
let u = "abcbdab"
let v = "bdcaba"
echo scs(u, v) |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Perl | Perl | sub lcs { # longest common subsequence
my( $u, $v ) = @_;
return '' unless length($u) and length($v);
my $longest = '';
for my $first ( 0..length($u)-1 ) {
my $char = substr $u, $first, 1;
my $i = index( $v, $char );
next if -1==$i;
my $next = $char;
$next .= lcs( substr( $u, $first+1), substr( $v, $i+1 ) ) unless $i==length($v)-1;
$longest = $next if length($next) > length($longest);
}
return $longest;
}
sub scs { # shortest common supersequence
my( $u, $v ) = @_;
my @lcs = split //, lcs $u, $v;
my $pat = "(.*)".join("(.*)",@lcs)."(.*)";
my @u = $u =~ /$pat/;
my @v = $v =~ /$pat/;
my $scs = shift(@u).shift(@v);
$scs .= $_.shift(@u).shift(@v) for @lcs;
return $scs;
}
my $u = "abcbdab";
my $v = "bdcaba";
printf "Strings %s %s\n", $u, $v;
printf "Longest common subsequence: %s\n", lcs $u, $v;
printf "Shortest common supersquence: %s\n", scs $u, $v;
|
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
| #Limbo | Limbo | implement Epoch;
include "sys.m"; sys: Sys;
include "draw.m";
include "daytime.m"; daytime: Daytime;
Tm: import daytime;
Epoch: module {
init: fn(nil: ref Draw->Context, nil: list of string);
};
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
daytime = load Daytime Daytime->PATH;
sys->print("%s\n", daytime->text(daytime->gmt(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
| #Lingo | Lingo | now = the systemDate
put now
-- date( 2018, 3, 21 )
babylonianDate = date(-1800,1,1)
-- print approx. year difference between "babylonianDate" and now
put (now-babylonianDate)/365.2425
-- 3818.1355 |
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
| #LiveCode | LiveCode | put 0 into somedate
convert somedate to internet date
put somedate
-- output GMT (localised)
-- Thu, 1 Jan 1970 10:00:00 +1000
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #zkl | zkl | const order=5, sides=5, dim=250, scaleFactor=((3.0 - (5.0).pow(0.5))/2);
const tau=(0.0).pi*2; // 2*pi*r
orders:=order.pump(List,fcn(n){ (1.0 - scaleFactor)*dim*scaleFactor.pow(n) });
println(
#<<<
0'|<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="%d" width="%d" style="fill:blue" transform="translate(%d,%d) rotate(-18)"
version="1.1" xmlns="http://www.w3.org/2000/svg">|
#<<<
.fmt(dim*2,dim*2,dim,dim));
vertices:=sides.pump(List,fcn(s){ (1.0).toRectangular(tau*s/sides) }); // points on unit circle
vx:=vertices.apply('wrap([(a,b)]v,x){ return(a*x,b*x) }, // scaled points
orders[-1]*(1.0 - scaleFactor));
fmt:="%%0%d.%dB".fmt(sides,order).fmt; //-->%05.5B (leading zeros, 5 places, base 5)
sides.pow(order).pump(Console.println,'wrap(i){
vector:=fmt(i).pump(List,vertices.get) // "00012"-->(vertices[0],..,vertices[2])
.zipWith(fcn([(a,b)]v,x){ return(a*x,b*x) },orders) // ((a,b)...)*x -->((ax,bx)...)
.reduce(fcn(vsum,v){ vsum[0]+=v[0]; vsum[1]+=v[1]; vsum },L(0.0, 0.0)); //-->(x,y)
pgon(vx.apply(fcn([(a,b)]v,c,d){ return(a+c,b+d) },vector.xplode()));
});
println("</svg>"); // 3,131 lines
fcn pgon(vertices){ // eg ( ((250,0),(248.595,1.93317),...), len 5
0'|<polygon points="%s"/>|.fmt(
vertices.pump(String,fcn(v){ "%.3f %.3f ".fmt(v.xplode()) }) )
} |
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
| #DWScript | DWScript | procedure PrintSierpinski(order : Integer);
var
x, y, size : Integer;
begin
size := (1 shl order)-1;
for y:=size downto 0 do begin
Print(StringOfChar(' ', y));
for x:=0 to size-y do begin
if (x and y)=0 then
Print('* ')
else Print(' ');
end;
PrintLn('');
end;
end;
PrintSierpinski(4);
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Ring | Ring |
load "guilib.ring"
new qapp
{
win1 = new qwidget() {
setwindowtitle("drawing using qpainter")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(200,400,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
new qpainter() {
begin(p1)
setpen(pen)
order = 7
size = pow(2,order)
for y = 0 to size-1
for x = 0 to size-1
if (x & y)=0 drawpoint(x*2,y*2) ok
next
next
endpaint()
}
label1 { setpicture(p1) show() }
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Ruby | Ruby | Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do
def triangle(slot, tri, color)
x, y, len = tri
slot.append do
fill color
shape do
move_to(x,y)
dx = len * Math::cos(Math::PI/3)
dy = len * Math::sin(Math::PI/3)
line_to(x-dx, y+dy)
line_to(x+dx, y+dy)
line_to(x,y)
end
end
end
@s = stack(:width => 520, :height => 520) {}
@s.move(10,10)
length = 512
@triangles = [[length/2,0,length]]
triangle(@s, @triangles[0], rgb(0,0,0))
@n = 1
animate(1) do
if @n <= 7
@triangles = @triangles.inject([]) do |sum, (x, y, len)|
dx = len/2 * Math::cos(Math::PI/3)
dy = len/2 * Math::sin(Math::PI/3)
triangle(@s, [x, y+2*dy, -len/2], rgb(255,255,255))
sum += [[x, y, len/2], [x-dx, y+dy, len/2], [x+dx, y+dy, len/2]]
end
end
@n += 1
end
keypress do |key|
case key
when :control_q, "\x11" then exit
end
end
end |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #APL | APL | carpet←{{⊃⍪/,⌿3 3⍴4 0 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.
| #Ada | Ada | with Ada.Text_IO;
procedure Shoelace_Formula_For_Polygonal_Area
is
type Point is record
x, y : Float;
end record;
type Polygon is array (Positive range <>) of Point;
function Shoelace(input : in Polygon) return Float
is
sum_1 : Float := 0.0;
sum_2 : Float := 0.0;
tmp : constant Polygon := input & input(input'First);
begin
for I in tmp'First .. tmp'Last - 1 loop
sum_1 := sum_1 + tmp(I).x * tmp(I+1).y;
sum_2 := sum_2 + tmp(I+1).x * tmp(I).y;
end loop;
return abs(sum_1 - sum_2) / 2.0;
end Shoelace;
my_polygon : constant Polygon :=
((3.0, 4.0),
(5.0, 11.0),
(12.0, 8.0),
(9.0, 5.0),
(5.0, 6.0));
begin
Ada.Text_IO.Put_Line(Shoelace(my_polygon)'Img);
end Shoelace_Formula_For_Polygonal_Area; |
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
| #Go | Go | package main
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strings"
"time"
"unicode"
)
// Database record format. Time stamp and name are required.
// Tags and notes are optional.
type Item struct {
Stamp time.Time
Name string
Tags []string `json:",omitempty"`
Notes string `json:",omitempty"`
}
// Item implements stringer interface
func (i *Item) String() string {
s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name
if len(i.Tags) > 0 {
s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags)
}
if i.Notes > "" {
s += "\n Notes: " + i.Notes
}
return s
}
// collection of Items
type db []*Item
// db implements sort.Interface
func (d db) Len() int { return len(d) }
func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) }
// hard coded database file name
const fn = "sdb.json"
func main() {
if len(os.Args) == 1 {
latest()
return
}
switch os.Args[1] {
case "add":
add()
case "latest":
latest()
case "tags":
tags()
case "all":
all()
case "help":
help()
default:
usage("unrecognized command")
}
}
func usage(err string) {
if err > "" {
fmt.Println(err)
}
fmt.Println(`usage: sdb [command] [data]
where command is one of add, latest, tags, all, or help.`)
}
func help() {
usage("")
fmt.Println(`
Commands must be in lower case.
If no command is specified, the default command is latest.
Latest prints the latest item.
All prints all items in chronological order.
Tags prints the lastest item for each tag.
Help prints this message.
Add adds data as a new record. The format is,
name [tags] [notes]
Name is the name of the item and is required for the add command.
Tags are optional. A tag is a single word.
A single tag can be specified without enclosing brackets.
Multiple tags can be specified by enclosing them in square brackets.
Text remaining after tags is taken as notes. Notes do not have to be
enclosed in quotes or brackets. The brackets above are only showing
that notes are optional.
Quotes may be useful however--as recognized by your operating system shell
or command line--to allow entry of arbitrary text. In particular, quotes
or escape characters may be needed to prevent the shell from trying to
interpret brackets or other special characters.
Examples:
sdb add Bookends // no tags, no notes
sdb add Bookends rock my favorite // tag: rock, notes: my favorite
sdb add Bookends [rock folk] // two tags
sdb add Bookends [] "Simon & Garfunkel" // notes, no tags
sdb add "Simon&Garfunkel [artist]" // name: Simon&Garfunkel, tag: artist
As shown in the last example, if you use features of your shell to pass
all data as a single string, the item name and tags will still be identified
by separating whitespace.
The database is stored in JSON format in the file "sdb.json"
`)
}
// load data for read only purposes.
func load() (db, bool) {
d, f, ok := open()
if ok {
f.Close()
if len(d) == 0 {
fmt.Println("no items")
ok = false
}
}
return d, ok
}
// open database, leave open
func open() (d db, f *os.File, ok bool) {
var err error
f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Println("cant open??")
fmt.Println(err)
return
}
jd := json.NewDecoder(f)
err = jd.Decode(&d)
// EOF just means file was empty. That's okay with us.
if err != nil && err != io.EOF {
fmt.Println(err)
f.Close()
return
}
ok = true
return
}
// handle latest command
func latest() {
d, ok := load()
if !ok {
return
}
sort.Sort(d)
fmt.Println(d[len(d)-1])
}
// handle all command
func all() {
d, ok := load()
if !ok {
return
}
sort.Sort(d)
for _, i := range d {
fmt.Println("-----------------------------------")
fmt.Println(i)
}
fmt.Println("-----------------------------------")
}
// handle tags command
func tags() {
d, ok := load()
if !ok {
return
}
// we have to traverse the entire list to collect tags so there
// is no point in sorting at this point.
// collect set of unique tags associated with latest item for each
latest := make(map[string]*Item)
for _, item := range d {
for _, tag := range item.Tags {
li, ok := latest[tag]
if !ok || item.Stamp.After(li.Stamp) {
latest[tag] = item
}
}
}
// invert to set of unique items, associated with subset of tags
// for which the item is the latest.
type itemTags struct {
item *Item
tags []string
}
inv := make(map[*Item][]string)
for tag, item := range latest {
inv[item] = append(inv[item], tag)
}
// now we sort just the items we will output
li := make(db, len(inv))
i := 0
for item := range inv {
li[i] = item
i++
}
sort.Sort(li)
// finally ready to print
for _, item := range li {
tags := inv[item]
fmt.Println("-----------------------------------")
fmt.Println("Latest item with tags", tags)
fmt.Println(item)
}
fmt.Println("-----------------------------------")
}
// handle add command
func add() {
if len(os.Args) < 3 {
usage("add command requires data")
return
} else if len(os.Args) == 3 {
add1()
} else {
add4()
}
}
// add command with one data string. look for ws as separators.
func add1() {
data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace)
if data == "" {
// data must have at least some non-whitespace
usage("invalid name")
return
}
sep := strings.IndexFunc(data, unicode.IsSpace)
if sep < 0 {
// data consists only of a name
addItem(data, nil, "")
return
}
name := data[:sep]
data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace)
if data == "" {
// nevermind trailing ws, it's still only a name
addItem(name, nil, "")
return
}
if data[0] == '[' {
sep = strings.Index(data, "]")
if sep < 0 {
// close bracketed list for the user. no notes.
addItem(name, strings.Fields(data[1:]), "")
} else {
// brackets make things easy
addItem(name, strings.Fields(data[1:sep]),
strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))
}
return
}
sep = strings.IndexFunc(data, unicode.IsSpace)
if sep < 0 {
// remaining word is a tag
addItem(name, []string{data}, "")
} else {
// there's a tag and some data
addItem(name, []string{data[:sep]},
strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace))
}
}
// add command with multiple strings remaining on command line
func add4() {
name := os.Args[2]
tag1 := os.Args[3]
if tag1[0] != '[' {
// no brackets makes things easy
addItem(name, []string{tag1}, strings.Join(os.Args[4:], " "))
return
}
if tag1[len(tag1)-1] == ']' {
// tags all in one os.Arg is easy too
addItem(name, strings.Fields(tag1[1:len(tag1)-1]),
strings.Join(os.Args[4:], " "))
return
}
// start a list for tags
var tags []string
if tag1 > "[" {
tags = []string{tag1[1:]}
}
for x, tag := range os.Args[4:] {
if tag[len(tag)-1] != ']' {
tags = append(tags, tag)
} else {
// found end of tag list
if tag > "]" {
tags = append(tags, tag[:len(tag)-1])
}
addItem(name, tags, strings.Join(os.Args[5+x:], " "))
return
}
}
// close bracketed list for the user. no notes.
addItem(name, tags, "")
}
// complete the add command
func addItem(name string, tags []string, notes string) {
db, f, ok := open()
if !ok {
return
}
defer f.Close()
// add the item and format JSON
db = append(db, &Item{time.Now(), name, tags, notes})
sort.Sort(db)
js, err := json.MarshalIndent(db, "", " ")
if err != nil {
fmt.Println(err)
return
}
// time to overwrite the file
if _, err = f.Seek(0, 0); err != nil {
fmt.Println(err)
return
}
f.Truncate(0)
if _, err = f.Write(js); err != nil {
fmt.Println(err)
}
} |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Phix | Phix | with javascript_semantics
function longest_common_subsequence(sequence a, b)
sequence res = ""
if length(a) and length(b) then
if a[$]=b[$] then
res = longest_common_subsequence(a[1..-2],b[1..-2])&a[$]
else
sequence l = longest_common_subsequence(a,b[1..-2]),
r = longest_common_subsequence(a[1..-2],b)
res = iff(length(l)>length(r)?l:r)
end if
end if
return res
end function
function shortest_common_supersequence(string a, b)
string lcs = longest_common_subsequence(a, b),
scs = ""
-- Consume lcs
while length(lcs) do
integer c = lcs[1]
if a[1]==c and b[1]==c then
-- Part of the lcs, so consume from all strings
scs &= c
lcs = lcs[2..$]
a = a[2..$]
b = b[2..$]
elsif a[1]==c then
scs &= b[1]
b = b[2..$]
else
scs &= a[1]
a = a[2..$]
end if
end while
-- append remaining characters
return scs & a & b
end function
?shortest_common_supersequence("abcbdab", "bdcaba")
?shortest_common_supersequence("WEASELS", "WARDANCE")
|
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
| #LotusScript | LotusScript |
Sub Click(Source As Button)
'Create timestamp as of now
Dim timeStamp As NotesDateTime
Set timeStamp = New NotesDateTime ( Now )
'Assign epoch start time to variable
Dim epochTime As NotesDateTime
Set epochTime = New NotesDateTime ( "01/01/1970 00:00:00 AM GMT" ) ''' These two commands only to get epoch time.
'Calculate time difference between both dates
Dim epochSeconds As Long
epochSeconds = timeStamp.TimeDifference ( epochTime )
'Print result
Print epochSeconds
End Sub
|
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
| #Lua | Lua | print(os.date("%c", 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
| #E | E | def printSierpinski(order, out) {
def size := 2**order
for y in (0..!size).descending() {
out.print(" " * y)
for x in 0..!(size-y) {
out.print((x & y).isZero().pick("* ", " "))
}
out.println()
}
} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
const SQRT3_2: f64 = 0.86602540378444;
fn sierpinski_triangle(
mut document: svg::Document,
mut x: f64,
mut y: f64,
mut side: f64,
order: usize,
) -> svg::Document {
use svg::node::element::Polygon;
if order == 1 {
let mut points = Vec::new();
points.push((x, y));
y += side * SQRT3_2;
x -= side * 0.5;
points.push((x, y));
x += side;
points.push((x, y));
let polygon = Polygon::new()
.set("fill", "black")
.set("stroke", "none")
.set("points", points);
document = document.add(polygon);
} else {
side *= 0.5;
document = sierpinski_triangle(document, x, y, side, order - 1);
y += side * SQRT3_2;
x -= side * 0.5;
document = sierpinski_triangle(document, x, y, side, order - 1);
x += side;
document = sierpinski_triangle(document, x, y, side, order - 1);
}
document
}
fn write_sierpinski_triangle(file: &str, size: usize, order: usize) -> std::io::Result<()> {
use svg::node::element::Rectangle;
let margin = 20.0;
let side = (size as f64) - 2.0 * margin;
let y = 0.5 * ((size as f64) - SQRT3_2 * side);
let x = margin + side * 0.5;
let rect = Rectangle::new()
.set("width", "100%")
.set("height", "100%")
.set("fill", "white");
let mut document = svg::Document::new()
.set("width", size)
.set("height", size)
.add(rect);
document = sierpinski_triangle(document, x, y, side, order);
svg::save(file, &document)
}
fn main() {
write_sierpinski_triangle("sierpinski_triangle.svg", 600, 8).unwrap();
} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
include "bin64.s7i";
const proc: main is func
local
const integer: order is 8;
const integer: width is 1 << order;
const integer: margin is 10;
var integer: x is 0;
var integer: y is 0;
begin
screen(width + 2 * margin, width + 2 * margin);
clear(curr_win, white);
KEYBOARD := GRAPH_KEYBOARD;
for y range 0 to pred(width) do
for x range 0 to pred(width) do
if bin64(x) & bin64(y) = bin64(0) then
point(margin + x, margin + y, black);
end if;
end for;
end for;
ignore(getc(KEYBOARD));
end func; |
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
| #AppleScript | AppleScript | ----------------------- CARPET MODEL ---------------------
-- sierpinskiCarpet :: Int -> [[Bool]]
on sierpinskiCarpet(n)
-- rowStates :: Int -> [Bool]
script rowStates
on |λ|(x, _, xs)
-- cellState :: Int -> Bool
script cellState
-- inCarpet :: Int -> Int -> Bool
on inCarpet(x, y)
if (0 = x or 0 = y) then
true
else
not ((1 = x mod 3) and ¬
(1 = y mod 3)) and ¬
inCarpet(x div 3, y div 3)
end if
end inCarpet
on |λ|(y)
inCarpet(x, y)
end |λ|
end script
map(cellState, xs)
end |λ|
end script
map(rowStates, enumFromTo(0, (3 ^ n) - 1))
end sierpinskiCarpet
--------------------------- TEST -------------------------
on run
-- Carpets of orders 1, 2, 3
set strCarpets to ¬
intercalate(linefeed & linefeed, ¬
map(showCarpet, enumFromTo(1, 3)))
set the clipboard to strCarpets
return strCarpets
end run
---------------------- CARPET DISPLAY --------------------
-- showCarpet :: Int -> String
on showCarpet(n)
-- showRow :: [Bool] -> String
script showRow
-- showBool :: Bool -> String
script showBool
on |λ|(bool)
if bool then
character id 9608
else
" "
end if
end |λ|
end script
on |λ|(xs)
intercalate("", map(my showBool, xs))
end |λ|
end script
intercalate(linefeed, map(showRow, sierpinskiCarpet(n)))
end showCarpet
-------------------- GENERIC FUNCTIONS -------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set xs to {}
repeat with i from m to n
set end of xs to i
end repeat
xs
else
{}
end if
end enumFromTo
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- 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 :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/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.
| #ALGOL_60 | ALGOL 60 | begin
comment Shoelace formula for polygonal area - Algol 60;
real array x[1:33],y[1:33];
integer i,n;
real a;
ininteger(0,n);
for i:=1 step 1 until n do
begin
inreal(0,x[i]);
inreal(0,y[i])
end;
x[i]:=x[1];
y[i]:=y[1];
a:=0;
for i:=1 step 1 until n do
a:=a+x[i]*y[i+1]-x[i+1]*y[i];
a:=abs(a/2.);
outreal(1,a)
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.
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns the area of the polygon defined by the points p using the Shoelace formula #
OP AREA = ( [,]REAL p )REAL:
BEGIN
[,]REAL points = p[ AT 1, AT 1 ]; # normalise array bounds to start at 1 #
IF 2 UPB points /= 2 THEN
# the points do not have 2 coordinates #
-1
ELSE
REAL result := 0;
INT n = 1 UPB points;
IF n > 1 THEN
# there at least two points #
[]REAL x = points[ :, 1 ];
[]REAL y = points[ :, 2 ];
FOR i TO 1 UPB points - 1 DO
result +:= x[ i ] * y[ i + 1 ];
result -:= x[ i + 1 ] * y[ i ]
OD;
result +:= x[ n ] * y[ 1 ];
result -:= x[ 1 ] * y[ n ]
FI;
( ABS result ) / 2
FI
END # AREA # ;
# test case as per the task #
print( ( fixed( AREA [,]REAL( ( 3.0, 4.0 ), ( 5.0, 11.0 ), ( 12.0, 8.0 ), ( 9.0, 5.0 ), ( 5.0, 6.0 ) ), -6, 2 ), newline ) )
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
| #Haskell | Haskell | import Control.Monad.State
import Data.List (sortBy, nub)
import System.Environment (getArgs, getProgName)
import System.Directory (doesFileExist)
import System.IO (openFile, hGetContents, hClose, IOMode(..),
Handle, hPutStrLn)
-- for storing dates
data Date = Date Integer Int Int deriving (Show, Read, Eq, Ord)
-- for storing database items
data Item = Item {description :: String
,category :: [String]
,date :: Date
,optional :: [String]}
deriving (Show, Read)
-- a state monad transformer which wraps IO actions.
-- the database (state) is passed implicitly between functions.
type ItemList a = StateT [Item] IO a
-- add an item to the database
addItem :: Item -> ItemList ()
addItem i = modify (++ [i])
-- get the newest of a list of items
latest :: [Item] -> [Item]
latest [] = []
latest [x]= [x]
latest xs = take 1 $ sortBy newer xs
-- compare two items to see which one is newer
newer :: Item -> Item -> Ordering
newer a b = compare (date b) (date a)
-- list all different categories (no duplicates)
categories :: ItemList [String]
categories = liftM (nub . concatMap category) get
-- list only the items with the given category tag
filterByCategory :: String -> ItemList [Item]
filterByCategory c = liftM (filter (\i -> c `elem` category i)) get
-- get the newest of all items
lastOfAll :: ItemList [Item]
lastOfAll = liftM latest get
-- get the newest item in each category
latestByCategory :: ItemList [Item]
latestByCategory = do
cats <- categories
filt <- mapM filterByCategory cats
return $ concatMap latest filt
-- sort all items chronologically, newest first
sortByDate :: ItemList [Item]
sortByDate = liftM (sortBy newer) get
toScreen :: Item -> IO ()
toScreen (Item desc cats (Date y m d) opt) = putStrLn $
"Description:\t" ++ desc ++ "\nCategories:\t" ++ show cats ++
"\nDate:\t\t" ++ show y ++ "-" ++ show m ++ "-" ++ show d ++
"\nOther info:\t" ++ show opt
-- command line argument handling
-- if the user called the program with the option "add", the
-- new item is returned to main so that it can be saved to disk.
-- the argument "opt" is a list.
arguments :: ItemList [Item]
arguments = do
args <- liftIO getArgs
case args of
("add":desc:cat:year:month:day:opt) -> do
let newItem = parseItem args
addItem newItem
return [newItem]
("latest":[]) -> do
item <- lastOfAll
lift $ mapM_ toScreen item
return []
("category":[]) -> do
items <- latestByCategory
lift $ mapM_ toScreen items
return []
("all":[]) -> do
sorted <- sortByDate
lift $ mapM_ toScreen sorted
return []
_ -> do
lift usage
return []
parseItem :: [String] -> Item
parseItem (_:desc:cat:year:month:day:opt) =
Item {description = desc, category = words cat,
date = Date (read year) (read month) (read day),
optional = opt}
usage :: IO ()
usage = do
progName <- getProgName
putStrLn $ "Usage: " ++ progName ++ " add|all|category|latest \
\OPTIONS\n\nadd \"description\" \"category1 category2\"... \
\year month day [\"note1\" \"note2\"...]\n\tAdds a new record \
\to the database.\n\nall\n\tPrints all items in chronological \
\order.\n\ncategory\n\tPrints the latest item for each category.\
\\n\nlatest\n\tPrints the latest item."
-- the program creates, reads and writes to a file in the current directory
main :: IO ()
main = do
progName <- getProgName
let fileName = progName ++ ".db"
e <- doesFileExist fileName
if e
then do
hr <- openFile fileName ReadMode
f <- hGetContents hr
v <- evalStateT arguments (map read $ lines f)
hClose hr -- must be called after working with contents!
hw <- openFile fileName AppendMode
mapM_ (hPutStrLn hw . show) v
hClose hw
else do
v <- evalStateT arguments []
hw <- openFile fileName WriteMode
mapM_ (hPutStrLn hw . show) v
hClose hw
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Python | Python |
# Use the Longest Common Subsequence algorithm
def shortest_common_supersequence(a, b):
lcs = longest_common_subsequence(a, b)
scs = ""
# Consume lcs
while len(lcs) > 0:
if a[0]==lcs[0] and b[0]==lcs[0]:
# Part of the LCS, so consume from all strings
scs += lcs[0]
lcs = lcs[1:]
a = a[1:]
b = b[1:]
elif a[0]==lcs[0]:
scs += b[0]
b = b[1:]
else:
scs += a[0]
a = a[1:]
# append remaining characters
return scs + a + b
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Racket | Racket | #lang racket
(struct link (len letters))
(define (link-add li n letter)
(link (+ n (link-len li))
(cons letter (link-letters li))))
(define (memoize f)
(local ([define table (make-hash)])
(lambda args
(dict-ref! table args (λ () (apply f args))))))
(define scs/list
(memoize
(lambda (x y)
(cond
[(null? x)
(link (length y) y)]
[(null? y)
(link (length x) x)]
[(eq? (car x) (car y))
(link-add (scs/list (cdr x) (cdr y)) 1 (car x))]
[(<= (link-len (scs/list x (cdr y)))
(link-len (scs/list (cdr x) y)))
(link-add (scs/list x (cdr y)) 1 (car y))]
[else
(link-add (scs/list (cdr x) y) 1 (car x))]))))
(define (scs x y)
(list->string (link-letters (scs/list (string->list x) (string->list y)))))
(scs "abcbdab" "bdcaba") |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Raku | Raku | sub lcs(Str $xstr, Str $ystr) { # longest common subsequence
return "" unless $xstr && $ystr;
my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1);
return $x eq $y
?? $x ~ lcs($xs, $ys)
!! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) );
}
sub scs ($u, $v) { # shortest common supersequence
my @lcs = (lcs $u, $v).comb;
my $pat = '(.*)' ~ join('(.*)',@lcs) ~ '(.*)';
my $regex = "rx/$pat/".EVAL;
my @u = ($u ~~ $regex).list;
my @v = ($v ~~ $regex).list;
my $scs = shift(@u) ~ shift(@v);
$scs ~= $_ ~ shift(@u) ~ shift(@v) for @lcs;
return $scs;
}
my $u = 'abcbdab';
my $v = 'bdcaba';
printf "Strings: %s %s\n", $u, $v;
printf "Longest common subsequence: %s\n", lcs $u, $v;
printf "Shortest common supersquence: %s\n", scs $u, $v; |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DateString[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
| #MATLAB_.2F_Octave | MATLAB / Octave | d = [0,1,2,3.5,-3.5,1000*365,1000*366,now+[-1,0,1]];
for k=1:length(d)
printf('day %f\t%s\n',d(k),datestr(d(k),0))
disp(datevec(d(k)))
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
| #Elixir | Elixir | defmodule RC do
def sierpinski_triangle(n) do
f = fn(x) -> IO.puts "#{x}" end
Enum.each(triangle(n, ["*"], " "), f)
end
defp triangle(0, down, _), do: down
defp triangle(n, down, sp) do
newDown = (for x <- down, do: sp<>x<>sp) ++ (for x <- down, do: x<>" "<>x)
triangle(n-1, newDown, sp<>sp)
end
end
RC.sierpinski_triangle(4) |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Sidef | Sidef | func sierpinski_triangle(n) -> Array {
var triangle = ['*']
{ |i|
var sp = (' ' * 2**i)
triangle = (triangle.map {|x| sp + x + sp} +
triangle.map {|x| x + ' ' + x})
} * n
triangle
}
class Array {
method to_png(scale=1, bgcolor='white', fgcolor='black') {
static gd = require('GD::Simple')
var width = self.max_by{.len}.len
self.map!{|r| "%-#{width}s" % r}
var img = gd.new(width * scale, self.len * scale)
for i in ^self {
for j in RangeNum(i*scale, i*scale + scale) {
img.moveTo(0, j)
for line in (self[i].scan(/(\s+|\S+)/)) {
img.fgcolor(line.contains(/\S/) ? fgcolor : bgcolor)
img.line(scale * line.len)
}
}
}
img.png
}
}
var triangle = sierpinski_triangle(8)
var raw_png = triangle.to_png(bgcolor:'black', fgcolor:'red')
File('triangle.png').write(raw_png, :raw) |
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
| #Applesoft_BASIC | Applesoft BASIC | 100 HGR
110 POKE 49234,0
120 DEF FN M(X) = X - INT (D * 3) * INT (X / INT (D * 3))
130 DE = 4
140 DI = 3 ^ DE * 3
150 FOR I = 0 TO DI - 1
160 FOR J = 0 TO DI - 1
170 FOR D = DI / 3 TO 0 STEP 0
180 IF INT ( FN M(I) / D) = 1 AND INT ( FN M(J) / D) = 1 THEN 200BREAK
190 D = INT (D / 3): NEXT D
200 HCOLOR= 3 * (D = 0)
210 HPLOT J,I
220 NEXT J
230 NEXT I |
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.
| #APL | APL | shoelace ← 2÷⍨|∘(((1⊃¨⊢)+.×1⌽2⊃¨⊢)-(1⌽1⊃¨⊢)+.×2⊃¨⊢) |
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.
| #AutoHotkey | AutoHotkey | V := [[3, 4], [5, 11], [12, 8], [9, 5], [5, 6]]
n := V.Count()
for i, O in V
Sum += V[i, 1] * V[i+1, 2] - V[i+1, 1] * V[i, 2]
MsgBox % result := Abs(Sum += V[n, 1] * V[1, 2] - V[1, 1] * V[n, 2]) / 2 |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #11l | 11l | ...>echo L(i) 0..10 {print("Hello World"[0..i])} > oneliner.11l && 11l oneliner.11l && oneliner.exe
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World
|
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
| #J | J | HELP=: 0 :0
Commands:
DBNAME add DATA
DBNAME display the latest entry
DBNAME display the latest entry where CATEGORY contains WORD
DBNAME display all entries
DBNAME display all entries order by CATEGORY
1) The first add with new DBNAME assign category names.
2) lower case arguments verbatim.
3) UPPER CASE: substitute your values.
Examples, having saved this program as a file named s :
$ jconsole s simple.db display all entries
$ jconsole s simple.db add "first field" "2nd field"
)
Q=: '''' NB. quote character
time=: 6!:0@:('YYYY-MM-DD:hh:mm:ss.sss'"_)
embed=: >@:{.@:[ , ] , >@:{:@:[
assert '(x+y)' -: '()' embed 'x+y'
Duplicate=: 1 :'#~ m&= + 1 #~ #'
assert 0 1 2 3 3 4 -: 3 Duplicate i.5
prepare=: LF ,~ [: }:@:; (Q;Q,';')&embed@:(Q Duplicate)&.>@:(;~ time)
assert (-: }.@:".@:}:@:prepare) 'boxed';'';'li''st';'of';'''strings'''
categorize=: dyad define
i=. x i. y
if. (1 (~: #) i) +. i (= #) x do.
smoutput 'choose 1 of'
smoutput x
exit 1
end.
{. i NB. "index of" frame has rank 1.
)
assert 0 -: 'abc' categorize 'a'
loadsdb=: (<'time') (<0 0)} ".;._2@:(1!:1)
Dispatch=: conjunction define
help
:
commands=. y
command=. {. commands
x (u`help@.(command(i.~ ;:)n)) }.commands
)
NB. the long fork in show groups (": #~ (1 1 embed (1j1 }:@:# (1 #~ #))))
show=: smoutput@:(": #~ 1 1 embed 1j1 }:@:# 1 #~ #)
in=: +./@:E.
assert 'the' in'quick brown fox jumps over the lazy dog'
assert 'the'-.@:in'QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
where=: dyad define
'category contains word'=. 3 {. y
if. 'contains' -.@:-: contains do.
help''
exit 1
end.
i=. x ({.@:[ categorize <@:]) category
j=. {: I. ; word&in&.> i {"1 x
if. 0 (= #) j do.
smoutput 'no matches'
else.
x (show@:{~ 0&,) j
end.
)
entry=: 4 : 0
if. a: = y do.
show@:({. ,: {:) x
else.
x ''`where Dispatch'where' y
end.
)
latest=: ''`entry Dispatch'entry'
the=: ''`latest Dispatch'latest'
by=: 4 : 0
i=. x (categorize~ {.)~ y
show ({. , (/: i&{"1)@:}.) x
)
order=: ''`by Dispatch'by'
entries=: 4 : 0
if. a: = y do.
show x
else.
x ''`order Dispatch'order' y
end.
)
all=: ''`entries Dispatch'entries'
help=: smoutput@:(HELP"_)
add=: 1!:3~ prepare NB. minimal---no error tests
display=: (the`all Dispatch'the all'~ loadsdb)~ NB. load the simple db for some sort of display
({. add`display Dispatch'add display' }.)@:(2&}.)ARGV
exit 0
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #REXX | REXX | /*REXX program finds the Shortest common supersequence (SCS) of two character strings.*/
parse arg u v . /*obtain optional arguments from the CL*/
if u=='' | u=="," then u= 'abcbdab' /*Not specified? Then use the default.*/
if v=='' | v=="," then v= 'bdcaba' /* " " " " " " */
say ' string u=' u /*echo the value of string U to term.*/
say ' string v=' v /* " " " " " V " " */
$= u /*define initial value for the output. */
do n=1 to length(u) /*process the whole length of string U.*/
do m=n to length(v) - 1 /* " right─ish part " " V.*/
p= pos( substr(v, m, 1), $) /*position of mTH V char in $ string.*/
_= substr(v, m+1, 1) /*obtain a single character of string V*/
if p\==0 & _\==substr($, p+1, 1) then $= insert(_, $, p)
end /*m*/ /* [↑] insert _ in $ after position P.*/
end /*n*/
say
say 'shortest common supersequence=' $ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Ring | Ring |
# Project : Shortest common supersequence
str1 = "a b c b d a b"
str2 = "bdcaba"
str3 = str2list(substr(str1, " ", nl))
for n = 1 to len(str3)
for m = n to len(str2)-1
pos = find(str3, str2[m])
if pos > 0 and str2[m+1] != str3[pos+1]
insert(str3, pos, str2[m+1])
ok
next
next
showarray(str3)
func showarray(vect)
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n]
next
see svect
|
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Ruby | Ruby | require 'lcs'
def scs(u, v)
lcs = lcs(u, v)
u, v = u.dup, v.dup
scs = ""
# Iterate over the characters until LCS processed
until lcs.empty?
if u[0]==lcs[0] and v[0]==lcs[0]
# Part of the LCS, so consume from all strings
scs << lcs.slice!(0)
u.slice!(0)
v.slice!(0)
elsif u[0]==lcs[0]
# char of u = char of LCS, but char of LCS v doesn't so consume just that
scs << v.slice!(0)
else
# char of u != char of LCS, so consume just that
scs << u.slice!(0)
end
end
# append remaining characters, which are not in common
scs + u + v
end
u = "abcbdab"
v = "bdcaba"
puts "SCS(#{u}, #{v}) = #{scs(u, v)}" |
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
| #Maxima | Maxima | timedate(0);
"1900-01-01 10:00:00+10: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
| #min | min | 0 datetime puts! |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.text.DateFormat
edate = Date(0)
zulu = DateFormat.getDateTimeInstance()
zulu.setTimeZone(TimeZone.getTimeZone('UTC'))
say zulu.format(edate)
return
|
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
| #NewLISP | NewLISP | (date 0)
->"Thu Jan 01 01: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
| #Elm | Elm | import String exposing (..)
import Html exposing (..)
import Html.Attributes as A exposing (..)
import Html.Events exposing (..)
import Html.App exposing (beginnerProgram)
import Result exposing (..)
sierpinski : Int -> List String
sierpinski n =
let down n = sierpinski (n - 1)
space n = repeat (2 ^ (n - 1)) " "
in case n of
0 -> ["*"]
_ -> List.map ((\st -> space n ++ st) << (\st -> st ++ space n)) (down n)
++ List.map (join " " << List.repeat 2) (down n)
main = beginnerProgram { model = "4", view = view, update = update }
update newStr oldStr = newStr
view : String -> Html String
view levelString =
div []
([ Html.form
[]
[ label [ myStyle ] [ text "Level: "]
, input
[ placeholder "triangle level."
, value levelString
, on "input" targetValue
, type' "number"
, A.min "0"
, myStyle
]
[]
]
] ++
[ pre [] (levelString
|> toInt
|> withDefault 0
|> sierpinski
|> List.map (\s -> div [] [text s]))
])
myStyle : Attribute msg
myStyle =
style
[ ("height", "20px")
, ("padding", "5px 0 0 5px")
, ("font-size", "1em")
, ("text-align", "left")
] |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc mean args {expr {[::tcl::mathop::+ {*}$args] / [llength $args]}}
proc sierpinski {canv coords order} {
$canv create poly $coords -fill black -outline {}
set queue [list [list {*}$coords $order]]
while {[llength $queue]} {
lassign [lindex $queue 0] x1 y1 x2 y2 x3 y3 order
set queue [lrange $queue 1 end]
if {[incr order -1] < 0} continue
set x12 [mean $x1 $x2]; set y12 [mean $y1 $y2]
set x23 [mean $x2 $x3]; set y23 [mean $y2 $y3]
set x31 [mean $x3 $x1]; set y31 [mean $y3 $y1]
$canv create poly $x12 $y12 $x23 $y23 $x31 $y31 -fill white -outline {}
update idletasks; # So we can see progress
lappend queue [list $x1 $y1 $x12 $y12 $x31 $y31 $order] \
[list $x12 $y12 $x2 $y2 $x23 $y23 $order] \
[list $x31 $y31 $x23 $y23 $x3 $y3 $order]
}
}
pack [canvas .c -width 400 -height 400 -background white]
update; # So we can see progress
sierpinski .c {200 10 390 390 10 390} 7 |
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
| #Arturo | Arturo | inCarpet?: function [x,y][
X: x
Y: y
while [true][
if or? zero? X
zero? Y -> return true
if and? 1 = X % 3
1 = Y % 3 -> return false
X: X / 3
Y: Y / 3
]
]
carpet: function [n][
loop 0..dec 3^n 'i [
loop 0..dec 3^n 'j [
prints (inCarpet? i j)? -> "# "
-> " "
]
print ""
]
]
carpet 3 |
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area | Shoelace formula for polygonal area | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
Task
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| #BASIC256 | BASIC256 | arraybase 1
dim array = {{3,4}, {5,11}, {12,8}, {9,5}, {5,6}}
print "The area of the polygon = "; Shoelace(array)
end
function Shoelace(p)
sum = 0
for i = 1 to p[?][] -1
sum += p[i][1] * p[i +1][2]
sum -= p[i +1][1] * p[i][2]
next i
sum += p[i][1] * p[1][2]
sum -= p[1][1] * p[i][2]
return abs(sum) \ 2
end function |
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.
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double shoelace(char* inputFile){
int i,numPoints;
double leftSum = 0,rightSum = 0;
point* pointSet;
FILE* fp = fopen(inputFile,"r");
fscanf(fp,"%d",&numPoints);
pointSet = (point*)malloc((numPoints + 1)*sizeof(point));
for(i=0;i<numPoints;i++){
fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y);
}
fclose(fp);
pointSet[numPoints] = pointSet[0];
for(i=0;i<numPoints;i++){
leftSum += pointSet[i].x*pointSet[i+1].y;
rightSum += pointSet[i+1].x*pointSet[i].y;
}
free(pointSet);
return 0.5*fabs(leftSum - rightSum);
}
int main(int argC,char* argV[])
{
if(argC==1)
printf("\nUsage : %s <full path of polygon vertices file>",argV[0]);
else
printf("The polygon area is %lf square units.",shoelace(argV[1]));
return 0;
}
|
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.
| #ACL2 | ACL2 | $ acl2 <<< '(cw "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.
| #Ada | Ada | echo 'with Ada.text_IO; use Ada.text_IO; procedure X is begin Put("Hello!"); end X;' > x.adb; gnatmake x; ./x; rm x.adb x.ali x.o x |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #Aikido | Aikido | echo 'println ("Hello")' | aikido |
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
| #Java | Java | import java.io.*;
import java.text.*;
import java.util.*;
public class SimpleDatabase {
final static String filename = "simdb.csv";
public static void main(String[] args) {
if (args.length < 1 || args.length > 3) {
printUsage();
return;
}
switch (args[0].toLowerCase()) {
case "add":
addItem(args);
break;
case "latest":
printLatest(args);
break;
case "all":
printAll();
break;
default:
printUsage();
break;
}
}
private static class Item implements Comparable<Item>{
final String name;
final String date;
final String category;
Item(String n, String d, String c) {
name = n;
date = d;
category = c;
}
@Override
public int compareTo(Item item){
return date.compareTo(item.date);
}
@Override
public String toString() {
return String.format("%s,%s,%s%n", name, date, category);
}
}
private static void addItem(String[] input) {
if (input.length < 2) {
printUsage();
return;
}
List<Item> db = load();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
String cat = (input.length == 3) ? input[2] : "none";
db.add(new Item(input[1], date, cat));
store(db);
}
private static void printLatest(String[] a) {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
if (a.length == 2) {
for (Item item : db)
if (item.category.equals(a[1]))
System.out.println(item);
} else {
System.out.println(db.get(0));
}
}
private static void printAll() {
List<Item> db = load();
if (db.isEmpty()) {
System.out.println("No entries in database.");
return;
}
Collections.sort(db);
for (Item item : db)
System.out.println(item);
}
private static List<Item> load() {
List<Item> db = new ArrayList<>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNext()) {
String[] item = sc.nextLine().split(",");
db.add(new Item(item[0], item[1], item[2]));
}
} catch (IOException e) {
System.out.println(e);
}
return db;
}
private static void store(List<Item> db) {
try (FileWriter fw = new FileWriter(filename)) {
for (Item item : db)
fw.write(item.toString());
} catch (IOException e) {
System.out.println(e);
}
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println(" simdb cmd [categoryName]");
System.out.println(" add add item, followed by optional category");
System.out.println(" latest print last added item(s), followed by "
+ "optional category");
System.out.println(" all print all");
System.out.println(" For instance: add \"some item name\" "
+ "\"some category name\"");
}
} |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Sidef | Sidef | func scs(u, v) {
var ls = lcs(u, v).chars
var pat = Regex('(.*)'+ls.join('(.*)')+'(.*)')
u.scan!(pat)
v.scan!(pat)
var ss = (u.shift + v.shift)
ls.each { |c| ss += (c + u.shift + v.shift) }
return ss
}
say scs("abcbdab", "bdcaba") |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Tcl | Tcl | proc scs {u v} {
set lcs [lcs $u $v]
set scs ""
# Iterate over the characters until LCS processed
for {set ui [set vi [set li 0]]} {$li<[string length $lcs]} {} {
set uc [string index $u $ui]
set vc [string index $v $vi]
set lc [string index $lcs $li]
if {$uc eq $lc} {
if {$vc eq $lc} {
# Part of the LCS, so consume from all strings
append scs $lc
incr ui
incr li
} else {
# char of u = char of LCS, but char of LCS v doesn't so consume just that
append scs $vc
}
incr vi
} else {
# char of u != char of LCS, so consume just that
append scs $uc
incr ui
}
}
# append remaining characters, which are not in common
append scs [string range $u $ui end] [string range $v $vi end]
return $scs
} |
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
| #Nim | Nim | import times
echo "Epoch for Posix systems: ", fromUnix(0).utc
echo "Epoch for Windows system: ", fromWinTime(0).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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSDate *t = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"];
NSLog(@"%@", [dateFormatter stringFromDate:t]);
}
return 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
| #OCaml | OCaml | open Unix
let months = [| "January"; "February"; "March"; "April"; "May"; "June";
"July"; "August"; "September"; "October"; "November"; "December" |]
let () =
let t = Unix.gmtime 0.0 in
Printf.printf "%s %d, %d\n" months.(t.tm_mon) t.tm_mday (1900 + t.tm_year) |
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
| #Erlang | Erlang | -module(sierpinski).
-export([triangle/1]).
triangle(N) ->
F = fun(X) -> io:format("~s~n",[X]) end,
lists:foreach(F, triangle(N, ["*"], " ")).
triangle(0, Down, _) -> Down;
triangle(N, Down, Sp) ->
NewDown = [Sp++X++Sp || X<-Down]++[X++" "++X || X <- Down],
triangle(N-1, NewDown, Sp++Sp). |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
class Game {
static init() {
Window.title = "Sierpinski Triangle"
var size = 800
Window.resize(size, size)
Canvas.resize(size, size)
Canvas.cls(Color.white)
var level = 8
sierpinskiTriangle(level, 20, 20, size - 40)
}
static update() {}
static draw(alpha) {}
static sierpinskiTriangle(level, x, y, size) {
if (level > 0) {
var col = Color.black
Canvas.line(x, y, x + size, y, col)
Canvas.line(x, y, x, y + size, col)
Canvas.line(x + size, y, x, y + size, col)
var size2 = (size/2).floor
sierpinskiTriangle(level - 1, x, y, size2)
sierpinskiTriangle(level - 1, x + size/2, y, size2)
sierpinskiTriangle(level - 1, x, y + size/2, size2)
}
}
} |
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
| #Asymptote | Asymptote | path across(path p, real node) {
return
point(p, node + 1/3) + point(p, node - 1/3) - point(p, node);
}
path corner_subquad(path p, real node) {
return
point(p, node) --
point(p, node + 1/3) --
across(p, node) --
point(p, node - 1/3) --
cycle;
}
path noncorner_subquad(path p, real node1, real node2) {
return
point(p, node1 + 1/3) --
across(p, node1) --
across(p, node2) --
point(p, node2 - 1/3) --
cycle;
}
void carpet(path p, int order) {
if (order == 0)
fill(p);
else {
for (real node : sequence(0, 3)) {
carpet(corner_subquad(p, node), order - 1);
carpet(noncorner_subquad(p, node, node + 1), order - 1);
}
}
}
path q =
// A square
unitsquare
// An oblong rhombus
// (0, 0) -- (5, 3) -- (0, 6) -- (-5, 3) -- cycle
// A trapezoid
// (0, 0) -- (4, 2) -- (6, 2) -- (10, 0) -- cycle
// A less regular quadrilateral
// (0, 0) -- (4, 1) -- (9, -4) -- (1, -1) -- cycle
// A concave shape
// (0, 0) -- (5, 3) -- (10, 0) -- (5, 1) -- cycle
;
size(9 inches, 6 inches);
carpet(q, 5); |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace ShoelaceFormula {
using Point = Tuple<double, double>;
class Program {
static double ShoelaceArea(List<Point> v) {
int n = v.Count;
double a = 0.0;
for (int i = 0; i < n - 1; i++) {
a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2;
}
return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0;
}
static void Main(string[] args) {
List<Point> v = new List<Point>() {
new Point(3,4),
new Point(5,11),
new Point(12,8),
new Point(9,5),
new Point(5,6),
};
double area = ShoelaceArea(v);
Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v));
Console.WriteLine("its area is {0}.", 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.
| #Aime | Aime | $ src/aime -c 'o_text("Hello, World!\n");' |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #ALGOL_68 | ALGOL 68 | $ a68g -e 'print(("Hello",new line))' |
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.
| #AppleScript | AppleScript | osascript -e 'say "Hello, World!"' |
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
| #11l | 11l | L(i) 16
L(j) (32 + i .. 127).step(16)
String k
I j == 32
k = ‘Spc’
E I j == 127
k = ‘Del’
E
k = Char(code' j)
print(‘#3 : #<3’.format(j, k), end' ‘’)
print() |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
A description of the item. (e.g., title, name)
A category or tag (genre, topic, relationship such as “friend” or “family”)
A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
Other optional fields
The command should support the following Command-line arguments to run:
Add a new entry
Print the latest entry
Print the latest entry for each category
Print all entries sorted by a date
The category may be realized as a tag or as structure (by making all entries in that category subitems)
The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
JSON
S-Expressions
YAML
others
Related task
Take notes on the command line
| #Julia | Julia | Name,Birthdate,State,Relation,Email
Sally Whittaker,1988-12-05,Illinois,friend,[email protected]
Belinda Jameson,1994-02-17,California,family,[email protected]
Jeff Bragg,2018-10-10,Texas,family,[email protected]
Sandy Allen,2002-03-09,Colorado,friend,[email protected]
Fred Kobo,1967-10-10,Colorado,friend,[email protected] |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #Wren | Wren | var lcs // recursive
lcs = Fn.new { |x, y|
if (x.count == 0 || y.count == 0) return ""
var x1 = x[0...-1]
var y1 = y[0...-1]
if (x[-1] == y[-1]) return lcs.call(x1, y1) + x[-1]
var x2 = lcs.call(x, y1)
var y2 = lcs.call(x1, y)
return (x2.count > y2.count) ? x2 : y2
}
var scs = Fn.new { |u, v|
var lcs = lcs.call(u, v)
var ui = 0
var vi = 0
var sb = ""
for (i in 0...lcs.count) {
while (ui < u.count && u[ui] != lcs[i]) {
sb = sb + u[ui]
ui = ui + 1
}
while (vi < v.count && v[vi] != lcs[i]) {
sb = sb + v[vi]
vi = vi + 1
}
sb = sb + lcs[i]
ui = ui + 1
vi = vi + 1
}
if (ui < u.count) sb = sb + u[ui..-1]
if (vi < v.count) sb = sb + v[vi..-1]
return sb
}
var u = "abcbdab"
var v = "bdcaba"
System.print(scs.call(u, v)) |
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
| #Oforth | Oforth | import: date
0 asDateUTC println |
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
| #PARI.2FGP | PARI/GP | system("date -ur 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
| #Pascal | Pascal | Program ShowEpoch;
uses
SysUtils;
begin
Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now));
Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0));
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
| #Euphoria | Euphoria | procedure triangle(integer x, integer y, integer len, integer n)
if n = 0 then
position(y,x) puts(1,'*')
else
triangle (x, y+len, floor(len/2), n-1)
triangle (x+len, y, floor(len/2), n-1)
triangle (x+len*2, y+len, floor(len/2), n-1)
end if
end procedure
clear_screen()
triangle(1,1,8,4) |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def Order=7, Size=1<<Order;
int X, Y;
[SetVid($13); \set 320x200 graphics video mode
for Y:= 0 to Size-1 do
for X:= 0 to Size-1 do
if (X&Y)=0 then Point(X, Y, 4\red\);
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text display
] |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #zkl | zkl | const Order=8, Size=(1).shiftLeft(Order);
img:=PPM(300,300);
foreach y,x in (Size,Size){ if(x.bitAnd(y)==0) img[x,y]=0xff0000 }
img.write(File("sierpinskiTriangle.ppm","wb")); |
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
| #AutoHotkey | AutoHotkey | Loop 4
MsgBox % Carpet(A_Index)
Carpet(n) {
Loop % 3**n {
x := A_Index-1
Loop % 3**n
t .= Dot(x,A_Index-1)
t .= "`n"
}
Return t
}
Dot(x,y) {
While x>0 && y>0
If (mod(x,3)=1 && mod(y,3)=1)
Return " "
Else x //= 3, y //= 3
Return "."
} |
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.
| #C.2B.2B | C++ | #include <iostream>
#include <tuple>
#include <vector>
using namespace std;
double shoelace(vector<pair<double, double>> points) {
double leftSum = 0.0;
double rightSum = 0.0;
for (int i = 0; i < points.size(); ++i) {
int j = (i + 1) % points.size();
leftSum += points[i].first * points[j].second;
rightSum += points[j].first * points[i].second;
}
return 0.5 * abs(leftSum - rightSum);
}
void main() {
vector<pair<double, double>> points = {
make_pair( 3, 4),
make_pair( 5, 11),
make_pair(12, 8),
make_pair( 9, 5),
make_pair( 5, 6),
};
auto ans = shoelace(points);
cout << ans << endl;
} |
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.
| #Arturo | Arturo | $ arturo -e:"print {Hello World!}" |
http://rosettacode.org/wiki/Shell_one-liner | Shell one-liner | Task
Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.
Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.
| #AWK | AWK | $ awk 'BEGIN { print "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.
| #BASIC | BASIC | echo 'print "foo"'|basic |
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
| #6502_Assembly | 6502 Assembly | ==========================================================================
; task : show ascii table
; language: 6502 Assembly
; for: : rosettacode.org
; run : on a Commodore 64 with command
; sys 49152
;
; same logic of "Commodore BASIC"
;
; assembler win2c64 by Aart Bik
; http://www.aartbik.com/
;
; 2020-05-01 alvalongo
;==========================================================================
; constants
cr = 13 ; carriage-return
white = 5 ; color white
; ----------------------------------------------
; memory on zero page
linnum = $14
; ----------------------------------------------
; kernel routines
linstr = $bdcd ; C64 ROM : convert a 16-bit value to string and print on current device (default screen)
chrout = $ffd2 ; C64 ROM kernel: output a character to current device, default screen
; use $fded for Apple 2
;
; ----------------------------------------------
;
.org $c000 ; start at free RAM, on Commodore 64
; ----------------------------------------------
l100 lda #147 ; clear screen
jsr chrout
;
l110 lda #14 ;character set 2, upper/lower case mode
jsr chrout
;
lda #white ; color for characters
jsr chrout
;
l120 lda #<msg1
ldx #>msg1
jsr prtmsg
;
l130 lda #<msg2
ldx #>msg2
jsr prtmsg
;
l140 lda #cr
jsr chrout
;
l150 lda #0
sta row
;
l160 lda #0
sta column
;
l170 clc
lda row
adc #32
sta ascii
lda column
asl ; times 2, 2
asl ; times 2, 4
asl ; times 2, 8
asl ; times 2, 16
adc ascii
sta ascii
;
l180 cmp #100
bcs l185 ; equal or greater than
lda #" " ; a space before values less than 100
jsr chrout
;
l185 ldx ascii
lda #0
jsr linstr ; convert to string and print on screen
lda #":"
jsr chrout
lda ascii
jsr chrout
lda #" "
jsr chrout
;
l190 inc column ; next column
lda column
cmp #5
bcc l170
beq l170
;
l200 lda #cr
jsr chrout
;
l210 inc row ; next row
lda row
cmp #15
bcc l160
beq l160
;
l220 rts ; return to operating system
; ----------------------------------------------
; print message
;
prtmsg sta linnum
stx linnum+1
ldy #0
l310 lda (linnum),y
beq l320
jsr chrout
iny
bne l310
l320 lda #cr
jsr chrout
rts
; ----------------------------------------------
msg1 .byte "COMMODORE 64 - BASIC V2",0
msg2 .byte "CHARACTER SET 2 UPPER/LOWER CASE MODE",0
row .byte 0
column .byte 0
ascii .byte 0
|
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
| #Kotlin | Kotlin | // version 1.2.31
import java.text.SimpleDateFormat
import java.util.Date
import java.io.File
import java.io.IOException
val file = File("simdb.csv")
class Item(
val name: String,
val date: String,
val category: String
) : Comparable<Item> {
override fun compareTo(other: Item) = date.compareTo(other.date)
override fun toString() = "$name, $date, $category"
}
fun addItem(input: Array<String>) {
if (input.size < 2) {
printUsage()
return
}
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date = sdf.format(Date())
val cat = if (input.size == 3) input[2] else "none"
store(Item(input[1], date, cat))
}
fun printLatest(a: Array<String>) {
val db = load()
if (db.isEmpty()) {
println("No entries in database.")
return
}
// no need to sort db as items are added chronologically
if (a.size == 2) {
var found = false
for (item in db.reversed()) {
if (item.category == a[1]) {
println(item)
found = true
break
}
}
if (!found) println("There are no items for category '${a[1]}'")
}
else println(db[db.lastIndex])
}
fun printAll() {
val db = load()
if (db.isEmpty()) {
println("No entries in database.")
return
}
// no need to sort db as items are added chronologically
for (item in db) println(item)
}
fun load(): MutableList<Item> {
val db = mutableListOf<Item>()
try {
file.forEachLine { line ->
val item = line.split(", ")
db.add(Item(item[0], item[1], item[2]))
}
}
catch (e: IOException) {
println(e)
System.exit(1)
}
return db
}
fun store(item: Item) {
try {
file.appendText("$item\n")
}
catch (e: IOException) {
println(e)
}
}
fun printUsage() {
println("""
|Usage:
| simdb 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"
""".trimMargin())
}
fun main(args: Array<String>) {
if (args.size !in 1..3) {
printUsage()
return
}
file.createNewFile() // create file if it doesn't already exist
when (args[0].toLowerCase()) {
"add" -> addItem(args)
"latest" -> printLatest(args)
"all" -> printAll()
else -> printUsage()
}
} |
http://rosettacode.org/wiki/Shortest_common_supersequence | Shortest common supersequence | The shortest common supersequence is a problem closely related to the longest common subsequence, which you can use as an external function for this task.
Task
Given two strings
u
{\displaystyle u}
and
v
{\displaystyle v}
, find the shortest possible sequence
s
{\displaystyle s}
, which is the shortest common super-sequence of
u
{\displaystyle u}
and
v
{\displaystyle v}
where both
u
{\displaystyle u}
and
v
{\displaystyle v}
are a subsequence of
s
{\displaystyle s}
. Defined as such,
s
{\displaystyle s}
is not necessarily unique.
Demonstrate this by printing
s
{\displaystyle s}
where
u
=
{\displaystyle u=}
“abcbdab” and
v
=
{\displaystyle v=}
“bdcaba”.
Also see
Wikipedia: shortest common supersequence
| #zkl | zkl | class Link{ var len,letter,next;
fcn init(l=0,c="",lnk=Void){ len,letter,next=l,c,lnk; }
}
fcn scs(x,y,out){
lx,ly:=x.len(),y.len();
lnk:=(ly+1).pump(List,'wrap(_){ (lx+1).pump(List(),Link.create) });
foreach i in (ly){ lnk[i][lx]=Link(ly-i, y[i]) }
foreach j in (lx){ lnk[ly][j]=Link(lx-j, x[j]) }
foreach i,j in ([ly-1..0,-1],[lx-1..0,-1]){
lp:=lnk[i][j];
if (y[i]==x[j]){
lp.next =lnk[i+1][j+1];
lp.letter=x[j];
}else if(lnk[i][j+1].len < lnk[i+1][j].len){
lp.next =lnk[i][j+1];
lp.letter=x[j];
}else{
lp.next =lnk[i+1][j];
lp.letter=y[i];
}
lp.len=lp.next.len + 1;
}
lp:=lnk[0][0]; while(lp){ out.write(lp.letter); lp=lp.next; }
out.close()
} |
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
| #Perl | Perl | print scalar gmtime 0, "\n"; |
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
| #Phix | Phix | with javascript_semantics
constant d0 = {0,1,1,0,0,0,1,1}
include builtins\timedate.e
?format_timedate(d0,"YYYY-MM-DD")
?format_timedate(d0,"Dddd, Mmmm d, YYYY")
|
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
| #PHP | PHP | <?php
echo gmdate('r', 0), "\n";
?> |
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
| #Excel | Excel | sierpinskiTriangle
=LAMBDA(c,
LAMBDA(n,
IF(0 = n,
c,
LET(
prev, sierpinskiTriangle(c)(n - 1),
APPENDROWS(
sierpCentered(prev)
)(
sierpDoubled(prev)
)
)
)
)
)
sierpCentered
=LAMBDA(grid,
LET(
nRows, ROWS(grid),
padding, IF(
SEQUENCE(nRows, nRows, 1, 1),
" "
),
APPENDCOLS(
APPENDCOLS(padding)(grid)
)(padding)
)
)
sierpDoubled
=LAMBDA(grid,
APPENDCOLS(
APPENDCOLS(grid)(
IF(SEQUENCE(ROWS(grid), 1, 1, 1),
" "
)
)
)(grid)
) |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
The use of the # character is not rigidly required for ASCII art.
The important requirement is the placement of whitespace and non-whitespace characters.
Related task
Sierpinski triangle
| #AWK | AWK | # WSC.AWK - Waclaw Sierpinski's carpet contributed by Dan Nielsen
#
# syntax: GAWK -f WSC.AWK [-v o={a|A}{b|B}] [-v X=anychar] iterations
#
# -v o=ab default
# a|A loose weave | tight weave
# b|B don't show | show how the carpet is built
# -v X=? Carpet is built with X's. The character assigned to X replaces all X's.
#
# iterations
# The number of iterations. The default is 0 which produces one carpet.
#
# what is the difference between a loose weave and a tight weave:
# loose tight
# X X X X X X X X X XXXXXXXXX
# X X X X X X X XX XX X
# X X X X X X X X X XXXXXXXXX
# X X X X X X XXX XXX
# X X X X X X X X
# X X X X X X XXX XXX
# X X X X X X X X X XXXXXXXXX
# X X X X X X X XX XX X
# X X X X X X X X X XXXXXXXXX
#
# examples:
# GAWK -f WSC.AWK 2
# GAWK -f WSC.AWK -v o=Ab -v X=# 2
# GAWK -f WSC.AWK -v o=Ab -v X=\xDB 2
#
BEGIN {
optns = (o == "") ? "ab" : o
n = ARGV[1] + 0 # iterations
if (n !~ /^[0-9]+$/) { exit(1) }
seed = (optns ~ /A/) ? "XXX,X X,XXX" : "X X X ,X X ,X X X " # tight/loose weave
leng = row = split(seed,A,",") # seed the array
for (i=1; i<=n; i++) { # build carpet
for (a=1; a<=3; a++) {
row = 0
for (b=1; b<=3; b++) {
for (c=1; c<=leng; c++) {
row++
tmp = (a == 2 && b == 2) ? sprintf("%*s",length(A[c]),"") : A[c]
B[row] = B[row] tmp
}
if (optns ~ /B/) { # show how the carpet is built
if (max_row < row+0) { max_row = row }
for (r=1; r<=max_row; r++) {
printf("i=%d row=%02d a=%d b=%d '%s'\n",i,r,a,b,B[r])
}
print("")
}
}
}
leng = row
for (j=1; j<=row; j++) { A[j] = B[j] } # re-seed the array
for (j in B) { delete B[j] } # delete work array
}
for (j=1; j<=row; j++) { # print carpet
if (X != "") { gsub(/X/,substr(X,1,1),A[j]) }
sub(/ +$/,"",A[j])
printf("%s\n",A[j])
}
exit(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.
| #Cowgol | Cowgol | include "cowgol.coh";
typedef Coord is uint16; # floating point types are not supported
record Point is
x: Coord;
y: Coord;
end record;
sub shoelace(p: [Point], length: intptr): (area: Coord) is
var left: Coord := 0;
var right: Coord := 0;
var y0 := p.y;
var x0 := p.x;
while length > 1 loop
var xp := p.x;
var yp := p.y;
p := @next p;
left := left + xp * p.y;
right := right + yp * p.x;
length := length - 1;
end loop;
left := left + y0 * p.x;
right := right + x0 * p.y;
if left < right then
area := right - left;
else
area := left - right;
end if;
area := area / 2;
end sub;
var polygon: Point[] := {{3,4},{5,11},{12,8},{9,5},{5,6}};
print_i16(shoelace(&polygon[0], @sizeof polygon));
print_nl(); |
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.
| #D | D | import std.stdio;
Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}];
void main() {
auto ans = shoelace(pnts);
writeln(ans);
}
struct Point {
real x, y;
}
real shoelace(Point[] pnts) {
real leftSum = 0, rightSum = 0;
for (int i=0; i<pnts.length; ++i) {
int j = (i+1) % pnts.length;
leftSum += pnts[i].x * pnts[j].y;
rightSum += pnts[j].x * pnts[i].y;
}
import std.math : abs;
return 0.5 * abs(leftSum - rightSum);
}
unittest {
auto ans = shoelace(pnts);
assert(ans == 30);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.