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/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #CoffeeScript | CoffeeScript |
combinations = (n, p) ->
return [ [] ] if p == 0
i = 0
combos = []
combo = []
while combo.length < p
if i < n
combo.push i
i += 1
else
break if combo.length == 0
i = combo.pop() + 1
if combo.length == p
combos.push clone combo
i = combo.pop() + 1
combos
clone = (arr) -> (n for n in arr)
N = 5
for i in [0..N]
console.log "------ #{N} #{i}"
for combo in combinations N, i
console.log combo
|
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.
| #Modula-2 | Modula-2 | IF i = 1 THEN
InOut.WriteString('One')
ELSIF i = 2 THEN
InOut.WriteString('Two')
ELSIF i = 3 THEN
InOut.WriteString('Three')
ELSE
InOut.WriteString('Other')
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.)
| #PowerShell | PowerShell | # single-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.)
| #Processing | Processing | // a single-line comment
/* a multi-line
comment
*/
/*
* a multi-line comment
* with some decorative stars
*/
// comment out a code line
// println("foo");
// comment at the end of a line
println("foo bar"); // "baz" |
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "./dynamic" for Struct
import "./sort" for Sort
var QItem = Struct.create("QItem", ["color", "index"])
var ColorsUsed = []
class ColorQuantization {
construct new(filename, filename2) {
Window.title = "Color quantization"
_image = ImageData.loadFromFile(filename)
_w = _image.width
_h = _image.height
Window.resize(_w * 2 + 20, _h + 30)
Canvas.resize(_w * 2 + 20, _h + 30)
// draw original image on left half of canvas
_image.draw(0, 0)
Canvas.print(filename, _w/4, _h + 10, Color.white)
// create ImageData object for the quantized image
_qImage = ImageData.create(filename2, _w, _h)
_qFilename = filename2
}
init() {
// build the first bucket
var bucket = List.filled(_w * _h, null)
for (x in 0..._w) {
for (y in 0..._h) {
var idx = x * _w + y
bucket[idx] = QItem.new(_image.pget(x, y), idx)
}
}
var output = List.filled(_w * _h, Color.black)
// launch the quantization
medianCut(bucket, 4, output)
// load the result into the quantized ImageData object
for (x in 0..._w) {
for (y in 0..._h) {
_qImage.pset(x, y, output[x *_w + y])
}
}
// draw the quantized image on right half of canvas
_qImage.draw(_w + 20, 0)
Canvas.print(_qFilename, _w * 5/4 + 20, _h + 10, Color.white)
// save it to a file
_qImage.saveToFile(_qFilename)
// print colors used to terminal
System.print("The 16 colors used in R, G, B format are:")
for (c in ColorsUsed) {
System.print("(%(c.r), %(c.g), %(c.b))")
}
}
// apply the quantization to the colors in the bucket
quantize(bucket, output) {
// compute the mean value on each RGB component
var means = List.filled(3, 0)
for (q in bucket) {
var i = 0
for (val in [q.color.r, q.color.g, q.color.b]) {
means[i] = means[i] + val
i = i + 1
}
}
for (i in 0..2) {
means[i] = (means[i]/bucket.count).floor
}
var c = Color.rgb(means[0], means[1], means[2])
ColorsUsed.add(c)
// store the new color in the output list
for (q in bucket) output[q.index] = c
}
// apply the algorithm to the bucket of colors
medianCut(bucket, depth, output) {
if (depth == 0) { // terminated for this bucket, apply the quantization
quantize(bucket, output)
return
}
// compute the range of values for each RGB component
var minVal = [1000, 1000, 1000]
var maxVal = [-1, -1, -1]
for (q in bucket) {
var i = 0
for (val in [q.color.r, q.color.g, q.color.b]) {
if (val < minVal[i]) minVal[i] = val
if (val > maxVal[i]) maxVal[i] = val
i = i + 1
}
}
var valRange = [maxVal[0] - minVal[0], maxVal[1] - minVal[1], maxVal[2] - minVal[2]]
// find the RGB component with the greatest range
var greatest = 0
if (valRange[1] > valRange[0]) greatest = 1
if (valRange[2] > greatest) greatest = 2
// sort the quantization items according to the greatest
var cmp
if (greatest == 0) {
cmp = Fn.new { |i, j|
var t = (i.color.r - j.color.r).sign
if (t != 0) return t
return (i.index - j.index).sign
}
} else if (greatest == 1) {
cmp = Fn.new { |i, j|
var t = (i.color.g - j.color.g).sign
if (t != 0) return t
return (i.index - j.index).sign
}
} else {
cmp = Fn.new { |i, j|
var t = (i.color.b - j.color.b).sign
if (t != 0) return t
return (i.index - j.index).sign
}
}
Sort.quick(bucket, 0, bucket.count-1, cmp)
var medianIndex = ((bucket.count-1)/2).floor
medianCut(bucket[0...medianIndex], depth - 1, output)
medianCut(bucket[medianIndex..-1], depth - 1, output)
}
update() {}
draw(alpha) {}
}
var Game = ColorQuantization.new("Quantum_frog.png", "Quantum_frog_16.png") |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #AutoHotkey | AutoHotkey | #SingleInstance, Force
#NoEnv
SetBatchLines, -1
; Uncomment if Gdip.ahk is not in your standard library
;#Include, Gdip.ahk
; Start gdi+
If !pToken := Gdip_Startup()
{
message =
( LTrim
gdiplus error!, Gdiplus failed to start.
Please ensure you have gdiplus on your system.
)
MsgBox, 48, %message%
ExitApp
}
OnExit, Exit
; Set the width and height we want as our drawing area, to draw everything in.
; This will be the dimensions of our bitmap
Width := A_ScreenWidth, Height := A_ScreenHeight
; Create a layered window
; (+E0x80000 : must be used for UpdateLayeredWindow to work!)
; that is always on top (+AlwaysOnTop), has no taskbar entry or caption
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
; Show the window
Gui, 1: Show, NA
; Get a handle to this window we have created in order to update it later
hwnd1 := WinExist()
; Create a gdi bitmap with width and height of what we are going to
; draw into it. This is the entire drawing area for everything
hbm := CreateDIBSection(Width, Height)
; Get a device context compatible with the screen
hdc := CreateCompatibleDC()
; Select the bitmap into the device context
obm := SelectObject(hdc, hbm)
; Get a pointer to the graphics of the bitmap, for use with drawing functions
G := Gdip_GraphicsFromHDC(hdc)
; ARGB = Transparency, Red, Green, Blue
Colors := "0xFF000000,0xFFFF0000,0xFF00FF00,0xFF0000FF"
Colors .= ",0xFFFF00FF,0xFF00FFFF,0xFFFFFF00,0xFFFFFFFF"
; This list ^ is Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
StringSplit Colors, Colors, `,
w := Width // Colors0
Loop % Colors0
{
; Create a brush to draw a rectangle
pBrush := Gdip_BrushCreateSolid(Colors%A_Index%)
; Fill the graphics of the bitmap with a rectangle using the brush created
Gdip_FillRectangle(G, pBrush, w*(A_Index-1), 0, w, height)
; Delete the brush as it is no longer needed and wastes memory
Gdip_DeleteBrush(pBrush)
}
; Update the specified window we have created (hwnd1) with a handle to our
; bitmap (hdc), specifying the x,y,w,h we want it positioned on our screen
; So this will position our gui at (0,0) with the Width and
; Height specified earlier
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
; Select the object back into the hdc
SelectObject(hdc, obm)
; Now the bitmap may be deleted
DeleteObject(hbm)
; Also the device context related to the bitmap may be deleted
DeleteDC(hdc)
; The graphics may now be deleted
Gdip_DeleteGraphics(G)
Return
;#######################################################################
GuiEscape:
Exit:
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
ExitApp
Return |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Sidef | Sidef | require('GD')
func pinstripes(width = 1280, height = 720) {
var im = %O<GD::Image>.new(width, height)
var colors = [0, 255].variations_with_repetition(3)
var paintcolors = colors.shuffle.map {|rgb|
im.colorAllocate(rgb...)
}
var starty = 0
var barheight = height//4
for barwidth in (1..4) {
for (
var(startx = 0, colorindex = 0);
startx + barwidth <= width;
startx += barwidth
) {
im.filledRectangle(startx, starty, startx+barwidth,
starty + barheight - 1, paintcolors[colorindex++ % 8])
}
starty += barheight
}
return im
}
File('pinstripes.png').write(pinstripes().png, :raw) |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Common_Lisp | Common Lisp | (defun map-combinations (m n fn)
"Call fn with each m combination of the integers from 0 to n-1 as a list. The list may be destroyed after fn returns."
(let ((combination (make-list m)))
(labels ((up-from (low)
(let ((start (1- low)))
(lambda () (incf start))))
(mc (curr left needed comb-tail)
(cond
((zerop needed)
(funcall fn combination))
((= left needed)
(map-into comb-tail (up-from curr))
(funcall fn combination))
(t
(setf (first comb-tail) curr)
(mc (1+ curr) (1- left) (1- needed) (rest comb-tail))
(mc (1+ curr) (1- left) needed comb-tail)))))
(mc 0 n m combination)))) |
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.
| #Modula-3 | Modula-3 | IF Foo = TRUE THEN
Bar();
ELSE
Baz();
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.)
| #ProDOS | ProDOS | IGNORELINE your text here |
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.)
| #Prolog | Prolog | % this is a single-line comment that extends to the end of the line |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #AWK | AWK |
BEGIN {
nrcolors = 8
for (height=0; height<20; height++) {
for (width=0; width<nrcolors; width++) {
# print (ANSI) basic color and amount of spaces
printf("\033[%dm%*s", width + 40, 64 / nrcolors, " ")
}
# reset color and print newline
printf("\033[0m\n")
}
}
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #BASIC | BASIC | SCREEN 1,320,200,5,1
WINDOW 2,"Color bars",(0,10)-(297,186),15,1
FOR a=0 TO 300
LINE (a,0)-(a,186),(a+10)/10
NEXT
loop: GOTO loop |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #SmileBASIC | SmileBASIC | FOR I=1 TO 4
COLIDX=0
YTOP=(I-1)*60
FOR X=0 TO 399 STEP I
IF COLIDX MOD 8==0 THEN
RESTORE @COLOURS
ENDIF
READ R,G,B
GFILL X,YTOP,X+I,YTOP+59,RGB(R,G,B)
INC COLIDX
NEXT
NEXT
@COLOURS
DATA 0,0,0
DATA 255,0,0
DATA 0,255,0
DATA 0,0,255
DATA 255,0,255
DATA 0,255,255
DATA 255,255,0
DATA 255,255,255 |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Tcl | Tcl | package require Tcl 8.5
package require Tk 8.5
wm attributes . -fullscreen 1
pack [canvas .c -highlightthick 0] -fill both -expand 1
set colors {black red green blue magenta cyan yellow white}
set dy [expr {[winfo screenheight .c]/4}]
set y 0
foreach dx {1 2 3 4} {
for {set x 0} {$x < [winfo screenwidth .c]} {incr x $dx} {
.c create rectangle $x $y [expr {$x+$dx}] [expr {$y+$dy}] \
-fill [lindex $colors 0] -outline {}
set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]
}
incr y $dy
} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Crystal | Crystal |
def comb(m, n)
(0...n).to_a.each_combination(m) { |p| puts(p) }
end
|
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.
| #Monicelli | Monicelli |
che cosè var? # switch var
minore di 0: # case var < 0
...
maggiore di 0: # case var > 0
...
o tarapia tapioco: # else (none of the previous cases)
...
e velocità di esecuzione
|
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.)
| #PureBasic | PureBasic | ;comments come after an unquoted semicolon and last until the end of the line
foo = 5 ;This is a comment
c$ = ";This is not a comment" ;This is also 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.)
| #Python | Python | # This is a comment
foo = 5 # You can also append comments to statements |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Befunge | Befunge | <v%"P": <<*"(2"
v_:"P"/"["39*,, :55+/68v
v,,,";1H" ,+*86%+55 ,+*<
73654210v,,\,,,*93"[4m"<
>$:55+%#v_:1-"P"%55+/3g^
39*,,,~@>48*,1-:#v_$"m[" |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #C | C |
#include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK); //8 colour constants are defined
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch(); //waits for a key hit
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #True_BASIC | True BASIC | LET w = 640
LET h = 480
SET WINDOW 0, w, 0, h
LET h = h/4
LET y2 = h-1
FOR i = 1 TO 4
LET col = 0
LET y = (i-1)*h
FOR x = 1 TO w STEP i
IF remainder(col,15) = 0 THEN LET col = 0
SET COLOR col
BOX AREA x, x+i, y, y+h
LET col = col+1
NEXT x
NEXT i
END |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Visual_Basic_.NET | Visual Basic .NET | Public Class Main
Inherits System.Windows.Forms.Form
Public Sub New()
Me.FormBorderStyle = FormBorderStyle.None
Me.WindowState = FormWindowState.Maximized
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim Index As Integer
Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}
Dim Height = (Me.ClientSize.Height / 4) + 1
For y = 1 To 4
Dim Top = Me.ClientSize.Height / 4 * (y - 1)
For x = 0 To Me.ClientSize.Width Step y
If Index = 6 Then Index = 0 Else Index += 1
Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})
Next
Next
End Sub
End Class |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #D | D | T[][] comb(T)(in T[] arr, in int k) pure nothrow {
if (k == 0) return [[]];
typeof(return) result;
foreach (immutable i, immutable x; arr)
foreach (suffix; arr[i + 1 .. $].comb(k - 1))
result ~= x ~ suffix;
return result;
}
void main() {
import std.stdio;
[0, 1, 2, 3].comb(2).writeln;
} |
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.
| #Morfa | Morfa |
if(s == "Hello World")
{
foo();
}
else if(s == "Bye World")
bar();
else
{
baz();
}
|
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.)
| #Quackery | Quackery |
( The word "(" is a compiler directive (a builder,
in Quackery jargon) that causes the compiler to
disregard everything until it encounters a ")"
preceded by whitespace.
If you require more than that, it is trivial to
define new comment builders... )
[ behead carriage = until ] builds #
# Now the word "#" will cause the compiler to
# disregard everything from the "#" to the end of
# the line that it occurs on.
[ drop $ "" ] builds commentary
commentary
The word "commentary" will cause the compiler to
disregard everything that comes after it to the
end of the source string or file. |
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.)
| #QB64 | QB64 | REM This is a remark...
' This is also a remark...
IF a = 0 THEN REM (REM follows syntax rules)
IF a = 0 THEN '(apostrophe doesn't follow syntax rules, so use END IF after this)
END IF
'Metacommands such as $DYNAMIC and $INCLUDE use the REM (or apostrophe).
REM $STATIC 'arrays cannot be resized once dimensioned.
REM $DYNAMIC 'enables resizing of array dimensions with REDIM.
REM $INCLUDE: 'loads a reference file or library. |
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.)
| #R | R | # end of line comment |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #C.2B.2B | C++ | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. terminal-colour-bars.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 width PIC 9(3).
01 height PIC 9(3).
01 interval PIC 9(3).
01 colours-area.
03 colour-values.
05 FILLER PIC 9 VALUE 0. *> Black
05 FILLER PIC 9 VALUE 4. *> Red
05 FILLER PIC 9 VALUE 2. *> Green
05 FILLER PIC 9 VALUE 1. *> Blue
05 FILLER PIC 9 VALUE 5. *> Magneta
05 FILLER PIC 9 VALUE 3. *> Cyan
05 FILLER PIC 9 VALUE 6. *> Yellow
05 FILLER PIC 9 VALUE 7. *> White
03 colour-table REDEFINES colour-values.
05 colours PIC 9 OCCURS 8 TIMES INDEXED BY colour-index.
01 i PIC 9(3).
01 j PIC 9(3).
PROCEDURE DIVISION.
ACCEPT width FROM COLUMNS
ACCEPT height FROM LINES
DIVIDE width BY 8 GIVING interval
PERFORM VARYING i FROM 1 BY 1 UNTIL height < i
PERFORM VARYING j FROM 1 BY 1 UNTIL width < j
COMPUTE colour-index = (j / interval) + 1
IF 8 < colour-index
SET colour-index TO 8
END-IF
*> Some colours come a bit darker than they
*> should, with the yellow being orange and the white
*> being light-grey.
DISPLAY SPACE AT LINE i COLUMN j
WITH BACKGROUND-COLOR colours (colour-index)
END-PERFORM
END-PERFORM
ACCEPT i *> Prevent ncurses returning to console immediately.
GOBACK
. |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
class Game {
static init() {
Window.title = "Color pinstripe"
__width = 900
__height = 600
Canvas.resize(__width, __height)
Window.resize(__width, __height)
var colors = [
Color.hex("000000"), // black
Color.hex("FF0000"), // red
Color.hex("00FF00"), // green
Color.hex("0000FF"), // blue
Color.hex("FF00FF"), // magenta
Color.hex("00FFFF"), // cyan
Color.hex("FFFF00"), // yellow
Color.hex("FFFFFF") // white
]
pinstripe(colors)
}
static pinstripe(colors) {
var w = __width
var h = (__height/4).floor
for (b in 1..4) {
var x = 0
var ci = 0
while (x < w) {
var y = h * (b - 1)
Canvas.rectfill(x, y, b, h, colors[ci%8])
x = x + b
ci = ci + 1
}
}
}
static update() {}
static draw(dt) {}
} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Delphi | Delphi | def combinations(m, range) {
return if (m <=> 0) { [[]] } else {
def combGenerator {
to iterate(f) {
for i in range {
for suffix in combinations(m.previous(), range & (int > i)) {
f(null, [i] + suffix)
}
}
}
}
}
} |
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.
| #MUMPS | MUMPS | IF A list-of-MUMPS-commands |
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.)
| #Racket | Racket |
; this is a to-end-of-line coment
#| balanced comment, #| can be nested |# |#
#;(this expression is ignored)
#; ; the following expression is commented because of the #; in the beginning
(ignored)
|
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.)
| #Raku | Raku | # the answer to everything
my $x = 42; |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Common_Lisp | Common Lisp | (defun color-bars ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dotimes (i (height scr))
(move scr i 0)
(dolist (color '(:red :green :yellow :blue :magenta :cyan :white :black))
(add-char scr #\space :bgcolor color :n (floor (/ (width scr) 8)))))
(refresh scr)
;; wait for keypress
(get-char scr))) |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #XPL0 | XPL0 | code ChIn=7, Point=41, SetVid=45;
int X, Y, W, C;
[SetVid($13); \set 320x200 graphics mode in 256 colors
for Y:= 0 to 200-1 do \for all the scan lines...
[W:= Y/50 + 1; \width of stripe = 1, 2, 3, 4
C:= 0; \set color to black so first pixel becomes blue
for X:= 0 to 320-1 do \for all the pixels on a scan line...
[if rem(X/W) = 0 then C:= C+1; \cycle through all system colors
Point(X, Y, C); \set pixel at X,Y to color C
];
];
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode display
] |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Yabasic | Yabasic | w = 640 : h = 480
open window w, h
h4 = h/4
FOR I=1 TO 4
COLIDX=0
YTOP=(I-1)*h4
FOR X=1 TO w STEP I
IF mod(COLIDX, 8) = 0 RESTORE COLOURS
READ R,G,B
color R, G, B
fill rectangle X,YTOP,X+I,YTOP+h4
COLIDX = COLIDX + 1
NEXT
NEXT
label COLOURS
DATA 0,0,0
DATA 255,0,0
DATA 0,255,0
DATA 0,0,255
DATA 255,0,255
DATA 0,255,255
DATA 255,255,0
DATA 255,255,255
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #11l | 11l | [(() -> Int)] funcs
L(i) 10
funcs.append(() -> @=i * @=i)
print(funcs[3]()) |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #E | E | def combinations(m, range) {
return if (m <=> 0) { [[]] } else {
def combGenerator {
to iterate(f) {
for i in range {
for suffix in combinations(m.previous(), range & (int > i)) {
f(null, [i] + suffix)
}
}
}
}
}
} |
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.
| #Nanoquery | Nanoquery | if x = 0
foo()
else if x = 1
bar()
else if x = 2
baz()
else
boz()
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.)
| #Raven | Raven | # 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.)
| #REBOL | REBOL |
; This is a line comment.
{ Multi-line strings can
be used as comments
if you like }
|
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.)
| #Relation | Relation |
// This is a valid comment
// A space is needed after the double slash
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Delphi | Delphi |
unit Colour_barsDisplay;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms;
type
TfmColourBar = class(TForm)
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmColourBar: TfmColourBar;
Colors: array of TColor = [clblack, clred, clgreen, clblue, clFuchsia, clAqua,
clyellow, clwhite];
implementation
{$R *.dfm}
procedure TfmColourBar.FormPaint(Sender: TObject);
var
w, h, i: Integer;
r: TRect;
begin
w := ClientWidth div length(Colors);
h := ClientHeight;
r := Rect(0, 0, w, h);
with Canvas do
for i := 0 to High(Colors) do
begin
Brush.Color := Colors[i];
FillRect(r);
r.Offset(w, 0);
end;
end;
procedure TfmColourBar.FormResize(Sender: TObject);
begin
Invalidate;
end;
end. |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Ada | Ada | with Ada.Text_IO;
procedure Value_Capture is
protected type Fun is -- declaration of the type of a protected object
entry Init(Index: Natural);
function Result return Natural;
private
N: Natural := 0;
end Fun;
protected body Fun is -- the implementation of a protected object
entry Init(Index: Natural) when N=0 is
begin -- after N has been set to a nonzero value, it cannot be changed any more
N := Index;
end Init;
function Result return Natural is (N*N);
end Fun;
A: array (1 .. 10) of Fun; -- an array holding 10 protected objects
begin
for I in A'Range loop -- initialize the protected objects
A(I).Init(I);
end loop;
for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last
Ada.Text_IO.Put(Integer'Image(A(I).Result));
end loop;
end Value_Capture; |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #EasyLang | EasyLang | n = 5
m = 3
len result[] m
#
func combinations pos val . .
if pos < m
for i = val to n - m
result[pos] = pos + i
call combinations pos + 1 i
.
else
print result[]
.
.
call combinations 0 0 |
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.
| #Nemerle | Nemerle | if (the_answer == 42) FindQuestion() else Foo();
when (stock.price < buy_order) stock.Buy();
unless (text < "") Write(text); |
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.)
| #Retro | Retro | ( comments are placed between parentheses. A space must follow the opening parenthesis. ) |
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.)
| #REXX | REXX | /*REXX program that demonstrates what happens when dividing by zero. */
y=7
say 44 / (7-y) /* divide by some strange thingy.*/ |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #EasyLang | EasyLang | col[] = [ 000 900 090 909 099 990 999 ]
w = 100.0 / len col[]
for i range len col[]
color col[i]
move w * i 0
rect w 100
. |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Factor | Factor | USING: accessors colors.constants kernel math sequences ui
ui.gadgets ui.gadgets.tracks ui.pens.solid ;
IN: rosetta-code.colour-bars-display
: colors ( -- ) [
horizontal <track>
{
COLOR: black
COLOR: red
COLOR: green
COLOR: blue
COLOR: magenta
COLOR: cyan
COLOR: yellow
COLOR: white
}
[ <solid> gadget new swap >>interior ] map
dup length recip
[ track-add ] curry each
{ 640 480 } >>pref-dim
"bars" open-window
] with-ui ;
MAIN: colors |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Forth | Forth |
\ Color Bars for TI-99 CAMEL99 Forth
NEEDS HCHAR FROM DSK1.GRAFIX \ TMS9918 control lexicon
NEEDS CHARSET FROM DSK1.CHARSET \ restores default character data
NEEDS ENUM FROM DSK1.ENUM \ add simple enumerator to Forth
\ Name TI-99 colors
1 ENUM CLR ENUM BLK ENUM MGRN ENUM LGRN
ENUM BLU ENUM LBLU ENUM RED ENUM CYAN
ENUM MRED ENUM LRED ENUM YEL ENUM LYEL
ENUM GRN ENUM MAG ENUM GRY ENUM WHT
DROP
\ square character data
HEX
CREATE SQUARE FFFF , FFFF , FFFF , FFFF ,
DECIMAL
: COLOR-BARS ( -- )
24 0 DO
\ col row char wid
\ --- --- ---- ---
2 I 88 4 HCHAR
6 I 96 4 HCHAR
10 I 104 4 HCHAR
14 I 112 4 HCHAR
18 I 120 4 HCHAR
22 I 128 4 HCHAR
26 I 136 4 HCHAR
LOOP ;
DECIMAL
: DEFCHARS ( pattern first last -- )
1+ SWAP ?DO DUP I CHARDEF 8 +LOOP DROP ;
: SET-COLORS ( -- )
\ charset fg bg
\ ------- -- --
88 SET# GRY CLR COLOR
96 SET# YEL CLR COLOR
104 SET# CYAN CLR COLOR
112 SET# GRN CLR COLOR
120 SET# MAG CLR COLOR
128 SET# RED CLR COLOR
136 SET# BLU CLR COLOR
144 SET# BLK CLR COLOR ;
\ restore characters and colors
: DEFAULTS
8 SCREEN
4 19 BLK CLR COLORS
CLEAR
CHARSET ;
: BARS
CLEAR BLK SCREEN
SET-COLORS
SQUARE 88 152 DEFCHARS
COLOR-BARS
BEGIN ?TERMINAL UNTIL
DEFAULTS
;
CR .( Done. Type BARS to run)
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #ALGOL_68 | ALGOL 68 |
[1:10]PROC(BOOL)INT squares;
FOR i FROM 1 TO 10 DO
HEAP INT captured i := i;
squares[i] := ((REF INT by ref i, INT by val i,BOOL b)INT:(INT i = by ref i; (b|by ref i := 0); by val i*i))
(captured i, captured i,)
OD;
FOR i FROM 1 TO 8 DO print(squares[i](i MOD 2 = 0)) OD;
print(new line);
FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #EchoLisp | EchoLisp |
;;
;; using the native (combinations) function
(lib 'list)
(combinations (iota 5) 3)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))
;;
;; using an iterator
;;
(lib 'sequences)
(take (combinator (iota 5) 3) #:all)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))
;;
;; defining a function
;;
(define (combine lst p) (cond
[(null? lst) null]
[(< (length lst) p) null]
[(= (length lst) p) (list lst)]
[(= p 1) (map list lst)]
[else (append
(map cons (circular-list (first lst)) (combine (rest lst) (1- p)))
(combine (rest lst) p))]))
(combine (iota 5) 3)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))
|
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.
| #NetRexx | NetRexx | -- simple construct
if logicalCondition then conditionWasTrue()
else conditionWasFalse()
-- multi-line is ok too
if logicalCondition
then
conditionWasTrue()
else
conditionWasFalse()
-- using block stuctures
if logicalCondition then do
conditionWasTrue()
...
end
else do
conditionWasFalse()
...
end
-- if/else if...
if logicalCondition1 then do
condition1WasTrue()
...
end
else if logicalCondition2 then do
condition2WasTrue()
...
end
else do
conditionsWereFalse()
...
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.)
| #Ring | Ring |
//this is a single line comment
#this also a single 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.)
| #RLaB | RLaB |
x = "code" # I am a comment
x = "code" // Here I comment thee
# matlab-like document line
// C++ like document line
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Draw the color bars on an 80 x 25 console using the system palette of 16 colors
' i.e. 5 columns per color
Width 80, 25
Shell "cls"
Locate ,, 0 '' turn cursor off
For clr As UInteger = 0 To 15
Color 0, clr
For row As Integer = 1 to 25
Locate row, clr * 5 + 1
Print Space(5);
Next row
Next clr
Sleep
' restore default settings
Locate ,, 1 '' turn cursor on
Color 7, 0 '' white text on black background |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Gambas | Gambas | Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]
Dim hPanel As Panel
Dim siCount As Short
With Me
.Arrangement = Arrange.Horizontal
.Height = 300
.Width = 400
End With
For siCount = 0 To 6
hpanel = New Panel(Me)
hpanel.Expand = True
hpanel.H = 500
HPanel.Background = iColour[siCount]
Next
End |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #AntLang | AntLang | fns: {n: x; {n expt 2}} map range[10]
(8 elem fns)[] |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #AppleScript | AppleScript | on run
set fns to {}
repeat with i from 1 to 10
set end of fns to closure(i)
end repeat
|λ|() of item 3 of fns
end run
on closure(x)
script
on |λ|()
x * x
end |λ|
end script
end closure |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Egison | Egison |
(define $comb
(lambda [$n $xs]
(match-all xs (list integer)
[(loop $i [1 ,n] <join _ <cons $a_i ...>> _) a])))
(test (comb 3 (between 0 4)))
|
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.
| #newLISP | newLISP | (set 'x 1)
(if (= x 1) (println "is 1")) |
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.)
| #Robotic | Robotic |
. "This is a comment line"
. "Print Hello world"
* "Hello world."
. "This is the only way to comment a line in Robotic"
|
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.)
| #Ruby | Ruby | x = "code" # I am a comment
=begin hello
I a POD documentation comment like Perl
=end puts "code" |
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.)
| #Run_BASIC | Run BASIC | 'This is a comment
REM This is a comment
print "Notice comment at the end of the line." 'This is a comment
print "Also notice this comment at the end of the line." : REM This is a comment
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Go | Go | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000", // black
"FF0000", // red
"00FF00", // green
"0000FF", // blue
"FF00FF", // magenta
"00FFFF", // cyan
"FFFF00", // yellow
"FFFFFF", // white
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
} |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Haskell | Haskell | #!/usr/bin/env stack
-- stack --resolver lts-7.0 --install-ghc runghc --package vty -- -threaded
import Graphics.Vty
colorBars :: Int -> [(Int, Attr)] -> Image
colorBars h bars = horizCat $ map colorBar bars
where colorBar (w, attr) = charFill attr ' ' w h
barWidths :: Int -> Int -> [Int]
barWidths nBars totalWidth = map barWidth [0..nBars-1]
where fracWidth = fromIntegral totalWidth / fromIntegral nBars
barWidth n =
let n' = fromIntegral n :: Double
in floor ((n' + 1) * fracWidth) - floor (n' * fracWidth)
barImage :: Int -> Int -> Image
barImage w h = colorBars h $ zip (barWidths nBars w) attrs
where attrs = map color2attr colors
nBars = length colors
colors = [black, brightRed, brightGreen, brightMagenta, brightCyan, brightYellow, brightWhite]
color2attr c = Attr Default Default (SetTo c)
main = do
cfg <- standardIOConfig
vty <- mkVty cfg
let output = outputIface vty
bounds <- displayBounds output
let showBars (w,h) = do
let img = barImage w h
pic = picForImage img
update vty pic
e <- nextEvent vty
case e of
EvResize w' h' -> showBars (w',h')
_ -> return ()
showBars bounds
shutdown vty |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Axiom | Axiom | )abbrev package TESTP TestPackage
TestPackage() : with
test: () -> List((()->Integer))
== add
test() == [(() +-> i^2) for i in 1..10] |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Babel | Babel | ((main {
{ iter
1 take bons 1 take
dup cp
{*} cp
3 take
append }
10 times
collect !
{eval %d nl <<} each })) |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #ALGOL_68 | ALGOL 68 | BEGIN # find circular primes - primes where all cyclic permutations #
# of the digits are also prime #
# genertes a sieve of circular primes, only the first #
# permutation of each prime is flagged as TRUE #
OP CIRCULARPRIMESIEVE = ( INT n )[]BOOL:
BEGIN
[ 0 : n ]BOOL prime;
prime[ 0 ] := prime[ 1 ] := FALSE;
prime[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
IF prime[ i ] THEN
FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD
FI
OD;
INT first digit multiplier := 10;
INT max with multiplier := 99;
# the 1 digit primes are non-curcular, so start at 10 #
FOR i FROM 10 TO UPB prime DO
IF i > max with multiplier THEN
# starting a new power of ten #
first digit multiplier *:= 10;
max with multiplier *:= 10 +:= 9
FI;
IF prime[ i ] THEN
# have a prime #
# cycically permute the number until we get back #
# to the original - flag all the permutations #
# except the original as non-prime #
INT permutation := i;
WHILE permutation := ( permutation OVER 10 )
+ ( ( permutation MOD 10 ) * first digit multiplier )
;
permutation /= i
DO
IF NOT prime[ permutation ] THEN
# the permutation is not prime #
prime[ i ] := FALSE
ELIF permutation > i THEN
# haven't permutated e.g. 101 to 11 #
IF NOT prime[ permutation ] THEN
# i is not a circular prime #
prime[ i ] := FALSE
FI;
prime[ permutation ] := FALSE
FI
OD
FI
OD;
prime
END # CIRCULARPRIMESIEVE # ;
# construct a sieve of circular primes up to 999 999 #
# only the first permutation is included #
[]BOOL prime = CIRCULARPRIMESIEVE 999 999;
# print the first 19 circular primes #
INT c count := 0;
print( ( "First 19 circular primes: " ) );
FOR i WHILE c count < 19 DO
IF prime[ i ] THEN
print( ( " ", whole( i, 0 ) ) );
c count +:= 1
FI
OD;
print( ( newline ) )
END |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Eiffel | Eiffel |
class
COMBINATIONS
create
make
feature
make (n, k: INTEGER)
require
n_positive: n > 0
k_positive: k > 0
k_smaller_equal: k <= n
do
create set.make
set.extend ("")
create sol.make
sol := solve (set, k, n - k)
sol := convert_solution (n, sol)
ensure
correct_num_of_sol: num_of_comb (n, k) = sol.count
end
sol: LINKED_LIST [STRING]
feature {None}
set: LINKED_LIST [STRING]
convert_solution (n: INTEGER; solution: LINKED_LIST [STRING]): LINKED_LIST [STRING]
-- strings of 'k' digits between 1 and 'n'
local
i, j: INTEGER
temp: STRING
do
create temp.make (n)
from
i := 1
until
i > solution.count
loop
from
j := 1
until
j > n
loop
if solution [i].at (j) = '1' then
temp.append (j.out)
end
j := j + 1
end
solution [i].deep_copy (temp)
temp.wipe_out
i := i + 1
end
Result := solution
end
solve (seta: LINKED_LIST [STRING]; one, zero: INTEGER): LINKED_LIST [STRING]
-- list of strings with a number of 'one' 1s and 'zero' 0, standig for wether the corresponing digit is taken or not.
local
new_P1, new_P0: LINKED_LIST [STRING]
do
create new_P1.make
create new_P0.make
if one > 0 then
new_P1.deep_copy (seta)
across
new_P1 as P1
loop
new_P1.item.append ("1")
end
new_P1 := solve (new_P1, one - 1, zero)
end
if zero > 0 then
new_P0.deep_copy (seta)
across
new_P0 as P0
loop
new_P0.item.append ("0")
end
new_P0 := solve (new_P0, one, zero - 1)
end
if one = 0 and zero = 0 then
Result := seta
else
create Result.make
Result.fill (new_p0)
Result.fill (new_p1)
end
end
num_of_comb (n, k: INTEGER): INTEGER
-- number of 'k' sized combinations out of 'n'.
local
upper, lower, m, l: INTEGER
do
upper := 1
lower := 1
m := n
l := k
from
until
m < n - k + 1
loop
upper := m * upper
lower := l * lower
m := m - 1
l := l - 1
end
Result := upper // lower
end
end
|
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.
| #Nim | Nim | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz() |
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.)
| #Rust | Rust | // A single line comment
/*
This is a multi-line (aka block) comment
/*
containing nested multi-line comment
(nesting supported since 0.9-pre https://github.com/mozilla/rust/issues/9468)
*/
*/
/// Outer single line Rustdoc comments apply to the next item.
/**
Outer multi-line Rustdoc comments.
* Leading asterisk (*) in multi-line Rustdoc comments
* is not considered to be part of the comment text,
* blanks and tabs preceding the initial asterisk (*) are also stripped.
*/
fn example() {
//! Inner single line Rustdoc comments apply to their enclosing item.
/*!
Inner multi-line Rustdoc comments.
See also https://github.com/mozilla/rust/wiki/Doc-using-rustdoc
*/
}
#[doc = "Unsugared outer Rustdoc comments.
(outer attributes are not terminated by a semi-colon)"]
fn example() {
#[doc = "Unsugared inner Rustdoc comments.
(inner attributes are terminated by a semi-colon)
See also https://github.com/mozilla/rust/blob/master/doc/rust.md#attributes"];
} |
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.)
| #SAS | SAS | /* comment */
*another comment;
* both
may
be
multiline; |
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.)
| #Sather | Sather | -- a single line comment |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Icon_and_Unicon | Icon and Unicon | link graphics,printf
procedure main() # generalized colour bars
DrawTestCard(Simple_TestCard())
WDone()
end
procedure DrawTestCard(TC)
size := sprintf("size=%d,%d",TC.width,TC.height)
&window := TC.window := open(TC.id,"g","bg=black",size) |
stop("Unable to open window")
every R := TC.bands[r := 1 to *TC.bands -1] do
every C := R.bars[c := 1 to *R.bars - 1] do {
Fg(R.bars[c].colour)
FillRectangle( C.left, R.top,
R.bars[c+1].left-C.left, TC.bands[r+1].top-R.top )
}
return TC
end
record testcard(window,id,width,height,bands)
record band(top,bars)
record bar(left,colour)
procedure Simple_TestCard() #: return structure simple testcard
return testcard(,"Simple Test Card",width := 800,height := 600,
[ band( 1, [ bar( 1, "black"),
bar(114, "red"),
bar(228, "green"),
bar(342, "blue"),
bar(456, "magenta"),
bar(570, "cyan"),
bar(684, "yellow"),
bar(width) ] ),
band(height) ])
end |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #Bracmat | Bracmat | ( -1:?i
& :?funcs
& whl
' ( 1+!i:<10:?i
& !funcs ()'(.$i^2):?funcs
)
& whl'(!funcs:%?func %?funcs&out$(!func$))
);
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
typedef int (*f_int)();
#define TAG 0xdeadbeef
int _tmpl() {
volatile int x = TAG;
return x * x;
}
#define PROT (PROT_EXEC | PROT_WRITE)
#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
f_int dupf(int v)
{
size_t len = (void*)dupf - (void*)_tmpl;
f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
char *p;
if(ret == MAP_FAILED) {
perror("mmap");
exit(-1);
}
memcpy(ret, _tmpl, len);
for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
if (*(int *)p == TAG) *(int *)p = v;
return ret;
}
int main()
{
f_int funcs[10];
int i;
for (i = 0; i < 10; i++) funcs[i] = dupf(i);
for (i = 0; i < 9; i++)
printf("func[%d]: %d\n", i, funcs[i]());
return 0;
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #ALGOL_W | ALGOL W | begin % find circular primes - primes where all cyclic permutations %
% of the digits are also prime %
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
begin
p( 1 ) := false; p( 2 ) := true;
for i := 3 step 2 until n do p( i ) := true;
for i := 4 step 2 until n do p( i ) := false;
for i := 3 step 2 until truncate( sqrt( n ) ) do begin
integer ii; ii := i + i;
if p( i ) then for pr := i * i step ii until n do p( pr ) := false
end for_i ;
end Eratosthenes ;
% find circular primes in p in the range lo to hi, if they are circular, flag the %
% permutations as non-prime so we do not consider them again %
% non-circular primes are also flageed as non-prime %
% lo must be a power of ten and hi must be at most ( lo * 10 ) - 1 %
procedure keepCircular ( logical array p ( * ); integer value lo, hi ) ;
for n := lo until hi do begin
if p( n ) then begin
% have a prime %
integer c, pCount;
logical isCircular;
integer array permutations ( 1 :: 10 );
c := n;
isCircular := true;
pCount := 0;
% cyclically permute c until we get back to p or find a non-prime value for c %
while begin
integer first, rest;
first := c div lo;
rest := c rem lo;
c := ( rest * 10 ) + first;
isCircular := p( c );
c not = n and isCircular
end do begin
pCount := pCount + 1;
permutations( pCount ) := c
end while_have_another_prime_permutation ;
if not isCircular
then p( n ) := false
else begin
% have a circular prime - flag the permutations as non-prime %
for i := 1 until pCount do p( permutations( i ) ) := false
end if_not_isCircular__
end if_p_n
end keepCircular ;
integer cCount;
% sieve the primes up to 999999 %
logical array p ( 1 :: 999999 );
Eratosthenes( p, 999999 );
% remove non-circular primes from the sieve %
% the single digit primes are all circular so we start at 10 %
keepCircular( p, 10, 99 );
keepCircular( p, 100, 999 );
keepCircular( p, 1000, 9999 );
keepCircular( p, 10000, 99999 );
keepCircular( p, 100000, 200000 );
% print the first 19 circular primes %
cCount := 0;
write( "First 19 circular primes: " );
for i := 1 until 200000 do begin
if p( i ) then begin
writeon( i_w := 1, s_w := 1, i );
cCount := cCount + 1;
if cCount = 19 then goto end_circular
end if_p_i
end for_i ;
end_circular:
end. |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #Arturo | Arturo | perms: function [n][
str: repeat to :string n 2
result: new []
lim: dec size digits n
loop 0..lim 'd ->
'result ++ slice str d lim+d
return to [:integer] result
]
circulars: new []
circular?: function [x][
if not? prime? x -> return false
loop perms x 'y [
if not? prime? y -> return false
if contains? circulars y -> return false
]
'circulars ++ x
return true
]
i: 2
found: 0
while [found < 19][
if circular? i [
print i
found: found + 1
]
i: i + 1
] |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #11l | 11l | dc.l TrapString_Bus
dc.l TrapString_Addr
dc.l TrapString_Illegal
dc.l TrapString_Div0
dc.l TrapString_chk
dc.l TrapString_v
dc.l TrapString_priv
dc.l TrapString_trace
TrapString_Bus:
dc.b "Bus error",255
even
TrapString_Addr:
dc.b "Address error",255
even
TrapString_Illegal:
dc.b "Illegal Instruction",255
even
TrapString_Div0:
dc.b "Divide By Zero",255
even
TrapString_chk:
dc.b "CHK Failure",255
even
TrapString_v:
dc.b "Signed Overflow",255
even
TrapString_priv:
dc.b "Privilege Violation",255
even
TrapString_trace:
dc.b "Tracing",255
even |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Elena | Elena | import system'routines;
import extensions;
import extensions'routines;
const int M = 3;
const int N = 5;
Numbers(n)
{
^ Array.allocate(n).populate:(int n => n)
}
public program()
{
var numbers := Numbers(N);
Combinator.new(M, numbers).forEach:(row)
{
console.printLine(row.toString())
};
console.readChar()
} |
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.
| #Objeck | Objeck |
a := GetValue();
if(a < 5) {
"less than 5"->PrintLine();
}
else if(a > 5) {
"greater than 5"->PrintLine();
}
else {
"equal to 5"->PrintLine();
};
|
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.)
| #Scala | Scala | // A single 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.)
| #Scheme | Scheme | ; Basically the same as Common Lisp
; While R5RS does not provide block comments, they are defined in SRFI-30, as in Common Lisp :
#| comment
... #| nested comment
... |#
|#
; See http://srfi.schemers.org/srfi-30/srfi-30.html
|
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.)
| #Scilab | Scilab | // this is a comment
i=i+1 // this is a comment |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #J | J | load 'viewmat'
size=: 2{.".wd'qm' NB. J6
size=: getscreenwh_jgtk_ '' NB. J7
'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8 |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Java | Java |
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorFrame extends JFrame {
public ColorFrame(int width, int height) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(width, height);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.CYAN, Color.yellow, Color.white };
for (int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
/ colors.length, this.getHeight());
}
}
public static void main(String args[]) {
new ColorFrame(200, 200);
}
}
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Goal
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: Multiple distinct objects
| #C.23 | C# | using System;
using System.Linq;
class Program
{
static void Main()
{
var captor = (Func<int, Func<int>>)(number => () => number * number);
var functions = Enumerable.Range(0, 10).Select(captor);
foreach (var function in functions.Take(9))
{
Console.WriteLine(function());
}
}
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not.
A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1.
For example:
R(2) = 11 and R(5) = 11111 are repunits.
Task
Find the first 19 circular primes.
If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.
(Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.
See also
Wikipedia article - Circular primes.
Wikipedia article - Repunit.
OEIS sequence A016114 - Circular primes.
| #AWK | AWK |
# syntax: GAWK -f CIRCULAR_PRIMES.AWK
BEGIN {
p = 2
printf("first 19 circular primes:")
for (count=0; count<19; p++) {
if (is_circular_prime(p)) {
printf(" %d",p)
count++
}
}
printf("\n")
exit(0)
}
function cycle(n, m,p) { # E.G. if n = 1234 returns 2341
m = n
p = 1
while (m >= 10) {
p *= 10
m /= 10
}
return int(m+10*(n%p))
}
function is_circular_prime(p, p2) {
if (!is_prime(p)) {
return(0)
}
p2 = cycle(p)
while (p2 != p) {
if (p2 < p || !is_prime(p2)) {
return(0)
}
p2 = cycle(p2)
}
return(1)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a few values to it.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #68000_Assembly | 68000 Assembly | dc.l TrapString_Bus
dc.l TrapString_Addr
dc.l TrapString_Illegal
dc.l TrapString_Div0
dc.l TrapString_chk
dc.l TrapString_v
dc.l TrapString_priv
dc.l TrapString_trace
TrapString_Bus:
dc.b "Bus error",255
even
TrapString_Addr:
dc.b "Address error",255
even
TrapString_Illegal:
dc.b "Illegal Instruction",255
even
TrapString_Div0:
dc.b "Divide By Zero",255
even
TrapString_chk:
dc.b "CHK Failure",255
even
TrapString_v:
dc.b "Signed Overflow",255
even
TrapString_priv:
dc.b "Privilege Violation",255
even
TrapString_trace:
dc.b "Tracing",255
even |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Elixir | Elixir | defmodule RC do
def comb(0, _), do: [[]]
def comb(_, []), do: []
def comb(m, [h|t]) do
(for l <- comb(m-1, t), do: [h|l]) ++ comb(m, t)
end
end
{m, n} = {3, 5}
list = for i <- 1..n, do: i
Enum.each(RC.comb(m, list), fn x -> IO.inspect x end) |
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.
| #Object_Pascal | Object Pascal | let condition = true
if condition then
1 (* evaluate something *)
else
2 (* evaluate something *) |
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.)
| #sed | sed | # a single 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.)
| #Seed7 | Seed7 | # A single line comment
(* A multi-line
comment *)
(* In Seed7,
(* comments can be nested. *) *) |
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.)
| #SenseTalk | SenseTalk |
# Hashtag is a comment
-- Dash dash is another comment
// Slash slash is yet another comment
— Alt/Option + Underscore creates an m-dash comment
(* Parentheses and star is used for commenting
blocks of code (* and can be nested *) *)
set foo to true // all comments can append to statements
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Julia | Julia | using Images
colors = [colorant"black", colorant"red", colorant"green", colorant"darkblue",
colorant"purple", colorant"blue", colorant"yellow", colorant"white"]
wcol = 60 # width of each color bar
h, w = 150, wcol * length(colors) + 1
img = Matrix{RGB{N0f8}}(h, w);
for (j, col) in zip(1:wcol:w, colors)
img[:, j:j+wcol] = col
end
save("data/colourbars.jpg", img) |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Kotlin | Kotlin | import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class ColorFrame(width: Int, height: Int): JFrame() {
init {
defaultCloseOperation = EXIT_ON_CLOSE
setSize(width, height)
isVisible = true
}
override fun paint(g: Graphics) {
val colors = listOf(Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.cyan, Color.yellow, Color.white)
val size = colors.size
for (i in 0 until size) {
g.color = colors[i]
g.fillRect(width / size * i, 0, width / size, height)
}
}
}
fun main(args: Array<String>) {
ColorFrame(400, 400)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.