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/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Go | Go | if booleanExpression {
statements
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #PureBasic | PureBasic |
EnableExplicit
Procedure.s CommaQuibble(Input$)
Protected i, count
Protected result$, word$
Input$ = RemoveString(Input$, "[")
Input$ = RemoveString(Input$, "]")
Input$ = RemoveString(Input$, #DQUOTE$)
count = CountString(Input$, ",") + 1
result$ = "{"
For i = 1 To count
word$ = StringField(Input$, i, ",")
If i = 1
result$ + word$
ElseIf Count = i
result$ + " and " + word$
Else
result$ + ", " + word$
EndIf
Next
ProcedureReturn result$ + "}"
EndProcedure
If OpenConsole()
; As 3 of the strings contain embedded quotes these need to be escaped with '\' and the whole string preceded by '~'
PrintN(CommaQuibble("[]"))
PrintN(CommaQuibble(~"[\"ABC\"]"))
PrintN(CommaQuibble(~"[\"ABC\",\"DEF\"]"))
PrintN(CommaQuibble(~"[\"ABC\",\"DEF\",\"G\",\"H\"]"))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Ursa | Ursa | #
# command-line arguments
#
# output all arguments
for (decl int i) (< i (size args)) (inc i)
out args<i> endl console
end for |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Ursala | Ursala | #import std
#executable ('parameterized','')
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #V | V | $stack puts
./args.v a b c
=[args.v a b c] |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #vbScript | vbScript |
'Command line arguments can be accessed all together by
For Each arg In Wscript.Arguments
Wscript.Echo "arg=", arg
Next
'You can access only the named arguments such as /arg:value
For Each arg In Wscript.Arguments.Named
Wscript.Echo "name=", arg, "value=", Wscript.Arguments.Named(arg)
Next
'Or just the unnamed arguments
For Each arg In Wscript.Arguments.Unnamed
Wscript.Echo "arg=", arg
Next
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #HTML | HTML | <!-- Anything within these bracket tags is commented, single or multi-line. --> |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Icon_and_Unicon | Icon and Unicon | # This is a comment
procedure x(y,z) #: This is a comment and an IPL meta-comment for a procedure
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Phix | Phix | --
-- demo\rosetta\Conways_Game_of_Life.exw
-- =====================================
--
with javascript_semantics
include pGUI.e
constant title = "Conway's Game of Life"
Ihandle dlg, canvas
Ihandln hTimer = NULL
cdCanvas cddbuffer
sequence c = {}, -- cells
cn, -- new cells
cl -- last cells
procedure draw(integer what)
integer x = floor(length(c)/2)+1,
y = floor(length(c[1])/2)
switch what do
case ' ': c = sq_mul(c,0) -- Clear
case '+': c[x][y-1..y+1] = repeat(1,3) -- Blinker
case 'G': { c[x+1,y+4],
c[x+2,y+2], c[x+2,y+4],
c[x+3,y+3], c[x+3,y+4]} = repeat(1,5) -- Glider
case 'T': {c[x-1,y+1],c[x,y+1],c[x+1,y+1],
c[x ,y+3],c[x,y+4],c[x ,y+5]} = repeat(1,6) -- Thunderbird
case 'X': for i=0 to min(x,y)-1 do
{c[x-i,y+i],c[x+i,y+i],
c[x-i,y-i],c[x+i,y-i]} = repeat(1,4) -- Cross
end for
end switch
end procedure
atom t1 = time()+1
integer fps = 0
function redraw_cb(Ihandle /*ih*/)
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"),
-- limit to 10K cells (performance target of 10fps)
-- n here is the cell size in pixels (min of 1x1)
n = ceil(sqrt(width*height/10000)),
w = floor(width/n)+2, -- (see cx below)
h = floor(height/n)+2,
alive = 0
-- keep w, h odd for symmetry (plus I suspect the
-- "Cross" code above may now crash without this)
w -= even(w)
h -= even(h)
if length(c)!=w
or length(c[1])!=h then
c = repeat(repeat(0,h),w)
cn = deep_copy(c)
cl = deep_copy(c)
draw('X')
if hTimer!=NULL then
IupStoreAttribute(hTimer, "RUN", "YES")
end if
end if
cdCanvasActivate(cddbuffer)
--
-- There is a "dead border" of 1 cell all around the edge of c (etc) which
-- we never display or update. If we have got this right/an exact fit, then
-- w*n should be exactly 2n too wide, whereas in the worst case there is an
-- (2n-1) pixel border, which we split between left and right, ditto cy.
--
integer cx = n+floor((width-w*n)/2)
for x=2 to w-1 do
integer cy = n+floor((height-h*n)/2)
for y=2 to h-1 do
integer cxy = c[x,y],
clxy = cl[x,y],
cnxy = -cxy
for i=x-1 to x+1 do
for j=y-1 to y+1 do
cnxy += c[i,j]
end for
end for
integer live = iff(cxy?cnxy>=2 and cnxy<=3:cnxy==3),
colour = iff(live?iff(cxy?iff(clxy?CD_PURPLE -- adult
:CD_GREEN) -- newborn
:iff(clxy?CD_RED -- old
:CD_YELLOW)) -- shortlived
:CD_BLACK)
cn[x,y] = live
alive += live
cdCanvasSetForeground(cddbuffer,colour)
cdCanvasBox(cddbuffer, cx, cx+n-1, cy, cy+n-1)
cy += n
end for
cx += n
end for
cdCanvasFlush(cddbuffer)
if not alive then
IupStoreAttribute(hTimer, "RUN", "NO")
IupStoreAttribute(dlg, "TITLE", "died")
elsif c=cn then
IupStoreAttribute(hTimer, "RUN", "NO")
IupStoreAttribute(dlg, "TITLE", "stable")
else
cl = c
c = deep_copy(cn)
fps += 1
if time()>=t1 then
IupSetStrAttribute(dlg,"TITLE","%s (%d FPS)",{title,fps})
t1 = time()+1
fps = 0
end if
end if
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdCanvas cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_RED)
return IUP_DEFAULT
end function
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)
if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)
if find(c," ") then draw(' ') -- Clear
elsif find(c,"+bB") then draw('+') -- Blinker
elsif find(c,"gG") then draw('G') -- Glider
elsif find(c,"tT") then draw('T') -- Thunderbird
elsif find(c,"xX") then draw('X') -- Cross
end if
IupStoreAttribute(hTimer, "RUN", "YES")
return IUP_CONTINUE
end function
function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=390x390")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="%s", MINSIZE=350x55`, {title})
-- (above MINSIZE prevents the title from getting squished)
IupSetCallback(dlg, "KEY_CB", Icallback("key_cb"))
IupShow(dlg)
IupSetAttribute(canvas,"RASTERSIZE",NULL)
-- hTimer = IupTimer(Icallback("timer_cb"),40) -- 25fps (maybe)
hTimer = IupTimer(Icallback("timer_cb"),100) -- 10fps
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Harbour | Harbour | IF x == 1
SomeFunc1()
ELSEIF x == 2
SomeFunc2()
ELSE
SomeFunc()
ENDIF |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Python | Python | >>> def strcat(sequence):
return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]
>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))
Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'
>>> |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Visual_Basic | Visual Basic | Sub Main
MsgBox Command$
End Sub |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Visual_Basic_.NET | Visual Basic .NET | Sub Main(ByVal args As String())
For Each token In args
Console.WriteLine(token)
Next
End Sub |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Vlang | Vlang | import os
fn main() {
for i, x in os.args[1..] {
println("the argument #$i is $x")
}
} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #IDL | IDL | ; The following computes the factorial of a number "n"
fact = product(indgen( n )+1) ; where n should be an integer |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Inform_7 | Inform 7 | [This is a single-line comment.]
[This is a
multi-line comment.]
[Comments can [be nested].] |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Picat | Picat | go =>
Rows = 3,
Cols = 3,
println(blinker),
pattern(blinker, Pattern,I,J),
life(fill(Rows,Cols,Pattern,I,J)),
nl.
fill(Rows, Cols, Obj) = fill(Rows, Cols, Obj,1,1).
fill(Rows, Cols, Obj,OffsetI,OffsetJ) = Grid =>
Grid = new_array(Rows,Cols), bind_vars(Grid,0),
foreach(I in 1..Obj.length, J in 1..Obj[1].length)
Grid[I+OffsetI-1,J+OffsetJ-1] := Obj[I,J]
end.
% We stop whenever a fixpoint/cycle is detected
life(S) =>
Rows = S.length,
Cols = S[1].length,
println([rows=Rows, cols=Cols]),
print_grid(S),
Seen = new_map(), % detect fixpoint and cycle
Count = 0,
while (not Seen.has_key(S))
Seen.put(S,1),
T = new_array(Rows,Cols),
foreach(I in 1..Rows, J in 1..Cols)
Sum = sum([S[I+A,J+B] : A in -1..1,B in -1..1,
I+A > 0, J+B > 0,
I+A =< Rows, J+B =< Cols]) - S[I,J],
C = rules(S[I,J], Sum),
T[I,J] := C
end,
print_grid(T),
S := T,
Count := Count + 1
end,
printf("%d generations\n", Count).
print_grid(G) =>
foreach(I in 1..G.length)
foreach(J in 1..G[1].length)
if G[I,J] == 1 then print("#") else print(".") end
end,
nl
end,
nl.
% The Rules of Life
rules(This,Sum) = 1, (This == 1, member(Sum,[2,3]); This == 0, Sum == 3) => true.
rules(_This, _Sum) = 0 => true.
%
% The patterns
% pattern(Name, Pattern, OffsetI, OffsetJ)
% where Offset* is the recommended offsets in a grid.
%
% For the task
pattern(blinker, Pattern,I,J) ?=>
Pattern = [[0,0,0],
[1,1,1],
[0,0,0]],
I=1,J=1. |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Haskell | Haskell | fac x = if x==0 then
1
else x * fac (x - 1) |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Quackery | Quackery | [ swap join join ] is glue ( [ [ [ --> [ )
[ [ dup size
dup 0 = iff
[ 2drop [] ] done
dup 1 = iff
[ drop unpack ] done
2 = iff
[ unpack $ ' and ' glue ] done
behead swap recurse $ ', ' glue ]
$ '{' swap join $ '}' join ] is quibble ( [ --> $ )
[] quibble echo$ cr
$ 'ABC' nest$ quibble echo$ cr
$ 'ABC DEF' nest$ quibble echo$ cr
$ 'ABC DEF G H' nest$ quibble echo$ |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #R | R | quib <- function(vect)
{
#The task does not consider empty strings to be words, so we remove them immediately.
#We could also remove non-upper-case characters, but the tasks gives off the impression that the user will do that.
vect <- vect[nchar(vect) != 0]
len <- length(vect)
allButLastWord <- if(len >= 2) paste0(vect[seq_len(len - 1)], collapse = ", ") else ""
paste0("{", if(nchar(allButLastWord) == 0) vect else paste0(allButLastWord, " and ", vect[len]), "}")
}
quib(character(0)) #R has several types of empty string, e.g. character(0), "", and c("", "", "").
quib("")
quib(" ")
quib(c("", ""))
quib(rep("", 10))
quib("ABC")
quib(c("ABC", ""))
quib(c("ABC", "DEF"))
quib(c("ABC", "DEF", "G", "H"))
quib(c("ABC", "DEF", "G", "H", "I", "J", "")) |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #Wren | Wren | import "os" for Process
System.print(Process.arguments) |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #XPL0 | XPL0 | int C;
[loop [C:= ChIn(8);
if C = \EOF\$1A then quit;
ChOut(0, C);
];
CrLf(0);
] |
http://rosettacode.org/wiki/Command-line_arguments | Command-line arguments | Command-line arguments is part of Short Circuit's Console Program Basics selection.
Scripted main
See also Program name.
For parsing command line arguments intelligently, see Parsing command-line arguments.
Example command line:
myprogram -c "alpha beta" -h "gamma"
| #zkl | zkl | System.argv.println();
vm.arglist.println(); |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Intercal | Intercal | PLEASE NOTE This is a comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Io | Io | # Single-line comment
// Single-line comment
/* Multi-line
comment */ |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de life (DX DY . Init)
(let Grid (grid DX DY)
(for This Init
(=: life T) )
(loop
(disp Grid NIL
'((This) (if (: life) "X " " ")) )
(wait 1000)
(for Col Grid
(for This Col
(let N # Count neighbors
(cnt
'((Dir) (get (Dir This) 'life))
(quote
west east south north
((X) (south (west X)))
((X) (north (west X)))
((X) (south (east X)))
((X) (north (east X))) ) )
(=: next # Next generation
(if (: life)
(>= 3 N 2)
(= N 3) ) ) ) ) )
(for Col Grid # Update
(for This Col
(=: life (: next)) ) ) ) ) )
(life 5 5 b3 c3 d3) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #HicEst | HicEst | IF( a > 5 ) WRITE(Messagebox) a ! single line IF
IF( a >= b ) THEN
WRITE(Text=some_string) a, b
ELSEIF(some_string > "?") THEN
WRITE(ClipBoard) some_string
ELSEIF( nonzero ) THEN
WRITE(WINdowhandle=nnn) some_string
ELSE
WRITE(StatusBar) a, b, some_string
ENDIF |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Racket | Racket | (define (quibbling words)
(define (sub-quibbling words)
(match words
['() ""]
[(list a) a]
[(list a b) (format "~a and ~a" a b)]
[(list a b ___) (format "~a, ~a" a (sub-quibbling b))]))
(format "{~a}" (sub-quibbling words)))
(for ((input '([] ["ABC"] ["ABC" "DEF"] ["ABC" "DEF" "G" "H"])))
(printf "~s\t->\t~a~%" input (quibbling input))) |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Raku | Raku | sub comma-quibbling(@A) {
<{ }>.join: @A < 2 ?? @A !! "@A[0..*-2].join(', ') and @A[*-1]";
}
say comma-quibbling($_) for
[], [<ABC>], [<ABC DEF>], [<ABC DEF G H>]; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Isabelle | Isabelle | theory Text
imports Main
begin
(* Top-level Isar comment. *)
end |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #J | J | NB. Text that follows 'NB.' has no effect on execution.
0 : 0
Multi-line comments may be placed in strings,
like this.
)
Note 'example'
Another way to record multi-line comments as text is to use 'Note', which is actually
a simple program that makes it clearer when defined text is used only to provide comment.
)
'A simple string which is not used is legal, and will be discarded' |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #PL.2FI | PL/I | (subscriptrange):
Conway: procedure options (main); /* 20 November 2013 */
/* A grid of (1:100, 1:100) is desired; the array GRID is defined as (0:101, 0:101), */
/* to satisfy the requirement that elements off-grid are zero. */
declare n fixed binary; /* grid size) */
put ('What grid size do you want?');
get (n);
put skip list ('Generating a grid of size ' || trim(n) );
begin;
declare grid (0:n+1,0:n+1) bit(1) initial ((*) '0'b);
declare new (0:n+1,0:n+1) bit(1);
declare cell(3,3) defined grid(1sub-2+i, 2sub-2+j) bit (1);
declare (i, j, k) fixed binary;
/* Initialize some cells. */
grid(2,2) = '1'b; grid(2,3) = '1'b; grid(2,4) = '1'b;
/* Print the initial state. */
put list ('Initial pattern:');
do i = 1 to n;
put skip;
do j = 1 to n;
put edit (grid(i,j)) (b(1));
end;
end;
do k = 1 to 4;
/* Do one generation of life */
new = '0'b;
/* For each C, the center of a 3 x 3 cell matrix. */
do i = 1 to n;
do j = 1 to n;
if grid(i,j) then
select (sum(cell)-1);
when (0,1) new(i,j) = '0'b;
when (4,5,6,7,8) new(i,j) = '0'b;
when (2,3) new(i,j) = '1'b;
end;
else
select (sum(cell));
when (3) new(i,j) = '1'b;
otherwise new(i,j) = '0'b;
end;
end;
end;
grid = new; /* Update GRID with the new generation. */
/* Print the generation. */
put skip(2) list ('Generation ' || trim(k));
do i = 1 to n;
put skip;
do j = 1 to n;
put edit (grid(i,j)) (b(1));
end;
end;
end;
end;
end Conway; |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #HPPPL | HPPPL | IF X THEN
// do if X is not 0
ELSE
// do if X is 0
END; |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #REBOL | REBOL | rebol []
comma-quibbling: func [block] [
rejoin [
"^{"
to-string use [s] [
s: copy block
s: next s
forskip s 2 [insert s either tail? next s [" and "] [", "]]
s: head s
]
"^}"
]
]
foreach t [[] [ABC] [ABC DEF] [ABC DEF G H]] [print comma-quibbling t]
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #REXX | REXX | say quibbling('')
say quibbling('ABC')
say quibbling('ABC DEF')
say quibbling('ABC DEF G H')
exit
quibbling: procedure
parse arg list
Select
When list='' Then result=''
When words(list)=1 then result=word(list,1)
Otherwise result=translate(strip(subword(list,1,words(list)-1)),',',' '),
'and' word(list,words(list))
End
Return '{'result'}' |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Java | Java | /* This is a comment */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #JavaScript | JavaScript | n = n + 1; // This is a comment |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Pointless | Pointless | -----------------------------------------------------------
-- Print 100 simulated states of conway's game of life
-- for a glider starting pattern on a wrapping grid
-- Print generation number along with cells
output =
initCells
|> iterate(updateCells)
|> take(130)
|> enumerate
|> map(showPair)
|> printFrames
initCells =
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
width = length(initCells[0])
height = length(initCells)
positions =
for y in range(0, height - 1)
for x in range(0, width - 1)
yield (x, y)
-----------------------------------------------------------
-- Update each cell in the grid according to its position,
-- and convert the resulting list back to a 2D array
updateCells(cells) =
positions
|> map(tick(cells))
|> toNDArray((height, width))
-----------------------------------------------------------
-- Get the new value for a cell at a give position
-- based on the current cell values in the grid
tick(cells, pos) = toInt(survive or birth) where {
survive = cells[y][x] == 1 and count in {2, 3}
birth = cells[y][x] == 0 and count == 3
count = getCount(x, y, cells)
(x, y) = pos
}
-----------------------------------------------------------
-- Get the number of live neighbors of a given position
getCount(x, y, cells) = sum(
for dx in [-1, 0, 1]
for dy in [-1, 0, 1]
when (dx != 0 or dy != 0)
yield getNeighbor(x + dx, y + dy, cells)
)
getNeighbor(x, y, cells) = cells[y % height][x % width]
-----------------------------------------------------------
-- Print the board and generation number given pairs
-- of (gen, cells) from the enumerate function
showPair(pair) =
format("{}\ngeneration: {}", [showCells(cells), gen])
where (gen, cells) = pair
showCells(cells) =
toList(cells)
|> map(showRow)
|> join("\n")
showRow(row) =
format("|{}|", [map(showCell, toList(row)) |> join("")])
showCell(cell) =
if cell == 1 then "*" else " " |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #i | i | //'i' supports if, else, and else if
software {
a = 3
if a = 3
print("a = three")
else if a = 2
print("a = two")
else
print("a = ", a)
end
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Ring | Ring |
# Project : Comma Quibbling
text = list(4)
text[1] = "{}"
text[2] = "ABC"
text[3] = "ABC,DEF"
text[4] = "ABC,DEF,G,H"
comma(text)
func comma(text)
listtext = []
for n = 1 to 4
listtext = str2list(substr(text[n], ",", nl))
if n = 2
see "{" + list2str(listtext) + "}" + nl
loop
ok
if len(listtext) = 1
see "{}" + nl
loop
ok
str = "{"
for m = 1 to len(listtext)-1
if len(listtext) = 2
str = str + listtext[m] + " "
else
str = str + listtext[m] + ", "
ok
next
if len(listtext) = 2
str = left(str, len(str)-1)
else
str = left(str, len(str)-2)
ok
if len(listtext) = 2
str = str + " " + listtext[len(listtext)] + "}"
else
str = str + " and " + listtext[len(listtext)] + "}"
ok
see str + nl
next
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Ruby | Ruby | def comma_quibbling(a)
%w<{ }>.join(a.length < 2 ? a.first :
"#{a[0..-2].join(', ')} and #{a[-1]}")
end
[[], %w<ABC>, %w<ABC DEF>, %w<ABC DEF G H>].each do |a|
puts comma_quibbling(a)
end |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #JCL | JCL |
//* This is a comment line (//* in columns 1-3)
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Joy | Joy | # this is a single line comment
(* this is a
multi-line comment *) |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
/size 400 def
realtime srand
/rand1 { rand 2147483647 div } def
/m { moveto } bind def
/l { rlineto} bind def
/drawboard {
0 1 n 1 sub { /y exch def
0 1 n 1 sub { /x exch def
board x get y get 1 eq {
x c mul y c mul m
c 0 l 0 c l c neg 0 l
closepath fill
} if
} for } for
} def
/r1n { dup 0 lt { n add } if dup n ge { n sub } if } def
/neighbors { /y exch def /x exch def 0
y 1 sub 1 y 1 add { r1n /y1 exch def
x 1 sub 1 x 1 add { r1n /x1 exch def
board x1 get y1 get add
} for } for
board x get y get sub
} def
/iter {
/board
[0 1 n 1 sub { /x exch def
[0 1 n 1 sub { /y exch def
x y neighbors
board x get y get
0 eq { 3 eq {1}{0} ifelse }
{ dup 2 eq exch 3 eq or {1}{0} ifelse } ifelse
} for ]
} for ] def
} def
/n 200 def
/initprob .15 def
/c size n div def
/board [ n {[ n { rand1 initprob le {1}{0} ifelse } repeat]} repeat ] def
1000 { drawboard showpage iter } repeat
%%EOF |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Icon_and_Unicon | Icon and Unicon | if expr0 then
expr1
else
expr2 |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Run_BASIC | Run BASIC | wrds$ = "[]
[""ABC""]
[""ABC"", ""DEF""]
[""ABC"", ""DEF"", ""G"", ""H""]
"
while word$(wrds$,j+1,chr$(13)) <> ""
a$ = word$(wrds$,j+1,chr$(13))
print a$;" ==> ";
a$ = "{"+mid$(a$,2,len(a$)-2)+"}"
j = j + 1
for i = len(a$) to 1 step -1
if mid$(a$,i,1) = "," then
a$ = left$(a$,i-1) + " and " + mid$(a$,i+2)
exit for
end if
next i
print a$
WEND |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Rust | Rust |
fn quibble(seq: &[&str]) -> String {
match seq.len() {
0 => "{}".to_string(),
1 => format!("{{{}}}", seq[0]),
_ => {
format!("{{{} and {}}}",
seq[..seq.len() - 1].join(", "),
seq.last().unwrap())
}
}
}
fn main() {
println!("{}", quibble(&[]));
println!("{}", quibble(&["ABC"]));
println!("{}", quibble(&["ABC", "DEF"]));
println!("{}", quibble(&["ABC", "DEF", "G", "H"]));
}
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #jq | jq | # this is a single line comment
"Hello #world" # the first # on this line is part of the jq program
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Jsish | Jsish | #!/usr/bin/env/jsish
/* Comments, in Jsish */
// to end of line comment, double slash
/*
Enclosed comment, slash star, ending with star slash
Cannot be nested, but can cross line boundaries and occur
pretty much anywhere whitespace is allowed
*/
var x = 'X'; /* A var called X */
/* active code on this line */ printf("Result %q %d\n", /* comment code mix */ x, /**/42);
;x;
// jsish also handles double slash commented
// unit test echo lines as a special case of "expect failure"
;//noname(x);
/*
=!EXPECTSTART!=
Result X 42
x ==> X
noname(x) ==>
PASS!: err = can not execute expression: 'noname' not a function
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Prolog | Prolog |
%----------------------------------------------------------------------%
% GAME OF LIFE %
% %
% Adapt the prediacte grid_size according to the grid size of the %
% start pic. %
% Modify the number of generations. %
% Run PROLOG and type '[gol].' to compile the source file. %
% Create a subfolder <subfolder> where your gol.pl resides and place %
% your initial PBM '<filename>0.0000.pbm' inside <subfolder>. %
% You need to adjust the number of zeros after <filename>. The %
% sequence of zeros after '0.' must be as long as the number of %
% generations. This is important to obtain a propper animation. %
% (Maybe someone knows a better solution for this) %
% Start PROLOG and run %
% %
% cellular('./<subloder>/<filename>'). %
% %
% Inside <subfolder> run the following shell command %
% %
% convert -delay 25 -loop 0 <filename>* <filename>.gif %
% %
%----------------------------------------------------------------------%
%----------------------------------------------------------------------%
% Special thanks to René Thiemann improving the runtime performance. %
%----------------------------------------------------------------------%
% Size of the 2D grid
grid_size(300).
% Number of generations
generations(1000).
%----------------------------------------------------------------------%
% Main procedure: generate n generations of life and store each file. %
% cellular( +File path ) %
%----------------------------------------------------------------------%
cellular(I) :-
grid_size(GS),
string_concat(I,'0.0000.pbm',I1),
read_pbm(I1,GS,M),
cellular_(I,M,GS,1), !.
cellular_(I,M,GS,N) :-
N1 is N+1,
format(atom(N0),'~4d',N),
string_concat(I,N0,I1),
string_concat(I1,'.pbm',I2),
step(M,M1),
write_pbm(M1,GS,I2), !,
cellular_(I,M1,GS,N1).
cellular_(_,_,_,GE) :-
generations(GE),!.
%----------------------------------------------------------------------%
% Apply the Game Of Life rule set to every cell. %
% step( +OldMatrix, +NewMatrix ) %
% %
% ss | s | ... | s ss ... step_ss %
% ----+---+-----+--- s ... step_s %
% ii | i | ... | i ii ... step_ii %
% ----+---+-----+--- i ... step_i %
% : | : | : | : ee ... step_ee %
% ----+---+-----+--- e ... step_e %
% ii | i | ... | i %
% ----+---+-----+--- %
% ee | e | ... | e %
% %
%----------------------------------------------------------------------%
step([R1,R2|M],[H|T]) :-
step_ss(R1,R2,H), !,
step_([R1,R2|M],T).
step_([R1,R2,R3|M],[H|T]) :-
step_ii(R1,R2,R3,H),
step_([R2,R3|M],T), !.
step_([R1,R2],[H]) :-
step_ee(R1,R2,H).
% Start case
step_ss([A1,A2|R1],[B1,B2|R2],[H|T]) :-
rule([0,0,0],[0,A1,A2],[0,B1,B2],H),
step_s([A1,A2|R1],[B1,B2|R2],T).
step_s([A1,A2,A3|R1],[B1,B2,B3|R2],[H|T]) :-
rule([0,0,0],[A1,A2,A3],[B1,B2,B3],H),
step_s([A2,A3|R1],[B2,B3|R2],T).
step_s([A1,A2],[B1,B2],[H]) :-
rule([0,0,0],[A1,A2,0],[B1,B2,0],H).
% Immediate case
step_ii([A1,A2|R1],[B1,B2|R2],[C1,C2|R3],[H|T]) :-
rule([0,A1,A2],[0,B1,B2],[0,C1,C2],H),
step_i([A1,A2|R1],[B1,B2|R2],[C1,C2|R3],T).
step_i([A1,A2,A3|R1],[B1,B2,B3|R2],[C1,C2,C3|R3],[H|T]) :-
rule([A1,A2,A3],[B1,B2,B3],[C1,C2,C3],H),
step_i([A2,A3|R1],[B2,B3|R2],[C2,C3|R3],T).
step_i([A1,A2],[B1,B2],[C1,C2],[H]) :-
rule([A1,A2,0],[B1,B2,0],[C1,C2,0],H).
% End case
step_ee([A1,A2|R1],[B1,B2|R2],[H|T]) :-
rule([0,A1,A2],[0,B1,B2],[0,0,0],H),
step_e([A1,A2|R1],[B1,B2|R2],T).
step_e([A1,A2,A3|R1],[B1,B2,B3|R2],[H|T]) :-
rule([A1,A2,A3],[B1,B2,B3],[0,0,0],H),
step_e([A2,A3|R1],[B2,B3|R2],T).
step_e([A1,A2],[B1,B2],[H]) :-
rule([A1,A2,0],[B1,B2,0],[0,0,0],H).
%----------------------------------------------------------------------%
% o Any dead cell with exactly three live neighbours becomes a live %
% cell, as if by reproduction. %
% o Any other dead cell remains dead. %
% o Any live cell with fewer than two live neighbours dies, as if %
% caused by under-population. %
% o Any live cell with two or three live neighbours lives on to the %
% next generation. %
% o Any live cell with more than three live neighbours dies, as if by %
% overcrowding. %
% %
% [Source: Wikipedia] %
%----------------------------------------------------------------------%
rule([A,B,C],[D,0,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 3.
rule([_,_,_],[_,0,_],[_,_,_],0).
rule([A,B,C],[D,1,F],[G,H,I],0) :- A+B+C+D+F+G+H+I < 2.
rule([A,B,C],[D,1,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 2.
rule([A,B,C],[D,1,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 3.
rule([A,B,C],[D,1,F],[G,H,I],0) :- A+B+C+D+F+G+H+I > 3.
%----------------------------------------------------------------------%
% Read a 2bit Protable Bitmap into a GS x GS 2-dimensional list. %
% read_pbm( +File path, +Grid size, -List 2D ) %
%----------------------------------------------------------------------%
read_pbm(F,GS,M) :-
open(F,read,S),
skip(S,10),
skip(S,10),
get(S,C),
read_file(S,C,L),
nest(L,GS,M),
close(S).
read_file(S,C,[CHR|T]) :-
CHR is C-48,
get(S,NC),
read_file(S,NC,T).
read_file(_,-1,[]) :- !.
%----------------------------------------------------------------------%
% Morph simple list into a 2-dimensional one with size GS x GS %
% nest( ?List simple, ?Grid size, ?2D list ) %
%----------------------------------------------------------------------%
nest(L,GS,[H|T]) :-
length(H,GS),
append(H,S,L),
nest(S,GS,T).
nest(L,GS,[L]) :-
length(L,S),
S =< GS, !.
%----------------------------------------------------------------------%
% Write a GS x GS 2-dimensional list into a 2bit Protable Bitmap. %
% write_pbm( +List 2D, +Grid size, +File path ) %
%----------------------------------------------------------------------%
write_pbm(L,GS,F) :-
open(F,write,S),
write(S,'P1'), nl(S),
write(S,GS), put(S,' '), write(S,GS), nl(S),
write_file(S,L),
close(S).
write_file(S,[H|T]) :-
write_line(S,H), nl(S),
write_file(S,T).
write_file(_,[]) :- !.
write_line(S,[H|T]) :-
write(S,H), put(S,' '),
write_line(S,T).
write_line(_,[]) :- !.
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #IDL | IDL | if a eq 5 then print, "a equals five" [else print, "a is something else"] |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Scala | Scala | def quibble( s:List[String] ) = s match {
case m if m.isEmpty => "{}"
case m if m.length < 3 => m.mkString("{", " and ", "}")
case m => "{" + m.init.mkString(", ") + " and " + m.last + "}"
}
// A little test...
{
println( quibble( List() ) )
println( quibble( List("ABC") ) )
println( quibble( List("ABC","DEF") ) )
println( quibble( List("ABC","DEF","G","H") ) )
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Scheme | Scheme |
(define (quibble . args)
(display "{")
(do ((rem args (cdr rem)))
((null? rem) (display "}\n"))
(display (car rem))
(cond ((= 1 (length rem)) )
((= 2 (length rem))
(display " and "))
(else
(display ", ")))))
(quibble)
(quibble "ABC")
(quibble "ABC" "DEF")
(quibble "ABC" "DEF" "G" "H")
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Julia | Julia | # single line
#=
Multi-
line
comment
=# |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #K | K | / this is a comment
2+2 / as is this
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Processing | Processing | boolean play = true;
int cellSize = 10;
int cols, rows;
int lastCell = 0;
int sample = 10;
// Game of life board
int[][] grid;
void setup() {
size(800, 500);
noStroke();
// Calculate cols, rows and init array
cols = width/cellSize;
rows = height/cellSize;
grid = new int[cols][rows];
init(-1); // randomized start
println("Press 'space' to start/stop");
println("'e' to clear all cells");
println("'b' demonstrate 'blinker'");
println("'g' demonstrate glider");
println("'r' to randomize grid");
println("'+' and '-' to change speed");
}
void draw() {
background(0);
for ( int i = 0; i < cols; i++) {
for ( int j = 0; j < rows; j++) {
if ((grid[i][j] == 1)) fill(255);
else fill(0);
rect(i*cellSize, j*cellSize, cellSize, cellSize);
}
}
if (play && frameCount%sample==0 && !mousePressed) {
generate();
}
}
void generate() {
int[][] nextGrid = new int[cols][rows];
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int ngbs = countNgbs(x, y);
// the classic Conway rules
if ((grid[x][y] == 1) && (ngbs < 2)) nextGrid[x][y] = 0; // solitude
else if ((grid[x][y] == 1) && (ngbs > 3)) nextGrid[x][y] = 0; // crowded
else if ((grid[x][y] == 0) && (ngbs == 3)) nextGrid[x][y] = 1; // cell born
else nextGrid[x][y] = grid[x][y]; // keep
}
}
grid = nextGrid;
}
int countNgbs(int x, int y) {
int ngbCount = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
// 'united' borders
ngbCount += grid[(x+i+cols)%cols][(y+j+rows)%rows];
}
}
// cell taken out of count
ngbCount -= grid[x][y];
return ngbCount;
}
void init(int option) {
int state;
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
if (option == -1) {
state = int(random(2));
} else {
state = option;
}
grid[x][y] = state;
}
}
}
void keyReleased() {
if (key == 'r') {
init(-1); // randomize grid
}
if (key == 'e') {
init(0); // empty grid
}
if (key == 'g') {
int glider[][] = {
{0, 1, 0},
{0, 0, 1},
{1, 1, 1}};
setNine(10, 10, glider);
}
if (key == 'b') {
int blinker[][] = {
{0, 1, 0},
{0, 1, 0},
{0, 1, 0}};
setNine(10, 10, blinker);
}
if (key == ' ') {
play = !play;
}
if (key == '+' || key == '=') {
sample=max(sample-1, 1);
}
if (key == '-') {
sample++;
}
}
void setNine(int x, int y, int nine[][]) {
for (int i = 0; i <= 2; i++) {
for (int j = 0; j <= 2; j++) {
grid[(x+i+cols)%cols][(y+j+rows)%rows] = nine[i][j];
}
}
}
void mousePressed() {
paint();
}
void mouseDragged() {
paint();
}
void paint() {
int x = mouseX/cellSize;
int y = mouseY/cellSize;
int p = y*cols + x;
if (p!=lastCell) {
lastCell=p;
int states[] = {1, 0};
grid[x][y] = states[grid[x][y]]; // invert
}
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Inform_7 | Inform 7 | [short form]
if N is 1, say "one.";
otherwise say "not one.";
[block form]
if N is 1:
say "one.";
otherwise if N is 2:
say "two.";
otherwise:
say "not one or two.";
[short and long forms can be negated with "unless"]
unless N is 1, say "not one." |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Sed | Sed | s/#.*$//g
y/[/{/
y/]/}/
s/"//g
s/ [A-Z][A-Z]*}/ and&/g
s/, and/ and/ |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: quibble (in array string: input) is func
result
var string: quibble is "{";
begin
case length(input) of
when {0}: quibble &:= "}";
when {1}: quibble &:= input[1] & "}";
otherwise: quibble &:= join(input[.. pred(length(input))], ", ") &
" and " & input[length(input)] & "}";
end case;
end func;
const proc: main is func
begin
writeln(quibble(0 times ""));
writeln(quibble([] ("ABC")));
writeln(quibble([] ("ABC", "DEF")));
writeln(quibble([] ("ABC", "DEF", "G", "H")));
end func; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #KonsolScript | KonsolScript | //This is a comment.
//This is another comment.
/* This is a comment too. */
/* This is a
multi-line
comment */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Kotlin | Kotlin | // This is a single line comment
/*
This is a
multi-line
comment
*/
/*
Multi-line comments
/*
can also be nested
*/
like so
*/
const val CURRENT_VERSION = "1.0.5-2" // A comment can also be added at the end of a line
const val /* or even in the middle of a line */ NEXT_MAJOR_VERSION = "1.1"
/**
* This is a documentation comment used by KDoc.
*
* It's documenting the main function which is the entry-point to a Kotlin executable.
*
* @param [args] A string array containing the command line arguments (if any) passed to the executable
* @return Implicit return value is Unit which signifies no meaningful return value (like 'void' in java)
*/
fun main(args: Array<String>) {
println("Current stable version is $CURRENT_VERSION")
println("Next major version is $NEXT_MAJOR_VERSION")
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Python | Python | import random
from collections import defaultdict
printdead, printlive = '-#'
maxgenerations = 3
cellcount = 3,3
celltable = defaultdict(int, {
(1, 2): 1,
(1, 3): 1,
(0, 3): 1,
} ) # Only need to populate with the keys leading to life
##
## Start States
##
# blinker
u = universe = defaultdict(int)
u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1
## toad
#u = universe = defaultdict(int)
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,6)], u[(6,7)], u[(6,8)] = 1,1,1
## glider
#u = universe = defaultdict(int)
#maxgenerations = 16
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,5)] = 1
#u[(7,6)] = 1
## random start
#universe = defaultdict(int,
# # array of random start values
# ( ((row, col), random.choice((0,1)))
# for col in range(cellcount[0])
# for row in range(cellcount[1])
# ) ) # returns 0 for out of bounds
for i in range(maxgenerations):
print("\nGeneration %3i:" % ( i, ))
for row in range(cellcount[1]):
print(" ", ''.join(str(universe[(row,col)])
for col in range(cellcount[0])).replace(
'0', printdead).replace('1', printlive))
nextgeneration = defaultdict(int)
for row in range(cellcount[1]):
for col in range(cellcount[0]):
nextgeneration[(row,col)] = celltable[
( universe[(row,col)],
-universe[(row,col)] + sum(universe[(r,c)]
for r in range(row-1,row+2)
for c in range(col-1, col+2) )
) ]
universe = nextgeneration |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Isabelle | Isabelle | theory Scratch
imports Main
begin
text‹if-then-else›
lemma "(if True then 42 else 0) = 42" by simp
text‹case statement with pattern matching, which evaluates to the True-case›
lemma "case [42] of
Nil ⇒ False
| [x] ⇒ True
| x#xs ⇒ False" by simp
text‹Loops are implemented via recursive functions›
fun recurse :: "nat ⇒ nat" where
"recurse 0 = 0"
| "recurse (Suc n) = recurse n"
text‹The function always returns zero.›
lemma "recurse n = 0" by(induction n) simp+
end |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #SenseTalk | SenseTalk | Quibble [] // (No input words).
Quibble ["ABC"]
Quibble ["ABC", "DEF"]
Quibble ["ABC", "DEF", "G", "H"]
to Quibble with wordList
if the number of items in wordList is ...
... 0 then put "{}"
... 1 then put "{" & item 1 of wordList & "}"
... else put "{" & (items first to penultimate of wordList) joined by ", " & " and " & the last item of wordlist & "}"
end if
end Quibble
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Sidef | Sidef | func comma_quibbling(words) {
'{' + ([words.ft(0, -2).join(', ')]-[''] + [words.last] -> join(' and ')) + '}';
}
[<>, <ABC>, <ABC DEF>, <ABC DEF G H>].each { |w|
say comma_quibbling(w);
} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lambdatalk | Lambdatalk |
;; this is a comment on a single line
°°°
this is
a comment
on several lines
°°°
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #LabVIEW | LabVIEW | # This is a comment. |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #R | R | # Generates a new board - either a random one, sample blinker or gliders, or user specified.
gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL)
{
if(type=="random")
{
return(matrix(runif(nrow*ncol) > 0.5, nrow=nrow, ncol=ncol))
} else if(type=="blinker")
{
seeds <- list(c(2,1),c(2,2),c(2,3))
} else if(type=="glider")
{
seeds <- list(c(1,2),c(2,3),c(3,1), c(3,2), c(3,3))
}
board <- matrix(FALSE, nrow=nrow, ncol=ncol)
for(k in seq_along(seeds))
{
board[seeds[[k]][1],seeds[[k]][2]] <- TRUE
}
board
}
# Returns the number of living neighbours to a location
count.neighbours <- function(x,i,j)
{
sum(x[max(1,i-1):min(nrow(x),i+1),max(1,j-1):min(ncol(x),j+1)]) - x[i,j]
}
# Implements the rulebase
determine.new.state <- function(board, i, j)
{
N <- count.neighbours(board,i,j)
(N == 3 || (N ==2 && board[i,j]))
}
# Generates the next interation of the board from the existing one
evolve <- function(board)
{
newboard <- board
for(i in seq_len(nrow(board)))
{
for(j in seq_len(ncol(board)))
{
newboard[i,j] <- determine.new.state(board,i,j)
}
}
newboard
}
# Plays the game. By default, the board is shown in a plot window, though output to the console if possible.
game.of.life <- function(board, nsteps=50, timebetweensteps=0.25, graphicaloutput=TRUE)
{
if(!require(lattice)) stop("lattice package could not be loaded")
nr <- nrow(board)
for(i in seq_len(nsteps))
{
if(graphicaloutput)
{
print(levelplot(t(board[nr:1,]), colorkey=FALSE))
} else print(board)
Sys.sleep(timebetweensteps)
newboard <- evolve(board)
if(all(newboard==board))
{
message("board is static")
break
} else if(sum(newboard) < 1)
{
message("everything is dead")
break
} else board <- newboard
}
invisible(board)
}
# Example usage
game.of.life(gen.board("blinker"))
game.of.life(gen.board("glider", 18, 20))
game.of.life(gen.board(, 50, 50)) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #J | J | if(s.equals("Hello World"))
{
foo();
}
else if(s.equals("Bye World"))
bar();//{}'s optional for one-liners
else
{
deusEx();
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Standard_ML | Standard ML | local
fun quib [] = ""
| quib [x] = x
| quib [x0,x1] = x0 ^ " and " ^ x1
| quib (x::xs) = x ^ ", " ^ quib xs
in
fun quibble xs = "{" ^ quib xs ^ "}"
end
(* Tests: *)
val t_quibble_0 = quibble [] = "{}"
val t_quibble_1 = quibble ["ABC"] = "{ABC}"
val t_quibble_2 = quibble ["ABC", "DEF"] = "{ABC and DEF}"
val t_quibble_3 = quibble ["ABC", "DEF", "G", "H"] = "{ABC, DEF, G and H}"
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Swift | Swift | let inputs = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]
func quibbling(var words:[String]) {
if words.count == 0 {
println("{}")
} else if words.count == 1 {
println("{\(words[0])}")
} else if words.count == 2 {
println("{\(words[0]) and \(words[1])}")
} else {
var output = "{"
while words.count != 2 {
output += words.removeAtIndex(0) + ", "
}
output += "\(words.removeAtIndex(0)) and \(words.removeAtIndex(0))}"
println(output)
}
}
for word in inputs {
quibbling(word)
} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lang5 | Lang5 | # This is a comment. |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #langur | langur | # single line comment starts with hash mark
/* inline or multi-line comment uses C-style syntax */
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Racket | Racket |
#lang racket
(require 2htdp/image 2htdp/universe)
;;;
;;; Grid object
;;;
(define (make-empty-grid m n)
(build-vector m (lambda (y) (make-vector n 0))))
(define rows vector-length)
(define (cols grid)
(vector-length (vector-ref grid 0)))
(define (make-grid m n living-cells)
(let loop ([grid (make-empty-grid m n)]
[cells living-cells])
(if (empty? cells)
grid
(loop (2d-set! grid (caar cells) (cadar cells) 1) (cdr cells)))))
(define (2d-ref grid i j)
(cond [(< i 0) 0]
[(< j 0) 0]
[(>= i (rows grid)) 0]
[(>= j (cols grid)) 0]
[else (vector-ref (vector-ref grid i) j)]))
(define (2d-refs grid indices)
(map (lambda (ind) (2d-ref grid (car ind) (cadr ind))) indices))
(define (2d-set! grid i j val)
(vector-set! (vector-ref grid i) j val)
grid)
;;; cartesian product of 2 lists
(define (cart l1 l2)
(if (empty? l1)
'()
(append (let loop ([n (car l1)] [l l2])
(if (empty? l) '() (cons (list n (car l)) (loop n (cdr l)))))
(cart (cdr l1) l2))))
;;; Count living cells in the neighbourhood
(define (n-count grid i j)
(- (apply + (2d-refs grid (cart (list (- i 1) i (+ i 1))
(list (- j 1) j (+ j 1)))))
(2d-ref grid i j)))
;;;
;;; Rules and updates of the grid
;;;
;;; rules are stored in a 2d array: r_i,j = new state of a cell
;;; in state i with j neighboors
(define conway-rules
(list->vector (list (list->vector '(0 0 0 1 0 0 0 0 0))
(list->vector '(0 0 1 1 0 0 0 0 0)))))
(define (next-state rules grid i j)
(let ([current (2d-ref grid i j)]
[N (n-count grid i j)])
(2d-ref rules current N)))
(define (next-grid rules grid)
(let ([new-grid (make-empty-grid (rows grid) (cols grid))])
(let loop ([i 0] [j 0])
(if (>= i (rows grid))
new-grid
(if (>= j (cols grid))
(loop (+ i 1) 0)
(begin (2d-set! new-grid i j (next-state rules grid i j))
(loop i (+ j 1))))))))
(define (next-grid! rules grid)
(let ([new-grid (next-grid rules grid)])
(let loop ((i 0))
(if (< i (rows grid))
(begin (vector-set! grid i (vector-ref new-grid i))
(loop (+ i 1)))
grid))))
;;;
;;; Image / Animation
;;;
(define (grid->image grid)
(let ([m (rows grid)] [n (cols grid)] [size 5])
(let loop ([img (rectangle (* m size) (* n size) "solid" "white")]
[i 0] [j 0])
(if (>= i (rows grid))
img
(if (>= j (cols grid))
(loop img (+ i 1) 0)
(if (= (2d-ref grid i j) 1)
(loop (underlay/xy img (* i (+ 1 size)) (* j (+ 1 size))
(square (- size 2) "solid" "black"))
i (+ j 1))
(loop img i (+ j 1))))))))
(define (game-of-life grid refresh_time)
(animate (lambda (n)
(if (= (modulo n refresh_time) 0)
(grid->image (next-grid! conway-rules grid))
(grid->image grid)))))
;;;
;;; Examples
;;;
(define (blinker)
(make-grid 3 3 '((0 1) (1 1) (2 1))))
(define (thunder)
(make-grid 70 50 '((30 19) (30 20) (30 21) (29 17) (30 17) (31 17))))
(define (cross)
(let loop ([i 0] [l '()])
(if (>= i 80)
(make-grid 80 80 l)
(loop (+ i 1) (cons (list i i) (cons (list (- 79 i) i) l))))))
;;; To run examples:
;;; (game-of-life (blinker) 30)
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Java | Java | if(s.equals("Hello World"))
{
foo();
}
else if(s.equals("Bye World"))
bar();//{}'s optional for one-liners
else
{
deusEx();
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Tcl | Tcl | proc commaQuibble {lst} {
return \{[join [lreplace $lst end-1 end [join [lrange $lst end-1 end] " and "]] ", "]\}
}
foreach input { {} {"ABC"} {"ABC" "DEF"} {"ABC" "DEF" "G" "H"} } {
puts [commaQuibble $input]
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #TXR | TXR | (defun quib (list)
(tree-bind (: last . lead) (reverse list)
`{@{(nreverse lead) ", "}@(if lead " and ")@last}`)) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lasso | Lasso | //This is a comment.
/* This is also a comment. */
/* A multi-line
comment */
/* ==========================
A multi-line
comment
=========================== */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #LaTeX | LaTeX | \documentclass{minimal}
\begin{document}
% This is a comment
\end{document} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Raku | Raku | class Automaton {
subset World of Str where {
.lines>>.chars.unique == 1 and m/^^<[.#\n]>+$$/
}
has Int ($.width, $.height);
has @.a;
multi method new (World $s) {
self.new:
:width(.pick.chars), :height(.elems),
:a( .map: { [ .comb ] } )
given $s.lines.cache;
}
method gist { join "\n", map { .join }, @!a }
method C (Int $r, Int $c --> Bool) {
@!a[$r % $!height][$c % $!width] eq '#';
}
method N (Int $r, Int $c --> Int) {
+grep ?*, map { self.C: |@$_ },
[ $r - 1, $c - 1], [ $r - 1, $c ], [ $r - 1, $c + 1],
[ $r , $c - 1], [ $r , $c + 1],
[ $r + 1, $c - 1], [ $r + 1, $c ], [ $r + 1, $c + 1];
}
method succ {
self.new: :$!width, :$!height,
:a(
gather for ^$.height -> $r {
take [
gather for ^$.width -> $c {
take
(self.C($r, $c) == 1 && self.N($r, $c) == 2|3)
|| (self.C($r, $c) == 0 && self.N($r, $c) == 3)
?? '#' !! '.'
}
]
}
)
}
}
my Automaton $glider .= new: q:to/EOF/;
............
............
............
.......###..
.###...#....
........#...
............
EOF
for ^10 {
say $glider++;
say '--';
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #JavaScript | JavaScript | if( s == "Hello World" ) {
foo();
} else if( s == "Bye World" ) {
bar();
} else {
deusEx();
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #UNIX_Shell | UNIX Shell | quibble() {
# Here awk(1) is easier than sed(1).
awk 'BEGIN {
for (i = 1; i < ARGC - 2; i++) s = s ARGV[i] ", "
i = ARGC - 2; if (i > 0) s = s ARGV[i] " and "
i = ARGC - 1; if (i > 0) s = s ARGV[i]
printf "{%s}\n", s
exit 0
}' "$@"
}
quibble
quibble ABC
quibble ABC DEF
quibble ABC DEF G H |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #VBA | VBA | Option Explicit
Sub Main()
Debug.Print Quibbling("")
Debug.Print Quibbling("ABC")
Debug.Print Quibbling("ABC, DEF")
Debug.Print Quibbling("ABC, DEF, G, H")
Debug.Print Quibbling("ABC, DEF, G, H, IJKLM, NO, PQRSTUV")
End Sub
Private Function Quibbling(MyString As String) As String
Dim s As String, n As Integer
s = "{" & MyString & "}": n = InStrRev(s, ",")
If n > 0 Then s = Left(s, n - 1) & " and " & Right(s, Len(s) - (n + 1))
Quibbling = s
End Function |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Liberty_BASIC | Liberty BASIC | 'This is a comment
REM This is a comment
print "This has a comment on the end of the line." 'This is a comment
print "This also has a comment on the end of the line." : REM This is a comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lily | Lily | # This is a single-line comment |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Red | Red | Red [
Purpose: "Conway's Game of Life"
Author: "Joe Smith"
]
neigh: [[0 1] [0 -1] [1 0] [-1 0] [1 1] [1 -1] [-1 1] [-1 -1]]
conway: function [petri] [
new-petri: copy/deep petri
repeat row length? petri [
repeat col length? petri [
live-neigh: 0
foreach cell neigh [
try [
if petri/(:row + cell/1)/(:col + cell/2) = 1 [live-neigh: live-neigh + 1]
]
]
switch petri/:row/:col [
1 [if any [live-neigh < 2 live-neigh > 3]
[new-petri/:row/:col: 0]
]
0 [if live-neigh = 3 [new-petri/:row/:col: 1]]
]]]
clear insert petri new-petri
]
*3-3: [
[0 1 0]
[0 1 0]
[0 1 0]
]
*8-8: [
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 1 1 1 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
]
display: function [table] [
foreach row table [
print replace/all (replace/all to-string row "0" "_") "1" "#"
] print ""
]
loop 5 [
display *3-3
conway *3-3
]
loop 23 [
display *8-8
conway *8-8
]
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #JCL | JCL | 0 : ok
4 : warning
8 : error
12 : severe error
16 : terminal error
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #VBScript | VBScript | Function Quibble(s)
arr = Split(s,",")
If s = "" Then
Quibble = "{}"
ElseIf UBound(arr) = 0 Then
Quibble = "{" & arr(0) & "}"
Else
Quibble = "{"
For i = 0 To UBound(arr)
If i = UBound(arr) - 1 Then
Quibble = Quibble & arr(i) & " and " & arr(i + 1) & "}"
Exit For
Else
Quibble = Quibble & arr(i) & ", "
End If
Next
End If
End Function
WScript.StdOut.Write Quibble("")
WScript.StdOut.WriteLine
WScript.StdOut.Write Quibble("ABC")
WScript.StdOut.WriteLine
WScript.StdOut.Write Quibble("ABC,DEF")
WScript.StdOut.WriteLine
WScript.StdOut.Write Quibble("ABC,DEF,G,H")
WScript.StdOut.WriteLine |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Visual_Basic_.NET | Visual Basic .NET | Option Explicit On
Option Infer On
Option Strict On
Module Program
Function FormatEnumerable(source As IEnumerable(Of String)) As String
Dim res As New Text.StringBuilder("{")
Using en = source.GetEnumerator()
Dim moreThanOne As Boolean = False
Dim nxt = If(en.MoveNext(), en.Current, String.Empty)
Do While en.MoveNext()
If moreThanOne Then res.Append(", ")
moreThanOne = True
res.Append(nxt)
nxt = en.Current
Loop
Dim lastItem = If(moreThanOne, " and ", "") & nxt
Return res.ToString() & lastItem & "}"
End Using
End Function
Function FormatArray(source As String()) As String
Select Case source.Length
Case 0 : Return "{}"
Case 1 : Return "{" & source(0) & "}"
Case Else : Return "{" & String.Join(", ", source.Take(source.Length - 1)) & " and " & source(source.Length - 1) & "}"
End Select
End Function
Sub Main()
Dim cases As String()() = {Array.Empty(Of String), New String() {"ABC"}, New String() {"ABC", "DEF"}, New String() {"ABC", "DEF", "G", "H"}}
For Each c In cases
Console.WriteLine(FormatArray(c))
Console.WriteLine(FormatEnumerable(c))
Next
End Sub
End Module
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lilypond | Lilypond | % This is a comment
%{ This is a comment
spanning several lines %} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Lingo | Lingo | -- This is a comment.
-- This is another comment |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Retro | Retro | :w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;
'World d:create
'.................... w/l
'.................... w/l
'.................... w/l
'..ooo............... w/l
'....o............... w/l
'...o................ w/l
'.................... w/l
'.................... w/l
'.................... w/l
'.................... w/l
'.................... w/l
'....ooo............. w/l
'.................... w/l
'.................... w/l
'.................... w/l
'........ooo......... w/l
'.......ooo.......... w/l
'.................... w/l
'.................... w/l
'.................... w/l
'Next d:create
#20 #20 * allot
{{
'Surrounding var
:get (rc-v)
dup-pair [ #0 #19 n:between?
] bi@ and
[ &World + [ #20 * ] dip + fetch ] [ drop-pair #0 ] choose ;
:neighbor? (rc-) get &Surrounding v:inc-by ;
:NW (rc-rc) dup-pair [ n:dec ] bi@ neighbor? ;
:NN (rc-rc) dup-pair [ n:dec ] dip neighbor? ;
:NE (rc-rc) dup-pair [ n:dec ] dip n:inc neighbor? ;
:WW (rc-rc) dup-pair n:dec neighbor? ;
:EE (rc-rc) dup-pair n:inc neighbor? ;
:SW (rc-rc) dup-pair [ n:inc ] dip n:dec neighbor? ;
:SS (rc-rc) dup-pair [ n:inc ] dip neighbor? ;
:SE (rc-rc) dup-pair [ n:inc ] bi@ neighbor? ;
:count (rc-rcn)
#0 !Surrounding NW NN NE
WW EE
SW SS SE @Surrounding ;
:alive (rc-n)
count #2 #3 n:between? [ #1 ] if; #0 ;
:dead (rc-n)
count #3 eq? [ #1 ] if; #0 ;
:new-state (rc-n)
dup-pair get #1 eq? &alive &dead choose ;
:set (nrc-) &Next + [ #20 * ] dip + store ;
:cols (r-)
#20 [ I over swap new-state rot rot set ] times<with-index> drop ;
:output (n-) n:-zero? [ $o ] [ $. ] choose c:put sp ;
---reveal---
:display (-)
nl &World #20 [ #20 [ fetch-next output ] times nl ] times drop ;
:gen (-)
#20 [ I cols ] times<with-index> &Next &World #20 #20 * copy ;
}}
{{
:divide #20 [ $- c:put ] times sp 'Gen:_ s:put dup n:put nl ;
---reveal---
:gens (n-) #0 swap [ display divide n:inc gen ] times drop ;
}}
#12 gens |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Jinja | Jinja |
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}
{%- endfor %}""").render())
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Vlang | Vlang | fn q(s []string) string {
match s.len {
0 {
return '{}'
}
1 {
return '{${s[0]}}'
}
2 {
return '{${s[0]} and ${s[1]}}'
}
else{
return '{${s[0..s.len-1].join(', ')} and ${s[s.len-1]}}'
}
}
}
fn main(){
println(q([]))
println(q(['ABC']))
println(q(['ABC','DEF']))
println(q(['ABC','DEF','G','H']))
} |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #Wren | Wren | var quibbling = Fn.new { |w|
var c = w.count
if (c == 0) return "{}"
if (c == 1) return "{%(w[0])}"
if (c == 2) return "{%(w[0]) and %(w[1])}"
return "{%(w[0..-2].join(", ")) and %(w[-1])}"
}
var words = [ [], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"] ]
for (w in words) System.print(quibbling.call(w)) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #LiveCode | LiveCode | -- comment may appear anywhere on line
// comment may appear anywhere on line
# comment may appear anywhere on line
/* this is a
block comment that
may span any number of lines */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Logo | Logo | ; comments come after a semicolon, and last until the end of the line |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #REXX | REXX | /*REXX program runs and displays the Conway's game of life, it stops after N repeats. */
signal on halt /*handle a cell growth interruptus. */
parse arg peeps '(' rows cols empty life! clearScreen repeats generations .
rows = p(rows 3) /*the maximum number of cell rows. */
cols = p(cols 3) /* " " " " " columns. */
emp = pickChar(empty 'blank') /*an empty cell character (glyph). */
clearScr = p(clearScreen 0) /* "1" indicates to clear the screen.*/
life! = pickChar(life! '☼') /*the gylph kinda looks like an amoeba.*/
reps = p(repeats 2) /*stop pgm if there are two repeats.*/
generations = p(generations 100) /*the number of generations allowed. */
sw= max(linesize() - 1, cols) /*usable screen width for the display. */
#reps= 0; $.= emp /*the universe is new, ··· and barren.*/
gens=abs(generations) /*used for a programming convenience.*/
x= space(peeps); upper x /*elide superfluous spaces; uppercase. */
if x=='' then x= "BLINKER" /*if nothing specified, use BLINKER. */
if x=='BLINKER' then x= "2,1 2,2 2,3"
if x=='OCTAGON' then x= "1,5 1,6 2,4 2,7 3,3 3,8 4,2 4,9 5,2 5,9 6,3 6,8 7,4 7,7 8,5 8,6"
call assign. /*assign the initial state of all cells*/
call showCells /*show the initial state of the cells.*/
do life=1 for gens; call assign@ /*construct next generation of cells.*/
if generations>0 | life==gens then call showCells /*should cells be displayed? */
end /*life*/ /* [↑] cell colony grows, lives, dies.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showCells: if clearScr then 'CLS' /* ◄─── change 'command' for your OS.*/
call showRows /*show the rows in the proper order. */
say right(copies('▒', sw) life, sw) /*show a fence between the generations.*/
if _=='' then exit /*if there's no life, then stop the run*/
if !._ then #reps= #reps + 1 /*we detected a repeated cell pattern. */
!._= 1 /*existence state and compare later. */
if reps\==0 & #reps<=reps then return /*so far, so good, regarding repeats.*/
say
say center('"Life" repeated itself' reps "times, simulation has ended.",sw,'▒')
exit /*stick a fork in it, we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$: parse arg _row,_col; return $._row._col==life!
assign$: do r=1 for rows; do c=1 for cols; $.r.c= @.r.c; end; end; return
assign.: do while x\==''; parse var x r "," c x; $.r.c=life!; rows=max(rows,r); cols=max(cols,c); end; life=0; !.=0; return
assign?: ?=$.r.c; n=neighbors(); if ?==emp then do;if n==3 then ?=life!; end; else if n<2 | n>3 then ?=emp; @.r.c=?; return
assign@: @.=emp; do r=1 for rows; do c=1 for cols; call assign?; end; end; call assign$; return
halt: say; say "REXX program (Conway's Life) halted."; say; exit 0
neighbors: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1)
p: return word(arg(1), 1)
pickChar: _=p(arg(1)); arg u .; if u=='BLANK' then _=" "; L=length(_); if L==3 then _=d2c(_); if L==2 then _=x2c(_); return _
showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T',emp); say z; _=_||z; end; return |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #jq | jq | if cond then f else g end |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #XBS | XBS | func task(a:array){
set x:string="";
foreach(k,v as a){
set out:string="";
if ((k==(?a-2))&((?a)>1)){out=" and "}elif(k!=(?a-1)){out=", "}
x+=v+out;del out;
}
send "{"+x+"}";
}
log(task([]));
log(task(["ABC"]));
log(task(["ABC","DEF"]));
log(task(["ABC","DEF","GHI"])); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.