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/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #XLISP | XLISP | (defun quibble (inputs &optional oxford-comma)
(define final
(if (and (caddr inputs) oxford-comma)
", and "
" and " ) )
(defun comma-quibble (words)
(cond
((null words) "")
((null (cdr words)) (car words))
(t (begin
(string-append (car words)
(if (caddr words)
(string-append ", " (comma-quibble (cdr words)))
(string-append final (cadr words))) ) ) ) ) )
(string-append "{" (comma-quibble inputs) "}") )
; test cases:
(print (quibble '())) ; empty list
(print (quibble '("ABC")))
(print (quibble '("ABC" "DEF")))
(print (quibble '("ABC" "DEF" "G" "H")))
(newline)
; test cases using the Oxford comma:
(print (quibble '() t))
(print (quibble '("ABC") t))
(print (quibble '("ABC" "DEF") t))
(print (quibble '("ABC" "DEF" "G" "H") t)) |
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.)
| #Logtalk | Logtalk | % single-line comment; extends to the end of the line |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #LOLCODE | LOLCODE | OBTW This is a
multi line comment
TLDR |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Ruby | Ruby | def game_of_life(name, size, generations, initial_life=nil)
board = new_board size
seed board, size, initial_life
print_board board, name, 0
reason = generations.times do |gen|
new = evolve board, size
print_board new, name, gen+1
break :all_dead if barren? new, size
break :static if board == new
board = new
end
if reason == :all_dead then puts "no more life."
elsif reason == :static then puts "no movement"
else puts "specified lifetime ended"
end
puts
end
def new_board(n)
Array.new(n) {Array.new(n, 0)}
end
def seed(board, n, points=nil)
if points.nil?
# randomly seed board
indices = []
n.times {|x| n.times {|y| indices << [x,y] }}
indices.shuffle[0,10].each {|x,y| board[y][x] = 1}
else
points.each {|x, y| board[y][x] = 1}
end
end
def evolve(board, n)
new = new_board n
n.times {|i| n.times {|j| new[i][j] = fate board, i, j, n}}
new
end
def fate(board, i, j, n)
i1 = [0, i-1].max; i2 = [i+1, n-1].min
j1 = [0, j-1].max; j2 = [j+1, n-1].min
sum = 0
for ii in (i1..i2)
for jj in (j1..j2)
sum += board[ii][jj] if not (ii == i and jj == j)
end
end
(sum == 3 or (sum == 2 and board[i][j] == 1)) ? 1 : 0
end
def barren?(board, n)
n.times {|i| n.times {|j| return false if board[i][j] == 1}}
true
end
def print_board(m, name, generation)
puts "#{name}: generation #{generation}"
m.each {|row| row.each {|val| print "#{val == 1 ? '#' : '.'} "}; puts}
end
game_of_life "blinker", 3, 2, [[1,0],[1,1],[1,2]]
game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
game_of_life "random", 5, 10 |
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.
| #Julia | Julia |
function test(x, y)
if x < y
println("x is less than y")
elseif x > y
println("x is greater than y")
else
println("x is equal to y")
end
end
julia> test(1, 2)
x is less than y
julia> test(2, 1)
x is greater than y
julia> test(1, 1)
x is equal to y
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #XPL0 | XPL0 | include c:\cxpl\codes;
proc Quibble(N, S);
int N, S;
int I;
[ChOut(0, ^{);
for I:= 0 to N-1 do
[Text(0, S(I));
if I<N-2 then Text(0, ", ");
if I=N-2 then Text(0, " and ");
];
ChOut(0, ^});
];
int I;
for I:= 0 to 4 do
if I#3 then [Quibble(I, ["ABC", "DEF", "G", "H"]); CrLf(0)]
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #zkl | zkl | fcn quib(list){ text:=("{"+list.toString(*)[2,-1]+"}").replace("\"","");
if(list.len()<2) text;
else{
z:=(text=text.replace(",",", ")).rfind(",");
String(text[0,z]," and ",text[z+2,*])
}
} |
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.)
| #LotusScript | LotusScript | ' 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.)
| #LSE | LSE | * Ceci est un commentaire qui prend fin quand la ligne se termine
(* Ceci est un commentaire sur plusieurs lignes
comme vous pouvez le voir puisqu'il s'étend sur
plusieurs lignes justement... *)
(* Cette exemple est selon la revision LSE-2000 *) |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Rust | Rust |
use std::collections::HashMap;
use std::collections::HashSet;
type Cell = (i32, i32);
type Colony = HashSet<Cell>;
fn print_colony(col: &Colony, width: i32, height: i32) {
for y in 0..height {
for x in 0..width {
print!("{} ",
if col.contains(&(x, y)) {"O"}
else {"."}
);
}
println!();
}
}
fn neighbours(&(x,y): &Cell) -> Vec<Cell> {
vec![
(x-1,y-1), (x,y-1), (x+1,y-1),
(x-1,y), (x+1,y),
(x-1,y+1), (x,y+1), (x+1,y+1),
]
}
fn neighbour_counts(col: &Colony) -> HashMap<Cell, i32> {
let mut ncnts = HashMap::new();
for cell in col.iter().flat_map(neighbours) {
*ncnts.entry(cell).or_insert(0) += 1;
}
ncnts
}
fn generation(col: Colony) -> Colony {
neighbour_counts(&col)
.into_iter()
.filter_map(|(cell, cnt)|
match (cnt, col.contains(&cell)) {
(2, true) |
(3, ..) => Some(cell),
_ => None
})
.collect()
}
fn life(init: Vec<Cell>, iters: i32, width: i32, height: i32) {
let mut col: Colony = init.into_iter().collect();
for i in 0..iters+1
{
println!("({})", &i);
if i != 0 {
col = generation(col);
}
print_colony(&col, width, height);
}
}
fn main() {
let blinker = vec![
(1,0),
(1,1),
(1,2)];
life(blinker, 3, 3, 3);
let glider = vec![
(1,0),
(2,1),
(0,2), (1,2), (2,2)];
life(glider, 20, 8, 8);
}
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Kabap | Kabap |
if 1;
$result = "Execute";
if 0;
$result = "Ignored";
if 1; {
$result = "Block";
$result = "Execute";
}
if 0; {
$result = "Block";
$result = "Ignored";
}
if 1 == 1;
$result = "Execute";
if 1 < 2;
$result = "Execute";
if 1 <= 1;
$result = "Execute";
if 2 > 1;
$result = "Execute";
if 1 >= 1;
$result = "Execute";
if 1 != 2;
$result = "Execute";
$a = 1;
if $a == 1;
$result = "Execute";
if $a == kabap.version;
$result = "Execute";
if 1 == "1";
$result = "Execute";
if 1 + 1 == 2;
$result = "Execute";
if 1;
if 1; {
if 1;
if 1; {
$result = "Execute";
}
}
|
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
[] # (No input words).
["ABC"]
["ABC", "DEF"]
["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DATA 0
20 DATA 1,"ABC"
30 DATA 2,"ABC","DEF"
40 DATA 4,"ABC","DEF","G","H"
50 FOR n=10 TO 40 STEP 10
60 RESTORE n: GO SUB 1000
70 NEXT n
80 STOP
1000 REM quibble
1010 LET s$=""
1020 READ j
1030 IF j=0 THEN GO TO 1100
1040 FOR i=1 TO j
1050 READ a$
1060 LET s$=s$+a$
1070 IF (i+1)=j THEN LET s$=s$+" and ": GO TO 1090
1080 IF (i+1)<j THEN LET s$=s$+", "
1090 NEXT i
1100 PRINT "{";s$;"}"
1110 RETURN |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #C | C | #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
// A colorful number cannot be greater than 98765432.
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
// Maximum number of products is (8 x 9) / 2.
int products[36] = {};
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
static int count[8];
static bool used[10];
static int largest = 0;
void count_colorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
count_colorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (colorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
count_colorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
int main() {
setlocale(LC_ALL, "");
clock_t start = clock();
printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (colorful(n))
printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
count_colorful(0, 0, 0);
printf("\n\nLargest colorful number: %'d\n", largest);
printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
printf("%d %'d\n", d + 1, count[d]);
total += count[d];
}
printf("\nTotal: %'d\n", total);
clock_t end = clock();
printf("\nElapsed time: %f seconds\n",
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
} |
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.)
| #LSE64 | LSE64 | # single line comment (space after # is required) |
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.)
| #Lua | Lua | -- A single line comment
--[[A multi-line
comment --]] |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Scala | Scala |
;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
;;all cells outside the defined grid are dead
;if n is outside bounds of list, return 0 else value at n
(define (nth n lst)
(cond ((> n (length lst)) 0)
((< n 1) 0)
((= n 1) (car lst))
(else (nth (- n 1) (cdr lst)))))
;return the next state of the supplied universe
(define (next-universe universe)
;value at (x, y)
(define (cell x y)
(if (list? (nth y universe))
(nth x (nth y universe))
0))
;sum of the values of the cells surrounding (x, y)
(define (neighbor-sum x y)
(+ (cell (- x 1) (- y 1))
(cell (- x 1) y)
(cell (- x 1) (+ y 1))
(cell x (- y 1))
(cell x (+ y 1))
(cell (+ x 1) (- y 1))
(cell (+ x 1) y)
(cell (+ x 1) (+ y 1))))
;next state of the cell at (x, y)
(define (next-cell x y)
(let ((cur (cell x y))
(ns (neighbor-sum x y)))
(cond ((and (= cur 1)
(or (< ns 2) (> ns 3)))
0)
((and (= cur 0) (= ns 3))
1)
(else cur))))
;next state of row n
(define (row n out)
(let ((w (length (car universe))))
(if (= (length out) w)
out
(row n
(cons (next-cell (- w (length out)) n)
out)))))
;a range of ints from bot to top
(define (int-range bot top)
(if (> bot top) '()
(cons bot (int-range (+ bot 1) top))))
(map (lambda (n)
(row n '()))
(int-range 1 (length universe))))
;represent the universe as a string
(define (universe->string universe)
(define (prettify row)
(apply string-append
(map (lambda (b)
(if (= b 1) "#" "-"))
row)))
(if (null? universe)
""
(string-append (prettify (car universe))
"\n"
(universe->string (cdr universe)))))
;starting with seed, show reps states of the universe
(define (conway seed reps)
(when (> reps 0)
(display (universe->string seed))
(newline)
(conway (next-universe seed) (- reps 1))))
;; --- Example Universes --- ;;
;blinker in a 3x3 universe
(conway '((0 1 0)
(0 1 0)
(0 1 0)) 5)
;glider in an 8x8 universe
(conway '((0 0 1 0 0 0 0 0)
(0 0 0 1 0 0 0 0)
(0 1 1 1 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)) 30) |
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.
| #Keg | Keg | ?A>[The letter is larger than a|The letter is smaller than a] |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Factor | Factor | USING: assocs grouping grouping.extras io kernel literals math
math.combinatorics math.ranges prettyprint project-euler.common
sequences sequences.extras sets ;
CONSTANT: digits $[ 2 9 [a..b] ]
: (colorful?) ( seq -- ? )
all-subseqs [ product ] map all-unique? ;
: colorful? ( n -- ? )
[ t ] [ number>digits (colorful?) ] if-zero ;
: table. ( seq cols -- )
[ "" pad-groups ] keep group simple-table. ;
: (oom-count) ( n -- count )
digits swap <k-permutations> [ (colorful?) ] count ;
: oom-count ( n -- count )
dup 1 = [ drop 10 ] [ (oom-count) ] if ;
"Colorful numbers under 100:" print
100 <iota> [ colorful? ] filter 10 table. nl
"Largest colorful number:" print
digits <permutations> [ (colorful?) ] find-last nip digits>number . nl
"Count of colorful numbers by number of digits:" print
8 [1..b] [ oom-count ] zip-with dup .
"Total: " write values sum . |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Go | Go | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
} |
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.)
| #M2000_Interpreter | M2000 Interpreter |
Module Comments {
Print "ok" ' comment at the end of line
Print "ok" \ comment at the end of line
\ comment in one line - different color with previous two
'comment in one line
Rem : Print "ok" ' statements after Rem skipped, but stay with syntax highlight
}
Comments
|
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.)
| #M4 | M4 | eval(2*3) # eval(2*3) "#" and text after it aren't processed but passed along
dnl this text completely disappears, including the new line
divert(-1)
Everything diverted to -1 is processed but the output is discarded.
A comment could take this form as long as no macro names are used.
divert |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Scheme | Scheme |
;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
;;all cells outside the defined grid are dead
;if n is outside bounds of list, return 0 else value at n
(define (nth n lst)
(cond ((> n (length lst)) 0)
((< n 1) 0)
((= n 1) (car lst))
(else (nth (- n 1) (cdr lst)))))
;return the next state of the supplied universe
(define (next-universe universe)
;value at (x, y)
(define (cell x y)
(if (list? (nth y universe))
(nth x (nth y universe))
0))
;sum of the values of the cells surrounding (x, y)
(define (neighbor-sum x y)
(+ (cell (- x 1) (- y 1))
(cell (- x 1) y)
(cell (- x 1) (+ y 1))
(cell x (- y 1))
(cell x (+ y 1))
(cell (+ x 1) (- y 1))
(cell (+ x 1) y)
(cell (+ x 1) (+ y 1))))
;next state of the cell at (x, y)
(define (next-cell x y)
(let ((cur (cell x y))
(ns (neighbor-sum x y)))
(cond ((and (= cur 1)
(or (< ns 2) (> ns 3)))
0)
((and (= cur 0) (= ns 3))
1)
(else cur))))
;next state of row n
(define (row n out)
(let ((w (length (car universe))))
(if (= (length out) w)
out
(row n
(cons (next-cell (- w (length out)) n)
out)))))
;a range of ints from bot to top
(define (int-range bot top)
(if (> bot top) '()
(cons bot (int-range (+ bot 1) top))))
(map (lambda (n)
(row n '()))
(int-range 1 (length universe))))
;represent the universe as a string
(define (universe->string universe)
(define (prettify row)
(apply string-append
(map (lambda (b)
(if (= b 1) "#" "-"))
row)))
(if (null? universe)
""
(string-append (prettify (car universe))
"\n"
(universe->string (cdr universe)))))
;starting with seed, show reps states of the universe
(define (conway seed reps)
(when (> reps 0)
(display (universe->string seed))
(newline)
(conway (next-universe seed) (- reps 1))))
;; --- Example Universes --- ;;
;blinker in a 3x3 universe
(conway '((0 1 0)
(0 1 0)
(0 1 0)) 5)
;glider in an 8x8 universe
(conway '((0 0 1 0 0 0 0 0)
(0 0 0 1 0 0 0 0)
(0 1 1 1 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)) 30) |
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.
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
// conventional 'if/else if/else' statement
if (args.isEmpty()) println("No arguments were supplied")
else if (args.size == 1) println("One argument was supplied")
else println("${args.size} arguments were supplied")
print("Enter an integer : ")
val i = readLine()!!.toInt()
// 'when' statement (similar to 'switch' in C family languages)
when (i) {
0, 1 -> println("0 or 1")
in 2 .. 9 -> println("Between 2 and 9")
else -> println("Out of range")
}
// both of these can be used as expressions as well as statements
val s = if (i < 0) "negative" else "non-negative"
println("$i is $s")
val t = when {
i > 0 -> "positive"
i == 0 -> "zero"
else -> "negative"
}
println("$i is $t")
} |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Haskell | Haskell | import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
isColourful :: Integer -> Bool
isColourful n
|n >= 0 && n <= 10 = True
|n > 10 && n < 100 = ((length s) == (length $ nub s)) &&
(not $ any (\c -> elem c "01") s)
|n >= 100 = ((length s) == (length $ nub s)) && (not $ any (\c -> elem c "01") s)
&& ((length products) == (length $ nub products))
where
s :: String
s = show n
products :: [Int]
products = map (\p -> (digitToInt $ head p) * (digitToInt $ last p))
$ divvy 2 1 s
solution1 :: [Integer]
solution1 = filter isColourful [0 .. 100]
solution2 :: Integer
solution2 = head $ filter isColourful [98765432, 98765431 ..] |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #J | J | colorful=: {{(-:~.);<@(*/\)\. 10 #.inv y}}"0
I.colorful i.100
0 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
C=: I.colorful <.i.1e8
>./C
98746253
(~.,. #/.~) 10 <.@^. C
__ 1
0 9
1 56
2 328
3 1540
4 5514
5 13956
6 21596
7 14256
#C
57256 |
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.)
| #Maple | Maple | x := 4: x; # Everything on this line, after this, is a comment.
17; (* This
is
a multiline comment *) 23.4; |
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.)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | (*this is a comment*) |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Scilab | Scilab | Init_state=[0 0 0;...
1 1 1;...
0 0 0];
console_output=%T;
if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then
Input=imread('initial_state.bmp'); //Comment this three lines in case
Init_state=~im2bw(Input,0.1); //there is no input image but
Init_state=1.0.*Init_state; //you still want the graphic window
scf(0); clf();
imshow(~Init_state);
set(gca(),"isoview","on");
end
Curr_state=1.0.*Init_state;
Grid_size=size(Init_state);
Gens=4;
function varargout=neighbourhood(A,i,j)
R_top=i-1;
if i==1 then
R_top=1;
end
R_bottom=i+1;
if i==Grid_size(1) then
R_bottom=Grid_size(1);
end
R_left=j-1;
if j==1 then
R_left=1;
end
C_right=j+1;
if j==Grid_size(2) then
C_right=Grid_size(2);
end
varargout=list(A(R_top:R_bottom,R_left:C_right));
endfunction
function []=console_print(Grid)
String_grid=string(Grid);
for i=1:size(Grid,'r')
for j=1:size(Grid,'c')
if Grid(i,j) then
String_grid(i,j)="#";
else
String_grid(i,j)=" ";
end
end
end
disp(String_grid);
endfunction
neighbours=[];
Next_state=[];
for gen=1:Gens
Next_state=zeros(Init_state);
for i=1:Grid_size(1)
for j=1:Grid_size(2)
neighbours=zeros(3,3);
neighbours=neighbourhood(Curr_state,i,j);
Sum_neighbours=sum(neighbours)-1*Curr_state(i,j);
Alive=Curr_state(i,j);
if Alive then
if Sum_neighbours<2 then
Next_state(i,j)=0;
elseif Sum_neighbours==2 | Sum_neighbours==3 then
Next_state(i,j)=1;
elseif Sum_neighbours>3 then
Next_state(i,j)=0;
end
else
if Sum_neighbours==3 then
Next_state(i,j)=1;
end
end
end
end
if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then
imshow(~Next_state);
sleep(50);
else
sleep(50);
disp("Generation "+string(gen)+":")
console_print(Next_state);
end
if sum(Next_state)==0 | Curr_state==Next_state then
disp('ALL CELLS HAVE DIED OR BECAME INERT');
disp('No. of Generations: '+string(gen))
break
end
Curr_state=Next_state;
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.
| #LabVIEW | LabVIEW |
{if true then yes else no}
-> yes
{def switch
{lambda {:n}
{if {< :n 0}
then :n is negative
else {if {> :n 0}
then :n is positive
else :n is zero}}}}
{switch -12}
-> -12 is negative
{switch 12}
-> 12 is positive
{switch 0}
-> 0 is zero
|
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Java | Java | public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
// A colorful number cannot be greater than 98765432.
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
// Maximum number of products is (8 x 9) / 2.
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
} |
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.)
| #MATLAB | MATLAB | %This is a comment
%% Two percent signs and a space are called a cell divider |
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.)
| #Maxima | Maxima | /* Comment
/* Nested comment */
*/ |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Ada | Ada | with Ada.Text_IO;
with PDF_Out;
procedure Color_Pinstripe_Printer
is
use PDF_Out;
package Point_IO
is new Ada.Text_Io.Float_IO (Real);
procedure Pinstripe (Doc : in out Pdf_Out_File;
Line_Width : Real;
Line_Height : Real;
Screen_Width : Real;
Y : Real)
is
type Color_Range is (Blck, Red, Green, Blue, Magenta, Cyan, Yellow, White);
Colors : constant array (Color_Range) of Color_Type
:= (Blck => (0.0, 0.0, 0.0), Red => (1.0, 0.0, 0.0),
Green => (0.0, 1.0, 0.0), Blue => (0.0, 0.0, 1.0),
Magenta => (1.0, 0.0, 1.0), Cyan => (0.0, 1.0, 1.0),
Yellow => (1.0, 1.0, 0.0), White => (1.0, 1.0, 1.0));
Col : Color_Range := Color_Range'First;
Count : constant Natural
:= Natural (Real'Floor (Screen_Width / Line_Width));
Corner : constant Point := (Doc.Left_Margin, Doc.Bottom_Margin);
Corner_Box : constant Point := Corner + (10.0, 10.0);
Corner_Text : constant Point := Corner_Box + (10.0, 10.0);
Light_Gray : constant Color_Type := (0.9, 0.9, 0.9);
Image : String (1 .. 4);
begin
-- Pinstripes
for A in 0 .. Count loop
Doc.Color (Colors (Col));
Doc.Draw (What => Corner +
Rectangle'(X_Min => Real (A) * Line_Width,
Y_Min => Y,
Width => Line_Width,
Height => Line_Height),
Rendering => Fill);
Col := (if Col = Color_Range'Last
then Color_Range'First
else Color_Range'Succ (Col));
end loop;
-- Box
Doc.Stroking_Color (Black);
Doc.Color (Light_Gray);
Doc.Line_Width (3.0);
Doc.Draw (What => Corner_Box + (0.0, Y, 150.0, 26.0),
Rendering => Fill_Then_Stroke);
-- Text
Doc.Color (Black);
Doc.Text_Rendering_Mode (Fill);
Point_Io.Put (Image, Line_Width, Aft => 1, Exp => 0);
Doc.Put_XY (Corner_Text.X, Corner_Text.Y + Y,
Image & " point color pinstripe");
end Pinstripe;
Doc : PDF_Out_File;
begin
Doc.Create ("color-pinstripe.pdf");
Doc.Page_Setup (A4_Portrait);
Doc.Margins (Margins_Type'(Left => Cm_2_5,
others => One_cm));
declare
Width : constant Real
:= A4_Portrait.Width - Doc.Left_Margin - Doc.Right_Margin;
Height : constant Real
:= A4_Portrait.Height - Doc.Top_Margin - Doc.Bottom_Margin;
begin
for Point in 1 .. 11 loop
Pinstripe (Doc,
Line_Width => Real (Point),
Line_Height => One_Inch,
Screen_Width => Width,
Y => Height - Real (Point) * One_Inch);
end loop;
end;
Doc.Close;
end Color_Pinstripe_Printer; |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #SenseTalk | SenseTalk | set starting_condition to ((0, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1))
RunGameOfLife starting_condition
to printColony colonies
set xCoords to the first item of each item of colonies
set yCoords to the second item of each item of colonies
set min_x to the min of xCoords
set max_x to the max of xCoords
set min_y to the min of yCoords
set max_y to the max of yCoords
repeat for y in min_y..max_y
set row to ()
repeat for x in min_x..max_x
if (x, y) is in colonies
push "#" into row
else
push "-" into row
end if
end repeat
join row using ""
put row
end repeat
end printColony
to neighboursOf coordinate
return ( \
coordinate + (-1, 1), \
coordinate + (0, 1), \
coordinate + (1, 1), \
coordinate + (-1, 0), \
coordinate + (1, 0), \
coordinate + (-1, -1), \
coordinate + (0, -1), \
coordinate + (1, -1), \
)
end neighboursOf
to WillNextGenHaveCell colony, coordinate
set neighbour_count to the number of items in (each item of neighboursOf(coordinate) where each is in colony)
if coordinate is in colony
return neighbour_count is in (2, 3)
else
return neighbour_count equals 3
end if
end WillNextGenHaveCell
to RunGameOfLife colony
printColony colony
set the listInsertionMode to "nested"
repeat 10 times
set new_colony to ()
set xCoords to the first item of each item of colony
set yCoords to the second item of each item of colony
set min_x to (the min of xCoords) - 1
set max_x to (the max of xCoords) + 1
set min_y to (the min of yCoords) - 1
set max_y to (the max of yCoords) + 1
repeat for y in min_y..max_y
repeat for x in min_x..max_x
if WillNextGenHaveCell(colony, (x, y))
insert (x, y) into new_colony
end if
end repeat
end repeat
set colony to new_colony
printColony colony
wait 1 second
end repeat
end RunGameOfLife |
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.
| #Lambdatalk | Lambdatalk |
{if true then yes else no}
-> yes
{def switch
{lambda {:n}
{if {< :n 0}
then :n is negative
else {if {> :n 0}
then :n is positive
else :n is zero}}}}
{switch -12}
-> -12 is negative
{switch 12}
-> 12 is positive
{switch 0}
-> 0 is zero
|
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Julia | Julia | largest = 0
function iscolorful(n, base=10)
0 <= n < 10 && return true
dig = digits(n, base=base)
(1 in dig || 0 in dig || !allunique(dig)) && return false
products = Set(dig)
for i in 2:length(dig), j in 1:length(dig)-i+1
p = prod(dig[j:j+i-1])
p in products && return false
push!(products, p)
end
if n > largest
global largest = n
end
return true
end
function testcolorfuls()
println("Colorful numbers for 1:25, 26:50, 51:75, and 76:100:")
for i in 1:100
iscolorful(i) && print(rpad(i, 5))
i % 25 == 0 && println()
end
csum = 0
for i in 0:7
j, k = i == 0 ? 0 : 10^i, 10^(i+1) - 1
n = count(i -> iscolorful(i), j:k)
csum += n
println("The count of colorful numbers between $j and $k is $n.")
end
println("The largest possible colorful number is $largest.")
println("The total number of colorful numbers is $csum.")
end
testcolorfuls()
|
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ColorfulNumberQ]
ColorfulNumberQ[n_Integer?NonNegative] := Module[{digs, parts},
If[n > 98765432,
False
,
digs = IntegerDigits[n];
parts = Partition[digs, #, 1] & /@ Range[1, Length[digs]];
parts //= Catenate;
parts = Times @@@ parts;
DuplicateFreeQ[parts]
]
]
Multicolumn[Select[Range[99], ColorfulNumberQ], Appearance -> "Horizontal"]
sel = Union[FromDigits /@ Catenate[Permutations /@ Subsets[Range[2, 9], {1, \[Infinity]}]]];
sel = Join[sel, {0, 1}];
cns = Select[sel, ColorfulNumberQ];
Max[cns]
Tally[IntegerDigits/*Length /@ cns] // Grid
Length[cns] |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use enum qw(False True);
use List::Util <max uniqint product>;
use Algorithm::Combinatorics qw(combinations permutations);
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub is_colorful {
my($n) = @_;
return True if 0 <= $n and $n <= 9;
return False if $n =~ /0|1/ or $n < 0;
my @digits = split '', $n;
return False unless @digits == uniqint @digits;
my @p;
for my $w (0 .. @digits) {
push @p, map { product @digits[$_ .. $_+$w] } 0 .. @digits-$w-1;
return False unless @p == uniqint @p
}
True
}
say "Colorful numbers less than 100:\n" . table 10, grep { is_colorful $_ } 0..100;
my $largest = 98765432;
1 while not is_colorful --$largest;
say "Largest magnitude colorful number: $largest\n";
my $total= 10;
map { is_colorful(join '', @$_) and $total++ } map { permutations $_ } combinations [2..9], $_ for 2..8;
say "Total colorful numbers: $total"; |
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.)
| #MAXScript | MAXScript | -- Two dashes precede a single line comment
/* This is a
multi-line comment */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #MBS | MBS | ! A pling in a line starts a comment
INT n:=5 ! Comments can appear at the end of a line
/* A comment block can also be defined using climbstar and starclimb symbols.
This allows comments to be stretched across several lines */ |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #BBC_BASIC | BBC BASIC | PD_RETURNDC = 256
_LOGPIXELSY = 90
DIM pd{lStructSize%, hwndOwner%, hDevMode%, hDevNames%, \
\ hdc%, flags%, nFromPage{l&,h&}, nToPage{l&,h&}, \
\ nMinPage{l&,h&}, nMaxPage{l&,h&}, nCopies{l&,h&}, \
\ hInstance%, lCustData%, lpfnPrintHook%, lpfnSetupHook%, \
\ lpPrintTemplateName%, lpSetupTemplateName%, \
\ hPrintTemplate%, hSetupTemplate%}
pd.lStructSize% = DIM(pd{})
pd.hwndOwner% = @hwnd%
pd.flags% = PD_RETURNDC
SYS "PrintDlg", pd{} TO ok%
IF ok%=0 THEN QUIT
SYS "DeleteDC", @prthdc%
@prthdc% = pd.hdc%
*MARGINS 0,0,0,0
dx% = @vdu%!236-@vdu%!232
dy% = @vdu%!244-@vdu%!240
SYS "GetDeviceCaps", @prthdc%, _LOGPIXELSY TO dpi%
DIM rc{l%,t%,r%,b%}
DIM colour%(7)
colour%() = &000000, &0000FF, &00FF00, &FF0000, \
\ &FF00FF, &FFFF00, &00FFFF, &FFFFFF
VDU 2,1,32,3
pitch% = 1
FOR y% = 0 TO dy% STEP dpi%
col% = 0
FOR x% = 0 TO dx%-pitch% STEP pitch%
rc.l% = x% : rc.r% = x% + pitch%
rc.t% = y% : rc.b% = y% + dpi%
SYS "CreateSolidBrush", colour%(col% MOD 8) TO brush%
SYS "FillRect", @prthdc%, rc{}, brush%
SYS "DeleteObject", brush%
col% += 1
NEXT
pitch% += 1
NEXT y%
VDU 2,1,12,3 |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #FreeBASIC | FreeBASIC | Dim As String exename
#ifdef __FB_WIN32__
exename = "mspaint.exe /pt"
#endif
#ifdef __FB_LINUX__
exename = "lp -o media=A4 "
#endif
Dim As Uinteger ps, col, h, w, x, y1, y2
' (A4) # 595 x 842 dots
w = 842 : h = 595
' create display size window, 8bit color (palette), no frame
Screenres w, h, 8,, 8
h \= 7 : y2 = h -1
For ps = 1 To 7
col = 0
For x = 0 To (w - ps -1) Step ps
Line (x, y1) - (x + ps -1, y2), col, bf
col = (col +1) And 255
Next x
y1 += h : y2 += h
Next ps
Dim As String filename = "color_pinstripe.bmp"
If Bsave(filename, 0) <> 0 Then
Cls: Print "Error saving: "; fileName : Sleep
Else
Dim As Integer result = Exec(exename, filename)
If result = -1 Then Print "Error running "; exename : Sleep
End If
End |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"log"
"os/exec"
"runtime"
)
var palette = [8]string{
"000000", // black
"FF0000", // red
"00FF00", // green
"0000FF", // blue
"FF00FF", // magenta
"00FFFF", // cyan
"FFFF00", // yellow
"FFFFFF", // white
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 7
for b := 1; b <= 11; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(842, 595)
pinstripe(dc)
fileName := "color_pinstripe.png"
dc.SavePNG(fileName)
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("mspaint", "/pt", fileName)
} else {
cmd = exec.Command("lp", fileName)
}
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #SequenceL | SequenceL | life(Cells(2))[I, J] :=
let
numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] +
Cells[I,J-1] +/*current cell*/Cells[I,J+1] +
Cells[I+1,J-1] + Cells[I+1,J] + Cells[I+1,J+1];
in
0 when I=1 or J=1 or I=size(Cells) or J=size(Cells[I]) //On Border
else
0 when numNeighbors < 2 or numNeighbors > 3 //Cell Dies
else
1 when Cells[I,J] = 1 and numNeighbors = 2 or numNeighbors = 3 //Cell lives on or is born.
else
Cells[I,J]; //No Change
stressTestInput(n(0))[y,x] :=
0 when not y = n / 2
else
1
foreach y within 1 ... n,
x within 1 ... n; |
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.
| #langur | langur | # using the fact that submatch() returns an empty array for no match ...
# ... and that a decoupling assignment returns a Boolean...
if val .alias, .name = submatch($re/^(\.idregex;)\\s*;\\s*(\.idregex;)/, .row) {
# success (2 or more values in array returned from submatch function)
# use .alias and .name here
...
} else if .x > 0 {
val .y = 100
...
} else {
val .y = 70
...
} |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Phix | Phix | with javascript_semantics
function colourful(integer n)
if n<10 then return n>=0 end if
sequence digits = sq_sub(sprintf("%d",n),'0'),
ud = unique(deep_copy(digits))
integer ln = length(digits)
if ud[1]<=1 or length(ud)!=ln then return false end if
for i=1 to ln-1 do
for j=i+1 to ln do
atom prod = product(digits[i..j])
if find(prod,ud) then return false end if
ud &= prod
end for
end for
return true
end function
atom t0 = time()
sequence cn = apply(true,sprintf,{{"%2d"},filter(tagset(100,0),colourful)})
printf(1,"The %d colourful numbers less than 100 are:\n%s\n",
{length(cn),join_by(cn,1,10," ")})
sequence count = repeat(0,8),
used = repeat(false,10)
integer largestcn = 0
procedure count_colourful(integer taken=0, string n="")
if taken=0 then
for digit='0' to '9' do
integer dx = digit-'0'+1
used[dx] = true
count_colourful(iff(digit<'2'?9:1),""&digit)
used[dx] = false
end for
else
integer nn = to_integer(n)
if colourful(nn) then
integer ln = length(n)
count[ln] += 1
if nn>largestcn then largestcn = nn end if
end if
if taken<9 then
for digit='2' to '9' do
integer dx = digit-'0'+1
if not used[dx] then
used[dx] = true
count_colourful(taken+1,n&digit)
used[dx] = false
end if
end for
end if
end if
end procedure
count_colourful()
printf(1,"The largest possible colourful number is: %,d\n\n",largestcn)
atom pow = 10
for dc=1 to length(count) do
printf(1," %d digit colourful number count: %,6d - %7.3f%%\n",
{dc, count[dc], 100*count[dc]/pow})
pow = iff(pow=10?90:pow*10)
end for
printf(1,"\nTotal colourful numbers: %,d\n", sum(count))
?elapsed(time()-t0)
|
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.)
| #Metafont | Metafont | % this is "to-end-of-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.)
| #Microsoft_Small_Basic | Microsoft Small Basic | ' This is a comment
i = i + 1 ' You can also append comments to statements |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Julia | Julia |
using Colors, FileIO
const colors = [colorant"black", colorant"red", colorant"green", colorant"blue",
colorant"magenta", colorant"cyan", colorant"yellow", colorant"white"]
function getnumberwithprompt(prompt, t::Type)
s = ""
while (x = tryparse(t, s)) == nothing
print("\n", prompt, ": -> ")
s = strip(readline())
end
return x
end
function colorstripepng(filename)
dpi = getnumberwithprompt("Printer DPI (dots per inch)", Int)
pwidth, plength = getnumberwithprompt("Printer width (inches)", Float64), 10
imgwidth, imgheight = Int(round(pwidth * dpi)), plength * dpi
img = fill(colorant"black", imgheight, imgwidth)
for row in 1:imgheight
stripenum, stripewidth, colorindex = 1, div(row, dpi) + 1, 1
for col in 1:imgwidth
img[row, col] = colors[colorindex]
if (stripenum += 1) % stripewidth == 0
colorindex = mod1(colorindex + 1, length(colors))
end
end
end
save(filename, img)
end
colorstripepng("temp.png")
run(`print temp.png`) # the run statement may need to be set up for the installed device
|
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],
[0.0, 255.0, 0.0], [0.0, 0.0, 255.0],
[255.0, 0.0, 255.0], [0.0, 255.0, 255.0],
[255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]
#---------------------------------------------------------------------------------------------------
proc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) =
## Process signal "begin_print", that is set the number of pages to print.
op.setNPages(1)
#---------------------------------------------------------------------------------------------------
proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) =
## Draw a page.
let context = printContext.getCairoContext()
let lineHeight = printContext.height / 4
var y = 0.0
for lineWidth in [1.0, 2.0, 3.0, 4.0]:
context.setLineWidth(lineWidth)
var x = 0.0
var colorIndex = 0
while x < printContext.width:
context.setSource(Colors[colorIndex])
context.moveTo(x, y)
context.lineTo(x, y + lineHeight)
context.stroke()
colorIndex = (colorIndex + 1) mod Colors.len
x += lineWidth
y += lineHeight
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
# Launch a print operation.
let op = newPrintOperation()
op.connect("begin_print", beginPrint, pointer(nil))
op.connect("draw_page", drawPage, pointer(nil))
# Run the print dialog.
discard op.run(printDialog)
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.ColorPinstripe")
discard app.connect("activate", activate)
discard app.run() |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Phix | Phix | (load "@lib/ps.l")
# Using circular lists for an endless supply of colors
# (black red green blue magenta cyan yellow white)
(setq
Red (0 100 0 0 100 0 100 100 .)
Green (0 0 100 0 0 100 100 100 .)
Blue (0 0 0 100 100 100 0 100 .) )
(call 'lpr
(pdf "pinstripes"
(a4) # 595 x 842 dots
(let (I 0 Step 1)
(for X 595
(color (car Red) (car Green) (car Blue)
(vline X 0 842) )
(when (= Step (inc 'I))
(zero I)
(pop 'Red)
(pop 'Green)
(pop 'Blue) )
(when (=0 (% X 72)) # 1 inch
(zero I)
(inc 'Step) ) ) )
(page) ) ) |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #PicoLisp | PicoLisp | (load "@lib/ps.l")
# Using circular lists for an endless supply of colors
# (black red green blue magenta cyan yellow white)
(setq
Red (0 100 0 0 100 0 100 100 .)
Green (0 0 100 0 0 100 100 100 .)
Blue (0 0 0 100 100 100 0 100 .) )
(call 'lpr
(pdf "pinstripes"
(a4) # 595 x 842 dots
(let (I 0 Step 1)
(for X 595
(color (car Red) (car Green) (car Blue)
(vline X 0 842) )
(when (= Step (inc 'I))
(zero I)
(pop 'Red)
(pop 'Green)
(pop 'Blue) )
(when (=0 (% X 72)) # 1 inch
(zero I)
(inc 'Step) ) ) )
(page) ) ) |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Python | Python |
from turtle import *
from PIL import Image
import time
import subprocess
"""
Only works on Windows. Assumes that you have Ghostscript
installed and in your path.
https://www.ghostscript.com/download/gsdnld.html
Hard coded to 100 pixels per inch.
"""
colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]
screen = getscreen()
# width and height in pixels
# aspect ratio for 11 by 8.5 paper
inch_width = 11.0
inch_height = 8.5
pixels_per_inch = 100
pix_width = int(inch_width*pixels_per_inch)
pix_height = int(inch_height*pixels_per_inch)
screen.setup (width=pix_width, height=pix_height, startx=0, starty=0)
screen.screensize(pix_width,pix_height)
# center is 0,0
# get coordinates of the edges
left_edge = -screen.window_width()//2
right_edge = screen.window_width()//2
bottom_edge = -screen.window_height()//2
top_edge = screen.window_height()//2
# draw quickly
screen.delay(0)
screen.tracer(5)
for inch in range(int(inch_width)-1):
line_width = inch + 1
pensize(line_width)
colornum = 0
min_x = left_edge + (inch * pixels_per_inch)
max_x = left_edge + ((inch+1) * pixels_per_inch)
for y in range(bottom_edge,top_edge,line_width):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1) % len(colors)
setposition(min_x,y)
pendown()
setposition(max_x,y)
screen.getcanvas().postscript(file="striped.eps")
# convert to jpeg
# won't work without Ghostscript.
im = Image.open("striped.eps")
im.save("striped.jpg")
# Got idea from http://rosettacode.org/wiki/Colour_pinstripe/Printer#Go
subprocess.run(["mspaint", "/pt", "striped.jpg"])
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #SETL | SETL | program life;
const
initialMatrix =
[".....",
"..#..",
"...#.",
".###.",
"....."];
loop
init
s := initialLiveSet();
do
output(s);
nm := {[[x+dx, y+dy], [x, y]]: [x, y] in s, dx in {-1..1}, dy in {-1..1}};
s := {c: t = nm{c} | 3 in {#t, #(t less c)}};
end;
proc output(s);
system("clear");
(for y in [0..24])
(for x in [0..78])
nprint(if [x, y] in s then "#" else " " end);
end;
print();
end;
select([], 250);
end proc;
proc initialLiveSet();
return {[x,y]: row = initialMatrix(y), c = row(x) | c = '#'};
end proc;
end program; |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #6502_Assembly | 6502 Assembly | LDA $0200 ;get the color of the top-left pixel of the screen
LDA $05FF ;get the color of the bottom-right pixel of the screen. |
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.
| #LC3_Assembly | LC3 Assembly | BR or BRnzp ; unconditional branch, i.e.
; branch if (result < 0 || result == 0 || result > 0)
; ^ this is always true
BRn ; branch if (result < 0)
BRz ; branch if (result == 0)
BRp ; branch if (result > 0)
; or any combination of these condition codes, e.g.
BRnz ; branch if (result <= 0) |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Picat | Picat | colorful_number(N) =>
N < 10 ;
(X = N.to_string,
X.len <= 8,
not membchk('0',X),
not membchk('1',X),
distinct(X),
[prod(S.map(to_int)) : S in findall(S,(append(_,S,_,X),S != [])) ].distinct).
distinct(L) =>
L.len == L.remove_dups.len. |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Raku | Raku | sub is-colorful (Int $n) {
return True if 0 <= $n <= 9;
return False if $n.contains(0) || $n.contains(1) || $n < 0;
my @digits = $n.comb;
my %sums = @digits.Bag;
return False if %sums.values.max > 1;
for 2..@digits -> $group {
@digits.rotor($group => 1 - $group).map: { %sums{ [×] $_ }++ }
return False if %sums.values.max > 1;
}
True
}
put "Colorful numbers less than 100:\n" ~ (^100).race.grep( &is-colorful).batch(10)».fmt("%2d").join: "\n";
my ($start, $total) = 23456789, 10;
print "\nLargest magnitude colorful number: ";
.put and last if .Int.&is-colorful for $start.flip … $start;
put "\nCount of colorful numbers for each order of magnitude:\n" ~
"1 digit colorful number count: $total - 100%";
for 2..8 {
put "$_ digit colorful number count: ",
my $c = +(flat $start.comb.combinations($_).map: {.permutations».join».Int}).race.grep( &is-colorful ),
" - {($c / (exp($_,10) - exp($_-1,10) ) * 100).round(.001)}%";
$total += $c;
}
say "\nTotal colorful numbers: $total"; |
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.)
| #min | min | ; this is a comment
1 1 + ; add one and one together |
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.)
| #Mirah | Mirah | puts 'code' # I am a comment
/* This is
* a multiple
* line comment */
|
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Racket | Racket |
#lang racket/gui
(define parts 4)
(define dc (new printer-dc%))
(send* dc (start-doc "Colour Pinstripe") (start-page))
(define-values [W H] (send dc get-size))
(define parts 4)
(define colors
'("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White"))
(send dc set-pen "black" 0 'transparent)
(send dc set-brush "black" 'solid)
(define H* (round (/ H parts)))
(for ([row parts])
(define Y (* row H*))
(for ([X (in-range 0 W (add1 row))] [c (in-cycle colors)])
(send dc set-brush c 'solid)
(send dc draw-rectangle X Y (add1 row) H*)))
(send* dc (end-page) (end-doc))
|
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Raku | Raku | unit sub MAIN ($dpi = 300, $size = 'letter');
my $filename = './Color-pinstripe-printer-perl6.png';
my %paper = (
'letter' => { :width(8.5), :height(11.0) }
'A4' => { :width(8.2677), :height(11.6929)}
);
my ($w, $h) = %paper{$size}<width height> »*» $dpi;
# ROYGBIVK
my @color = (1,0,0),(1,.598,0),(1,1,0),(0,1,0),(0,0,1),(.294,0,.51),(.58,0,.827),(0,0,0);
my $gap = floor $w % ($dpi * +@color) / 2;
my $rows = (1, * * 2 … * > $dpi).elems;
my $height = $dpi;
use Cairo;
my @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };
given Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {
given Cairo::Context.new($image) {
my Cairo::Pattern::Solid $bg .= create(1,1,1);
.rectangle(0, 0, $w, $h);
.pattern($bg);
.fill;
$bg.destroy;
my $y = $gap;
for ^$rows -> $row {
my $x = $gap;
my $width = $dpi / (2 ** $row);
for @colors -> $this {
my $v = 0;
while $v++ < (2 ** ($row - 1)) {
given Cairo::Context.new($image) -> $block {
$block.rectangle($x, $y, $width, $height);
$block.pattern($this);
$block.fill;
$block.destroy;
}
$x += $width;
$x += $width if $row;
}
}
$y += $height;
}
}
$image.write_png($filename);
}
# Uncomment next line if you actually want to print it
#run('lp', $filename) |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Shen | Shen | (tc +)
(datatype subtype
(subtype B A); X : B;
_____________________
X : A;)
(datatype integer
if (integer? X)
___________
X: integer;
________________________
(subtype integer number);)
(datatype bit
if (< X 2)
_______
X: bit;
_____________________
(subtype bit integer);)
(datatype row
_________
[] : row;
C : bit; Row : row;
===================
[C | Row] : row;)
(datatype universe
______________
[] : universe;
R : row; Uni : universe;
========================
[R | Uni] : universe;)
(define conway-nth
\\ returns value of x from row if it exists, else 0
{ number --> row --> bit }
_ [] -> 0
N _ -> 0 where (< N 0)
0 [A|B] -> A
N [A|B] -> (conway-nth (- N 1) B))
(define row-retrieve
{ number --> universe --> row }
_ [] -> []
0 [] -> []
0 [A|B] -> A
N [A|B] -> (row-retrieve (- N 1) B))
(define cell-retrieve
{ number --> number --> universe --> bit }
X Y Universe -> (conway-nth X (row-retrieve Y Universe)))
(define neighbors
\\ takes an X and Y, retrieves the number of neighbors
{ number --> number --> universe --> number }
X Y Universe -> (let ++ (+ 1)
-- (/. X (- X 1))
(+ (cell-retrieve (++ X) Y Universe)
(cell-retrieve (++ X) (++ Y) Universe)
(cell-retrieve (++ X) (-- Y) Universe)
(cell-retrieve (-- X) Y Universe)
(cell-retrieve (-- X) (++ Y) Universe)
(cell-retrieve (-- X) (-- Y) Universe)
(cell-retrieve X (++ Y) Universe)
(cell-retrieve X (-- Y) Universe))))
(define handle-alive
{ number --> number --> universe --> bit }
X Y Universe -> (if (or (= (neighbors X Y Universe) 2)
(= (neighbors X Y Universe) 3))
1 0))
(define handle-dead
{ number --> number --> universe --> bit }
X Y Universe -> (if (= (neighbors X Y Universe) 3)
1 0))
(define next-row
\\ first argument must be a previous row, second must be 0 when
\\ first called, third must be a Y value and the final must be the
\\ current universe
{ row --> number --> number --> universe --> row }
[] _ _ _ -> []
[1|B] X Y Universe -> (cons (handle-alive X Y Universe)
(next-row B (+ X 1) Y Universe))
[_|B] X Y Universe -> (cons (handle-dead X Y Universe)
(next-row B (+ X 1) Y Universe)))
(define next-universe
\\ both the first and second arguments must be the same universe,
\\ the third must be 0 upon first call
{ universe --> number --> universe --> universe }
[] _ _ -> []
[Row|Rest] Y Universe -> (cons (next-row Row 0 Y Universe)
(next-universe Rest (+ Y 1) Universe)))
(define display-row
{ row --> number }
[] -> (nl)
[1|Rest] -> (do (output "* ")
(display-row Rest))
[_|Rest] -> (do (output " ")
(display-row Rest)))
(define display-universe
{ universe --> number }
[] -> (nl 2)
[Row|Rest] -> (do (display-row Row)
(display-universe Rest)))
(define iterate-universe
{ number --> universe --> number }
0 _ -> (nl)
N Universe -> (do (display-universe Universe)
(iterate-universe (- N 1)
(next-universe Universe 0 Universe))))
(iterate-universe
10
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 1 1 1 0]
[0 1 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]) |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #8086_Assembly | 8086 Assembly | ;input: cx = x coordinate of pixel, dx = y coordinate of pixel, bh = page number
mov ah,0Dh
int 10h |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Action.21 | Action! | PROC Main()
BYTE POINTER ptr
BYTE
w=[160],h=[160],x=[0],y=[0],c,k,update=[1],
CH=$02FC ;Internal hardware value for last key pressed
CARD size=[6400],i
Graphics(15) ;Graphics 160x160 with 4 colors with text window
ptr=PeekC(88)
; Fill screen with random colors
FOR i=1 TO size
DO
ptr^=Rand(0)
ptr==+1
OD
PrintE("Use arrow keys to change position and Esc to exit.")
DO
IF update THEN
c=Locate(x,y)
PrintF("x=%B y=%B c=%B%E",x,y,c)
FI
k=CH
CH=$FF
update=1
IF k=134 THEN
IF x=0 THEN x=w-1
ELSE x==-1 FI
ELSEIF k=135 THEN
IF x=w-1 THEN x=0
ELSE x==+1 FI
ELSEIF k=142 THEN
IF y=0 THEN y=h-1
ELSE y==-1 FI
ELSEIF k=143 THEN
IF y=h-1 THEN y=0
ELSE y==+1 FI
ELSEIF k=28 THEN
EXIT
ELSE
update=0
FI
OD
RETURN |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #App_Inventor | App Inventor | PixelGetColor, color, %X%, %Y% |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #AppleScript | AppleScript |
choose color default color {0, 0, 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.
| #LIL | LIL | if {$a > 10} {print "code evaluated on true"}
if {$a > 10} {print "again"} {print "code evaluated on false"} |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #Wren | Wren | import "./math" for Int, Nums
import "./set" for Set
import "./seq" for Lst
import "./fmt" for Fmt
var isColorful = Fn.new { |n|
if (n < 0) return false
if (n < 10) return true
var digits = Int.digits(n)
if (digits.contains(0) || digits.contains(1)) return false
var set = Set.new(digits)
var dc = digits.count
if (set.count < dc) return false
for (k in 2..dc) {
for (i in 0..dc-k) {
var prod = 1
for (j in i..i+k-1) prod = prod * digits[j]
if (set.contains(prod)) return false
set.add(prod)
}
}
return true
}
var count = List.filled(9, 0)
var used = List.filled(11, false)
var largest = 0
var countColorful // recursive
countColorful = Fn.new { |taken, n|
if (taken == 0) {
for (digit in 0..9) {
var dx = digit + 1
used[dx] = true
countColorful.call((digit < 2) ? 9 : 1, String.fromByte(digit + 48))
used[dx] = false
}
} else {
var nn = Num.fromString(n)
if (isColorful.call(nn)) {
var ln = n.count
count[ln] = count[ln] + 1
if (nn > largest) largest = nn
}
if (taken < 9) {
for (digit in 2..9) {
var dx = digit + 1
if (!used[dx]) {
used[dx] = true
countColorful.call(taken + 1, n + String.fromByte(digit + 48))
used[dx] = false
}
}
}
}
}
var cn = (0..99).where { |i| isColorful.call(i) }.toList
System.print("The %(cn.count) colorful numbers less than 100 are:")
for (chunk in Lst.chunks(cn, 10)) Fmt.print("$2d", chunk)
countColorful.call(0, "")
System.print("\nThe largest possible colorful number is:")
Fmt.print("$,d\n", largest)
System.print("Count of colorful numbers for each order of magnitude:")
var pow = 10
for (dc in 1...count.count) {
Fmt.print(" $d digit colorful number count: $,6d - $7.3f\%", dc, count[dc], 100 * count[dc] / pow)
pow = (pow == 10) ? 90 : pow * 10
}
Fmt.print("\nTotal colorful numbers: $,d", Nums.sum(count)) |
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.)
| #mIRC_Scripting_Language | mIRC Scripting Language | ;Single Line Comment
/*
Multiple
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.)
| #Modula-2 | Modula-2 | (* Comments (* can nest *)
and they can span multiple lines.
*) |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Tcl | Tcl | package require Tk
# Allocate a temporary drawing surface
canvas .c
# The cycle of colors we want to use
set colors {black red green blue magenta cyan yellow white}
# Draw the output we want
for {set y 0;set dx 1} {$y < 11*72} {incr y 72;incr dx} {
for {set x 0;set c 0} {$x < 8.5*72} {incr x $dx;incr c} {
.c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+73}] \
-fill [lindex $colors [expr {$c%[llength $colors]}]] -outline {}
}
}
# Send postscript to default printer, scaled 1 pixel -> 1 point
exec lp - << [.c postscript -height $y -width $x -pageheight $y -pagewidth $x]
# Explicit exit; no GUI desired
exit |
http://rosettacode.org/wiki/Colour_pinstripe/Printer | Colour pinstripe/Printer | The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.
After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).
Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.
Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.
| #Wren | Wren | import "graphics" for Canvas, Color, ImageData
import "dome" for Window
import "plugin" for Plugin
Plugin.load("printer")
import "printer" for Printer
class Main {
construct new() {
Window.title = "Color pinstripe - printer"
_width = 842
_height = 595
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)
}
pinstripe(colors) {
var w = _width
var h = (_height/7).floor
for (b in 1..11) {
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
}
}
}
init() {
var img = ImageData.create("color_pinstripe", _width, _height)
for (x in 0..._width) {
for (y in 0..._height) img.pset(x, y, Canvas.pget(x, y))
}
img.saveToFile("color_pinstripe.png")
Printer.printFile("color_pinstripe.png")
}
update() {}
draw(alpha) {}
}
var Game = Main.new() |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Sidef | Sidef | var w = Num(`tput cols`)
var h = Num(`tput lines`)
var r = "\033[H"
var dirs = [[-1,-1], [-1, 0], [-1, 1], [ 0,-1],
[ 0, 1], [ 1,-1], [ 1, 0], [ 1, 1]]
var universe = h.of { w.of {1.rand < 0.1} }
func iterate {
var new = h.of { w.of(false) }
static rx = (^h ~X ^w)
for i,j in rx {
var neighbor = 0
for y,x in (dirs.map {|dir| dir »+« [i, j] }) {
universe[y % h][x % w] && ++neighbor
neighbor > 3 && break
}
new[i][j] = (universe[i][j]
? (neighbor==2 || neighbor==3)
: (neighbor==3))
}
universe = new
}
STDOUT.autoflush(true)
loop {
print r
say universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
iterate()
} |
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
| #6502_Assembly | 6502 Assembly | define color $00
define looptemp $01
loop_1wide:
lda color
sta $0200,x
inc color
inx
bne loop_1wide
loop_2wide:
lda color
sta $0300,x
inx
sta $0300,x
inc color
inx
bne loop_2wide
lda #0
tax
tay
sta color
sta looptemp ;reset ram
loop_3wide:
lda color
sta $0400,x
inc looptemp
inx
sta $0400,x
inc looptemp
inx
sta $0400,x
inc looptemp
inc color
inx
lda looptemp
cmp #$1e
bne loop_3wide
lda color ;loop overhead
sta $0400,x ;can't fit all of this stripe.
;two columns will have to do.
inx
lda color
sta $0400,x
inx
lda #0
sta color
sta looptemp ;reset color and looptemp
iny
cpy #$08 ;check secondary loop counter
bne loop_3wide
lda #0
tax
tay
sta color
sta looptemp ;reset ram
loop_4wide:
lda color
sta $0500,x
inx
inc looptemp
sta $0500,x
inx
inc looptemp
sta $0500,x
inx
inc looptemp
sta $0500,x
inc color
inc looptemp
inx
lda looptemp
cmp #$20
bne loop_4wide
lda #0
sta looptemp
sta color
iny
cpy #$8
bcc loop_4wide
brk ;program end |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #AutoHotkey | AutoHotkey | PixelGetColor, color, %X%, %Y% |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #AutoIt | AutoIt | Opt('MouseCoordMode',1) ; 1 = (default) absolute screen coordinates
$pos = MouseGetPos()
$c = PixelGetColor($pos[0], $pos[1])
ConsoleWrite("Color at x=" & $pos[0] & ",y=" & $pos[1] & _
" ==> " & $c & " = 0x" & Hex($c) & @CRLF) |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #C.2B.2B | C++ | // colorwheelwidget.cpp
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
} |
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.
| #Lisaac | Lisaac | + n : INTEGER;
n := 3;
(n = 2).if {
IO.put_string "n is 2\n";
}.elseif {n = 3} then {
IO.put_string "n is 3\n";
}.elseif {n = 4} then {
IO.put_string "n is 4\n";
} else {
IO.put_string "n is none of the above\n";
}; |
http://rosettacode.org/wiki/Colorful_numbers | Colorful numbers | A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840
Every product is unique.
2346 is not a colorful number. 2, 3, 4, 6, (2×3)6, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144
The product 6 is repeated.
Single digit numbers are considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
Task
Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
Use that routine to find all of the colorful numbers less than 100.
Use that routine to find the largest possible colorful number.
Stretch
Find and display the count of colorful numbers in each order of magnitude.
Find and show the total count of all colorful numbers.
Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.
| #XPL0 | XPL0 | func IPow(A, B); \A^B
int A, B, T, I;
[T:= 1;
for I:= 1 to B do T:= T*A;
return T;
];
func Colorful(N); \Return 'true' if N is a colorful number
int N, Digits, R, I, J, Prod;
def Size = 9*8*7*6*5*4*3*2 + 1;
char Used(Size), Num(10);
[if N < 10 then return true; \single digit number is colorful
FillMem(Used, false, 10); \digits must be unique
Digits:= 0;
repeat N:= N/10; \slice digits off N
R:= rem(0);
if N=1 or R=0 or R=1 then return false;
if Used(R) then return false;
Used(R):= true; \digits must be unique
Num(Digits):= R;
Digits:= Digits+1;
until N = 0;
FillMem(Used+10, false, Size-10); \products must be unique
for I:= 0 to Digits-2 do
[Prod:= Num(I);
for J:= I+1 to Digits-1 do
[Prod:= Prod * Num(J);
if Used(Prod) then return false;
Used(Prod):= true;
];
];
return true;
];
int Count, N, Power, Total;
[Text(0, "Colorful numbers less than 100:
");
Count:= 0;
for N:= 0 to 99 do
if Colorful(N) then
[IntOut(0, N);
Count:= Count+1;
if rem(Count/10) then ChOut(0, 9\tab\) else CrLf(0);
];
Text(0, "
Largest magnitude colorful number: ");
N:= 98_765_432;
loop [if Colorful(N) then quit;
N:= N-1;
];
IntOut(0, N);
Text(0, "
Count of colorful numbers for each order of magnitude:
");
Total:= 0;
for Power:= 1 to 8 do
[Count:= if Power=1 then 1 else 0;
for N:= IPow(10, Power-1) to IPow(10, Power)-1 do
if Colorful(N) then Count:= Count+1;
IntOut(0, Power);
Text(0, " digit colorful number count: ");
IntOut(0, Count);
CrLf(0);
Total:= Total + Count;
];
Text(0, "
Total colorful numbers: ");
IntOut(0, Total);
CrLf(0);
] |
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.)
| #Modula-3 | Modula-3 | (* Comments (* can nest *)
and they can span multiple lines.
*) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Monte | Monte |
# This comment goes to the end of the line
/** This comment is multi-line.
Yes, it starts with a two stars
and ends with only one.
These should only be used for docstrings. */
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Simula | Simula | COMMENT A PORT OF AN R6RS SCHEME IMPLEMENTATION OF CONWAY'S GAME OF LIFE TO SIMULA --- ASSUMES ;
COMMENT ALL CELLS OUTSIDE THE DEFINED GRID ARE DEAD ;
BEGIN
COMMENT FIRST WE NEED CONS, CAR, CDR, LENGTH AND MAP TO SIMULATE SCHEME ;
CLASS ATOM;;
ATOM CLASS CELL(ALIVE); INTEGER ALIVE;;
ATOM CLASS LIST(A1, A2); REF(ATOM) A1, A2;;
REF(LIST) PROCEDURE CONS(A1, A2); REF(ATOM) A1, A2;
CONS :- NEW LIST(A1, A2);
REF(ATOM) PROCEDURE CAR(LST); REF(LIST) LST;
CAR :- LST.A1;
REF(ATOM) PROCEDURE CDR(LST); REF(LIST) LST;
CDR :- LST.A2;
INTEGER PROCEDURE LENGTH(LST); REF(LIST) LST;
LENGTH := IF LST == NONE THEN 0 ELSE 1 + LENGTH(CDR(LST));
REF(LIST) PROCEDURE MAP(F, LST); PROCEDURE F IS REF(ATOM) PROCEDURE F(ARG); REF(ATOM) ARG;; REF(LIST) LST;
MAP :- IF LST == NONE THEN NONE ELSE CONS(F(CAR(LST)), MAP(F, CDR(LST)));
COMMENT NOW FOLLOWS THE PROBLEM SPECIFIC PART ;
COMMENT IF N IS OUTSIDE BOUNDS OF LIST, RETURN 0 ELSE VALUE AT N ;
REF(ATOM) PROCEDURE NTH(N, LST); INTEGER N; REF(LIST) LST;
NTH :- IF N > LENGTH(LST) THEN NEW CELL(0) ELSE
IF N < 1 THEN NEW CELL(0) ELSE
IF N = 1 THEN CAR(LST) ELSE NTH(N - 1, CDR(LST));
COMMENT RETURN THE NEXT STATE OF THE SUPPLIED UNIVERSE ;
REF(LIST) PROCEDURE NEXTUNIVERSE(UNIVERSE); REF(LIST) UNIVERSE;
BEGIN
COMMENT VALUE AT (X, Y) ;
INTEGER PROCEDURE VALUEAT(X, Y); INTEGER X, Y;
BEGIN
REF(ATOM) A;
A :- NTH(Y, UNIVERSE);
INSPECT A
WHEN LIST DO
VALUEAT := NTH(X, THIS LIST) QUA CELL.ALIVE
OTHERWISE
VALUEAT := 0;
END VALUEAT;
COMMENT SUM OF THE VALUES OF THE CELLS SURROUNDING (X, Y) ;
INTEGER PROCEDURE NEIGHBORSUM(X, Y); INTEGER X, Y;
NEIGHBORSUM :=
VALUEAT(X - 1, Y - 1)
+ VALUEAT(X - 1, Y )
+ VALUEAT(X - 1, Y + 1)
+ VALUEAT(X, Y - 1)
+ VALUEAT(X, Y + 1)
+ VALUEAT(X + 1, Y - 1)
+ VALUEAT(X + 1, Y )
+ VALUEAT(X + 1, Y + 1);
COMMENT NEXT STATE OF THE CELL AT (X, Y) ;
INTEGER PROCEDURE NEXTCELL(X, Y); INTEGER X, Y;
BEGIN
INTEGER CUR, NS;
CUR := VALUEAT(X, Y);
NS := NEIGHBORSUM(X, Y);
NEXTCELL := IF CUR = 1 AND (NS < 2 OR NS > 3) THEN 0 ELSE
IF CUR = 0 AND NS = 3 THEN 1 ELSE CUR;
END NEXTCELL;
COMMENT NEXT STATE OF ROW N ;
REF(LIST) PROCEDURE ROW(N, OUT); INTEGER N; REF(LIST) OUT;
BEGIN
INTEGER W, O;
W := LENGTH(CAR(UNIVERSE));
O := LENGTH(OUT);
ROW :- IF W = O THEN OUT ELSE ROW(N, CONS(NEW CELL(NEXTCELL(W - O, N)), OUT));
END ROW;
COMMENT A RANGE OF INTS FROM BOT TO TOP ;
REF(LIST) PROCEDURE INTRANGE(BOT, TOP); INTEGER BOT, TOP;
INTRANGE :- IF BOT > TOP THEN NONE ELSE CONS(NEW CELL(BOT), INTRANGE(BOT + 1, TOP));
REF(ATOM) PROCEDURE LAMBDA(N); REF(ATOM) N;
LAMBDA :- ROW(N QUA CELL.ALIVE, NONE);
NEXTUNIVERSE :- MAP(LAMBDA, INTRANGE(1, LENGTH(UNIVERSE)));
END NEXTUNIVERSE;
COMMENT DISPLAY THE UNIVERSE ;
PROCEDURE DISPLAY(LST); REF(LIST) LST;
BEGIN
WHILE LST =/= NONE DO
BEGIN
REF(LIST) LI;
LI :- CAR(LST);
WHILE LI =/= NONE DO
BEGIN
REF(CELL) CE;
CE :- CAR(LI);
OUTCHAR(IF CE.ALIVE = 1 THEN '#' ELSE '-');
LI :- CDR(LI);
END;
OUTIMAGE;
LST :- CDR(LST);
END;
END DISPLAY;
COMMENT STARTING WITH SEED, SHOW REPS STATES OF THE UNIVERSE ;
PROCEDURE CONWAY(SEED, REPS); REF(LIST) SEED; INTEGER REPS;
BEGIN
IF REPS > 0 THEN
BEGIN
DISPLAY(SEED);
OUTIMAGE;
CONWAY(NEXTUNIVERSE(SEED), REPS - 1);
END;
END CONWAY;
REF(CELL) O, L;
O :- NEW CELL(0);
L :- NEW CELL(1);
COMMENT BLINKER IN A 3X3 UNIVERSE ;
! (CONWAY '((0 1 0)
(0 1 0)
(0 1 0)) 5) ;
CONWAY(CONS(CONS(O, CONS(L, CONS(O, NONE))),
CONS(CONS(O, CONS(L, CONS(O, NONE))),
CONS(CONS(O, CONS(L, CONS(O, NONE))),
NONE))), 5);
COMMENT GLIDER IN AN 8X8 UNIVERSE ;
!(CONWAY '((0 0 1 0 0 0 0 0)
(0 0 0 1 0 0 0 0)
(0 1 1 1 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)
(0 0 0 0 0 0 0 0)) 30) ;
OUTIMAGE;
CONWAY(CONS(CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(L, CONS(L, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
NONE)))))))), 30);
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
| #Action.21 | Action! | PROC Main()
BYTE
i,
CH=$02FC, ;Internal hardware value for last key pressed
PALNTSC=$D014, ;To check if PAL or NTSC system is used
PCOLR0=$02C0,PCOLR1=$02C1,
PCOLR2=$02C2,PCOLR3=$02C3,
COLOR0=$02C4,COLOR1=$02C5,
COLOR2=$02C6,COLOR3=$02C7,
COLOR4=$02C8
Graphics(10)
PCOLR0=$04 ;gray
PCOLR1=$00 ;black
IF PALNTSC=15 THEN
PCOLR2=$42 ;red for NTSC
PCOLR3=$C6 ;green for NTSC
COLOR0=$84 ;blue for NTSC
COLOR1=$66 ;magenta for NTSC
COLOR2=$A6 ;cyan for NTSC
COLOR3=$FC ;yellow for NTSC
ELSE
PCOLR2=$22 ;red for PAL
PCOLR3=$B6 ;green for PAL
COLOR0=$74 ;blue for PAL
COLOR1=$48 ;magenta for PAL
COLOR2=$96 ;cyan for PAL
COLOR3=$EC ;yellow for PAL
FI
COLOR4=$0F ;white
FOR i=0 TO 79
DO
Color=i MOD 8+1
Plot(i,0) DrawTo(i,47)
Color=i/2 MOD 8+1
Plot(i,48) DrawTo(i,95)
Color=i/3 MOD 8+1
Plot(i,96) DrawTo(i,143)
Color=i/4 MOD 8+1
Plot(i,144) DrawTo(i,191)
OD
DO UNTIL CH#$FF OD
CH=$FF
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
| #ActionScript | ActionScript |
package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
public class ColourPinstripe extends Sprite {
public function ColourPinstripe():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
var colours:Array = [ 0xFF000000, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF00FF, 0xFF00FFFF, 0xFFFFFF00, 0xFFFFFFFF ];
var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xFFFFFFFF);
data.lock();
var w:uint = data.width, h:uint = data.height / 4;
var x:uint, y:uint = 0, i:uint, px:uint, colourIndex:uint, colour:uint, maxy:uint = h;
for ( i = 1; i <= 4; i++ ) {
for ( ; y < maxy; y++ ) {
colour = 0xFF000000;
colourIndex = 0;
px = 1;
for ( x = 0; x < w; x++ ) {
if ( px == i ) {
colourIndex = (colourIndex > 7) ? 0 : colourIndex + 1;
colour = colours[colourIndex];
px = 1;
}
else px++;
data.setPixel32(x, y, colour);
}
}
maxy += h;
}
data.unlock();
addChild(new Bitmap(data));
}
}
}
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Axe | Axe | Disp pxl-Test(50,50)▶Dec,i |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #BaCon | BaCon | INCLUDE canvas
FULLSCREEN
color = GETINK(100, 100, 4)
WAITKEY |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #BASIC | BASIC | MOUSE ON
WHILE 1
m=MOUSE(0)
PRINT POINT(MOUSE(1),MOUSE(2))
WEND |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Delphi | Delphi |
program Color_wheel;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils,
Vcl.Graphics,
System.Math,
Vcl.Imaging.pngimage;
const
TAU = 2 * PI;
function HSBtoColor(hue, sat, bri: Double): TColor;
var
f, h: Double;
u, p, q, t: Byte;
begin
u := Trunc(bri * 255 + 0.5);
if sat = 0 then
Exit(rgb(u, u, u));
h := (hue - Floor(hue)) * 6;
f := h - Floor(h);
p := Trunc(bri * (1 - sat) * 255 + 0.5);
q := Trunc(bri * (1 - sat * f) * 255 + 0.5);
t := Trunc(bri * (1 - sat * (1 - f)) * 255 + 0.5);
case Trunc(h) of
0:
result := rgb(u, t, p);
1:
result := rgb(q, u, p);
2:
result := rgb(p, u, t);
3:
result := rgb(p, q, u);
4:
result := rgb(t, p, u);
5:
result := rgb(u, p, q);
else
result := clwhite;
end;
end;
function ColorWheel(Width, Height: Integer): TPngImage;
var
Center: TPoint;
Radius: Integer;
x, y: Integer;
Hue, dy, dx, dist, theta: Double;
Bmp: TBitmap;
begin
Bmp := TBitmap.Create;
Bmp.SetSize(Width, Height);
with Bmp.Canvas do
begin
Brush.Color := clWhite;
FillRect(ClipRect);
Center := ClipRect.CenterPoint;
Radius := Center.X;
if Center.Y < Radius then
Radius := Center.Y;
for y := 0 to Height - 1 do
begin
dy := y - Center.y;
for x := 0 to Width - 1 do
begin
dx := x - Center.x;
dist := Sqrt(Sqr(dx) + Sqr(dy));
if dist <= Radius then
begin
theta := ArcTan2(dy, dx);
Hue := (theta + PI) / TAU;
Pixels[x, y] := HSBtoColor(Hue, 1, 1);
end;
end;
end;
end;
Result := TPngImage.Create;
Result.Assign(Bmp);
Bmp.Free;
end;
begin
with ColorWheel(500, 500) do
begin
SaveToFile('ColorWheel.png');
Free;
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.
| #Little | Little | int a = 3;
// if-then-else
if (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
// unless
unless (a == 2) { // equivalent to if (a != 2)
puts ("a is 2"); // It will print this line
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
// switch
switch (a) {
case 2:
puts ("a is 2");
break;
case 3:
puts ("a is 3");
break;
case 4:
puts ("a is 4");
break;
default:
puts("is neither");
} |
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.)
| #MontiLang | MontiLang |
/# This is a comment #/
/#
comments can span multiple lines
nested comments are not supported #/
|
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.)
| #MOO | MOO | "String literals are technically the only long-term comment format";
// Some compilers will, however, compile // one-liners to string literals as well (and vice-versa)
/* Classical C-style comments are removed entirely during compile */ |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Smalltalk | Smalltalk |
"Blinker"
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.
"Toad"
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10
|
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
| #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Palettes;
with SDL.Events.Events;
procedure Colour_Pinstripe_Display is
Width : constant := 1_200;
Height : constant := 800;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
procedure Draw_Pinstripe (Line_Width : in Integer;
Line_Height : in Integer;
Screen_Width : in Integer;
Y : in Integer)
is
type Colour_Range is (Black, Red, Green, Blue, Magenta, Cyan, Yellow, White);
Colours : constant array (Colour_Range) of SDL.Video.Palettes.Colour
:= (Black => (0, 0, 0, 255), Red => (255, 0, 0, 255),
Green => (0, 255, 0, 255), Blue => (0, 0, 255, 255),
Magenta => (255, 0, 255, 255), Cyan => (0, 255, 255, 255),
Yellow => (255, 255, 0, 255), White => (255, 255, 255, 255));
Col : Colour_Range := Colour_Range'First;
Count : constant Integer := Screen_Width / Line_Width;
begin
for A in 0 .. Count loop
Renderer.Set_Draw_Colour (Colour => Colours (Col));
Renderer.Fill (Rectangle => (X => SDL.C.int (A * Line_Width), Y => SDL.C.int (Y),
Width => SDL.C.int (Line_Width),
Height => SDL.C.int (Line_Height)));
Col := (if Col = Colour_Range'Last
then Colour_Range'First
else Colour_Range'Succ (Col));
end loop;
end Draw_Pinstripe;
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Pinstripe",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Draw_Pinstripe (1, Height / 4, Width, 0);
Draw_Pinstripe (2, Height / 4, Width, 200);
Draw_Pinstripe (3, Height / 4, Width, 400);
Draw_Pinstripe (4, Height / 4, Width, 600);
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Colour_Pinstripe_Display; |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #QBasic | QBasic |
'Example: Find color of a screen pixel in QBasic (adapted from QBasic Help file).
' POINT(x%, y%) returns color of pixel at coordinates x,y.
SCREEN 7 'Choose color graphics screen (1,2,4,7,8,9,11,12,13).
LINE (0, 0)-(100, 100), 2 'Draw diagonal line in color attribute 2.
LOCATE 14, 1 'Locate below diagonal line to show output.
FOR y% = 1 TO 10
FOR x% = 1 TO 10
PRINT POINT(x%, y%); 'POINT(x%, y%) displays pixel color.
NEXT x%
PRINT
NEXT y%
END
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #C | C |
#include <X11/Xlib.h>
void
get_pixel_color (Display *d, int x, int y, XColor *color)
{
XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
color->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);
}
// Your code
XColor c;
get_pixel_color (display, 30, 40, &c);
printf ("%d %d %d\n", c.red, c.green, c.blue);
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | #include "fbgfx.bi"
Sub HSVtoRGB(h As Single, s As Integer, v As Integer, Byref r As Integer, Byref g As Integer, Byref b As Integer)
If s = 0 Then
r = v
g = v
b = v
Return
End If
h = h Mod 360
Dim As Single hue = h
Select Case h
Case 0f To 51.5f
hue = ((hue ) * (30f / (51.5f )))
Case 51.5f To 122f
hue = ((hue - 51.5f) * (30f / (122f - 51.5f))) + 30
Case 122f To 142.5f
hue = ((hue - 122f) * (30f / (142.5f - 122f))) + 60
Case 142.5f To 165.5f
hue = ((hue - 142.5f) * (30f / (165.5f - 142.5f))) + 90
Case 165.5f To 192f
hue = ((hue - 165.5f) * (30f / (192f - 165.5f))) + 120
Case 192f To 218.5f
hue = ((hue - 192f) * (30f / (218.5f - 192f))) + 150
Case 218.5f To 247f
hue = ((hue - 218.5f) * (30f / (247f - 218.5f))) + 180
Case 247f To 275.5f
hue = ((hue - 247f) * (30f / (275.5f - 247f))) + 210
Case 275.5f To 302.5f
hue = ((hue - 275.5f) * (30f / (302.5f - 275.5f))) + 240
Case 302.5f To 330f
hue = ((hue - 302.5f) * (30f / (330f - 302.5f))) + 270
Case 330f To 344.5f
hue = ((hue - 330f) * (30f / (344.5f - 330f))) + 300
Case 344.5f To 360f
hue = ((hue - 344.5f) * (30f / (360f - 344.5f))) + 330
End Select
h = hue
h = h Mod 360
Dim As Single h1 = h / 60
Dim As Integer i = Int(h1)
Dim As Single f = h1 - i
Dim As Integer p = v * (255 - s) / 256
Dim As Integer q = v * (255 - f * s) / 256
Dim As Integer t = v * (255 - (1 - f) * s) / 256
Select Case As Const i
Case 0
r = v
g = t
b = p
Return
Case 1
r = q
g = v
b = p
Return
Case 2
r = p
g = v
b = t
Return
Case 3
r = p
g = q
b = v
Return
Case 4
r = t
g = p
b = v
Return
Case 5
r = v
g = p
b = q
Return
End Select
End Sub
Const pi As Single = 4 * Atn(1)
Const radius = 160
Const xres = (radius * 2) + 1, yres = xres
Screenres xres, yres, 32
Windowtitle "Color wheel"
Dim As Integer r,g,b
Dim As Single dx, dy, dist, angle
Do
Screenlock
Cls
For x As Integer = 0 To (radius * 2) - 1
For y As Integer = 0 To (radius * 2) - 1
dx = x - radius
dy = radius - y
dist = Sqr(dx * dx + dy * dy)
If dist < radius Then
angle = Atan2(dy, dx) * (180/pi)
If angle < 0 Then angle += 360
If angle > 360 Then angle -= 360
HSVtoRGB(angle, (dist / radius) * 255, 255, r, g, b)
Pset(x, y), Rgb(r, g, b)
End If
Next y
Next x
Screenunlock
Loop Until Inkey = Chr(27) |
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.
| #Logo | Logo | if :x < 0 [make "x 0 - :x]
ifelse emptyp :list [print [empty]] [print :list] |
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.)
| #Nanoquery | Nanoquery | // this is 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.)
| #NATURAL | NATURAL | * This is a comment and extends to the end of the line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.