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/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Python
|
Python
|
import random
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)]
if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
break
def populate_board(brd, wp, bp):
for x in range(2):
if x == 0:
piece_amount = wp
pieces = piece_list
else:
piece_amount = bp
pieces = [s.lower() for s in piece_list]
while piece_amount != 0:
piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
piece = random.choice(pieces)
if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
brd[piece_rank][piece_file] = piece
piece_amount -= 1
def fen_from_board(brd):
fen = ""
for x in brd:
n = 0
for y in x:
if y == " ":
n += 1
else:
if n != 0:
fen += str(n)
fen += y
n = 0
if n != 0:
fen += str(n)
fen += "/" if fen.count("/") < 7 else ""
fen += " w - - 0 1\n"
return fen
def pawn_on_promotion_square(pc, pr):
if pc == "P" and pr == 0:
return True
elif pc == "p" and pr == 7:
return True
return False
def start():
piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
place_kings(board)
populate_board(board, piece_amount_white, piece_amount_black)
print(fen_from_board(board))
for x in board:
print(x)
#entry point
start()
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Fortran
|
Fortran
|
!-----------------------------------------------------------------------
! gjinv - Invert a matrix, Gauss-Jordan algorithm
! A is destroyed.
!
!___Name_______Type_______________In/Out____Description_________________
! A(LDA,N) Real In An N by N matrix
! LDA Integer In Row bound of A
! N Integer In Order of matrix
! B(LDB,N) Real Out Inverse of A
! LDB Integer In Row bound of B
! IERR Integer Out 0 = no errors
! 1 = singular matrix
!-----------------------------------------------------------------------
SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR)
IMPLICIT NONE
INTEGER LDA, N, LDB, IERR
REAL A(LDA,N), B(LDB,N)
REAL EPS ! machine constant
PARAMETER (EPS = 1.1920929E-07)
INTEGER I, J, K, P ! local variables
REAL F, TOL
!-----------------------------------------------------------------------
! Begin.
!-----------------------------------------------------------------------
IF (N < 1) THEN ! Validate.
IERR = -1
RETURN
ELSE IF (N > LDA .OR. N > LDB) THEN
IERR = -2
RETURN
END IF
IERR = 0
F = 0. ! Frobenius norm of A
DO J = 1, N
DO I = 1, N
F = F + A(I,J)**2
END DO
END DO
F = SQRT(F)
TOL = F * EPS
DO J = 1, N ! Set B to identity matrix.
DO I = 1, N
IF (I .EQ. J) THEN
B(I,J) = 1.
ELSE
B(I,J) = 0.
END IF
END DO
END DO
! Main loop
DO K = 1, N
F = ABS(A(K,K)) ! Find pivot.
P = K
DO I = K+1, N
IF (ABS(A(I,K)) > F) THEN
F = ABS(A(I,K))
P = I
END IF
END DO
IF (F < TOL) THEN ! Matrix is singular.
IERR = 1
RETURN
END IF
IF (P .NE. K) THEN ! Swap rows.
DO J = K, N
F = A(K,J)
A(K,J) = A(P,J)
A(P,J) = F
END DO
DO J = 1, N
F = B(K,J)
B(K,J) = B(P,J)
B(P,J) = F
END DO
END IF
F = 1. / A(K,K) ! Scale row so pivot is 1.
DO J = K, N
A(K,J) = A(K,J) * F
END DO
DO J = 1, N
B(K,J) = B(K,J) * F
END DO
DO 10 I = 1, N ! Subtract to get zeros.
IF (I .EQ. K) GO TO 10
F = A(I,K)
DO J = K, N
A(I,J) = A(I,J) - A(K,J) * F
END DO
DO J = 1, N
B(I,J) = B(I,J) - B(K,J) * F
END DO
10 CONTINUE
END DO
RETURN
END ! of gjinv
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Common_Lisp
|
Common Lisp
|
(defun fizzbuzz (limit factor-words)
(loop for i from 1 to limit
if (assoc-if #'(lambda (factor) (zerop (mod i factor))) factor-words)
do (loop for (factor . word) in factor-words
when (zerop (mod i factor)) do (princ word)
finally (fresh-line))
else do (format t "~a~%" i)))
(defun read-factors (&optional factor-words)
(princ "> ")
(let ((input (read-line t nil)))
(cond ((zerop (length input))
(sort factor-words #'< :key #'car))
((digit-char-p (char input 0))
(multiple-value-bind (n i) (parse-integer input :junk-allowed t)
(read-factors (acons n (string-trim " " (subseq input i))
factor-words))))
(t (write-line "Invalid input.")
(read-factors factor-words)))))
(defun main ()
(loop initially (princ "> ")
for input = (read-line t nil)
until (and (> (length input) 0)
(digit-char-p (char input 0))
(not (zerop (parse-integer input :junk-allowed t))))
finally (fizzbuzz (parse-integer input :junk-allowed t) (read-factors))))
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Ursa
|
Ursa
|
import "math"
def hailstone (int n)
decl int<> seq
while (> n 1)
append n seq
if (= (mod n 2) 0)
set n (floor (/ n 2))
else
set n (int (+ (* 3 n) 1))
end if
end while
append n seq
return seq
end hailstone
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Bracmat
|
Bracmat
|
a:?seq:?c
& whl
' ( chr$(asc$!c+1):~>z:?c
& !seq !c:?seq
)
& !seq
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Nyquist
|
Nyquist
|
(format t "Hello world!")
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Ursala
|
Ursala
|
pmgs("x","y") = ("y","x") # the pattern matching way
ugs = ~&rlX # the idiosyncratic Ursala way
#cast %sWL
test = <pmgs ('a','b'),ugs ('x','y')>
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#V
|
V
|
[swap [a b : b a] view].
1 2 swap
= 2 1
'hello' 'hi' swap
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#FunL
|
FunL
|
def powers( m ) = map( (^ m), 0.. )
def
filtered( s@sh:_, ch:ct ) | sh > ch = filtered( s, ct )
filtered( sh:st, c@ch:_ ) | sh < ch = sh # filtered( st, c )
filtered( _:st, c ) = filtered( st, c )
println( filtered(powers(2), powers(3)).drop(20).take(10) )
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#TSE_SAL
|
TSE SAL
|
// library: math: get: greatest: common: divisor <description>greatest common divisor whole numbers. Euclid's algorithm. Recursive version</description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmacdi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 14:22:41]
INTEGER PROC FNMathGetGreatestCommonDivisorI( INTEGER x1I, INTEGER x2I )
//
IF ( x2I == 0 )
//
RETURN( x1I )
//
ENDIF
//
RETURN( FNMathGetGreatestCommonDivisorI( x2I, x1I MOD x2I ) )
//
END
PROC Main()
STRING s1[255] = "353"
STRING s2[255] = "46"
REPEAT
IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
IF ( NOT ( Ask( " = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
Warn( FNMathGetGreatestCommonDivisorI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 1
UNTIL FALSE
END
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#TXR
|
TXR
|
$ txr -p '(gcd (expt 2 123) (expt 6 49))'
562949953421312
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#J
|
J
|
row0=: u: 9812+2}.5|i.10
king=: u:9812
rook=: u:9814
bish=: u:9815
pos=: I.@e.
bishok=: 1=2+/ .| pos&bish
rookok=: pos&rook -: (<./,>./)@pos&(rook,king)
ok=: bishok*rookok
perm=: A.&i.~ !
valid=: (#~ ok"1) ~.row0{"1~perm 8
gen=: valid {~ ? bind 960
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Java
|
Java
|
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Chess960{
private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');
public static List<Character> generateFirstRank(){
do{
Collections.shuffle(pieces);
}while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); //List.toString adds some human stuff, remove that
return pieces;
}
private static boolean check(String rank){
if(!rank.matches(".*R.*K.*R.*")) return false; //king between rooks
if(!rank.matches(".*B(..|....|......|)B.*")) return false; //all possible ways bishops can be placed
return true;
}
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.println(generateFirstRank());
}
}
}
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Aime
|
Aime
|
integer f0(void); # No arguments
void f1(integer, real); # Two arguments
real f2(...); # Varargs
void f3(integer, ...); # Varargs
void f4(integer &, text &); # Two arguments (integer and string), pass by reference
integer f5(integer, integer (*)(integer));
# Two arguments: integer and function returning integer and taking one integer argument
integer f6(integer a, real b); # Parameters names are allowed
record f7(void); # Function returning an associative array
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#ALGOL_68
|
ALGOL 68
|
#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# An explanation of any placement restrictions for prototype declarations #
PROC VOID no args; # Declare a function with no argument that returns an INTeger #
PROC (INT #a#,INT #b#)VOID two args; # Declare a function with two arguments that returns an INTeger #
MODE VARARGS = UNION(INT,REAL,COMPL);
PROC ([]VARARGS)VOID var args; # An empty parameter list can be used to declare a function that accepts varargs #
PROC (INT, []VARARGS)VOID at least one args; # One mandatory INTeger argument followed by varargs #
MODE OPTINT = UNION(VOID,INT), OPTSTRING=UNION(VOID,STRING); # a function that utilizes optional arguments #
PROC (OPTINT, OPTSTRING)VOID optional arguments;
# A prototype declaration for a function that utilizes named parameters #
MODE KWNAME = STRUCT(STRING name),
KWSPECIES = STRUCT(STRING species),
KWBREED = STRUCT(STRING breed),
OWNER=STRUCT(STRING first name, middle name, last name);
# due to the "Yoneda ambiguity" simple arguments must have an unique operator defined #
OP NAME = (STRING name)KWNAME: (KWNAME opt; name OF opt := name; opt),
SPECIES = (STRING species)KWSPECIES: (KWSPECIES opt; species OF opt := species; opt),
BREED = (STRING breed)KWBREED: (KWBREED opt; breed OF opt := breed; opt);
PROC ([]UNION(KWNAME,KWSPECIES,KWBREED,OWNER) #options#)VOID print pet;
# subroutines, and fuctions are procedures, so have the same prototype declarations #
# An explanation and example of any special forms of prototyping not covered by the above: #
COMMENT
If a function has no arguments, eg f,
then it is not requied to pass it a "vacuum()" to call it, eg "f()" not correct!
Rather is can be called without the () vacuum. eg "f"
A GOTO "label" is equivalent to "PROC VOID label".
END COMMENT
SKIP
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Clojure
|
Clojure
|
(defn first-digit [n] (Integer/parseInt (subs (str n) 0 1)))
(defn last-digit [n] (mod n 10))
(defn bookend-number [n] (+ (* 10 (first-digit n)) (last-digit n)))
(defn is-gapful? [n] (and (>= n 100) (zero? (mod n (bookend-number n)))))
(defn gapful-from [n] (filter is-gapful? (iterate inc n)))
(defn gapful [] (gapful-from 1))
(defn gapfuls-in-range [start size] (take size (gapful-from start)))
(defn report-range [[start size]]
(doall (map println
[(format "First %d gapful numbers >= %d:" size start)
(gapfuls-in-range start size)
""])))
(doall (map report-range [ [1 30] [1000000 15] [1000000000 10] ]))
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))
void swap_row(double *a, double *b, int r1, int r2, int n)
{
double tmp, *p1, *p2;
int i;
if (r1 == r2) return;
for (i = 0; i < n; i++) {
p1 = mat_elem(a, r1, i, n);
p2 = mat_elem(a, r2, i, n);
tmp = *p1, *p1 = *p2, *p2 = tmp;
}
tmp = b[r1], b[r1] = b[r2], b[r2] = tmp;
}
void gauss_eliminate(double *a, double *b, double *x, int n)
{
#define A(y, x) (*mat_elem(a, y, x, n))
int i, j, col, row, max_row,dia;
double max, tmp;
for (dia = 0; dia < n; dia++) {
max_row = dia, max = A(dia, dia);
for (row = dia + 1; row < n; row++)
if ((tmp = fabs(A(row, dia))) > max)
max_row = row, max = tmp;
swap_row(a, b, dia, max_row, n);
for (row = dia + 1; row < n; row++) {
tmp = A(row, dia) / A(dia, dia);
for (col = dia+1; col < n; col++)
A(row, col) -= tmp * A(dia, col);
A(row, dia) = 0;
b[row] -= tmp * b[dia];
}
}
for (row = n - 1; row >= 0; row--) {
tmp = b[row];
for (j = n - 1; j > row; j--)
tmp -= x[j] * A(row, j);
x[row] = tmp / A(row, row);
}
#undef A
}
int main(void)
{
double a[] = {
1.00, 0.00, 0.00, 0.00, 0.00, 0.00,
1.00, 0.63, 0.39, 0.25, 0.16, 0.10,
1.00, 1.26, 1.58, 1.98, 2.49, 3.13,
1.00, 1.88, 3.55, 6.70, 12.62, 23.80,
1.00, 2.51, 6.32, 15.88, 39.90, 100.28,
1.00, 3.14, 9.87, 31.01, 97.41, 306.02
};
double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 };
double x[6];
int i;
gauss_eliminate(a, b, x, 6);
for (i = 0; i < 6; i++)
printf("%g\n", x[i]);
return 0;
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#R
|
R
|
place_kings <- function(brd){
###
# Function that puts the two kings on the board
# and makes sure that they are not adjacent
###
while (TRUE) {
# generate positions for white and black kings
rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1)
rank_black <- sample(1:8, 1) ; file_black <- sample(1:8, 1)
# compute the differences between ranks and files
diff_vec <- c(abs(rank_white - rank_black), abs(file_white - file_black))
# if the two kings are not adjacent, place them on the board
if (sum(diff_vec) > 2 | setequal(diff_vec, c(0,2))) {
brd[rank_white, file_white] <- "K"
brd[rank_black, file_black] <- "k"
break
}
}
return(brd)
}
pawn_on_extreme_ranks <- function(pc, pr){
###
# Function that checks whether a pawn is on the first or eight rank
# (such a situation is not possible in chess)
###
if (pc %in% c("P","p") & pr %in% c(1,8))
return(TRUE)
else
return(FALSE)
}
populate_board <- function(brd, wp, bp){
###
# Function that puts pieces on the board making sure that they
# are not on the same squares, and verifying for pawn_on_extreme_ranks
###
# initialization
piece_list <- c("P", "N", "B", "R", "Q")
for (color in c("white", "black")){
# iterate for white (first) and black (after) pieces
if (color == "white"){
n_pieces = wp
pieces = piece_list
}
else {
n_pieces = bp
pieces = tolower(piece_list)
}
# place pieces one by one until we have them
while (n_pieces != 0){
piece_rank <- sample(1:8, 1) ; piece_file <- sample(1:8, 1)
piece <- sample(pieces, 1)
# check if square is empty and it is not a pawn on an extreme rank
if (brd[piece_rank, piece_file] == " " & !pawn_on_extreme_ranks(piece, piece_rank)){
brd[piece_rank, piece_file] <- piece
n_pieces <- n_pieces - 1
}
}
}
return(brd)
}
fen_from_board <- function(brd){
###
# Function that prints out the FEN of a given input board
###
# create vector of positions by row
fen <- apply(brd, 1, function(x) {
r <- rle(x)
paste(ifelse(r$values == " ", r$lengths, r$values), collapse = "")
})
# paste them together with separator '/' and add the final string
fen <- paste(paste(fen, collapse = "/"), "w - - 0 1")
return(fen)
}
generate_fen <- function(){
###
# This function calls all the functions above and generates
# the board representation along with its FEN
###
# initialization
board <- matrix(" ", nrow = 8, ncol = 8)
# generate random amount of white and black pieces (kings excluded)
n_pieces_white <- sample(0:31, 1) ; n_pieces_black <- sample(0:31, 1)
# place kings on board
board <- place_kings(board)
# put other pieces on board
board <- populate_board(board, wp = n_pieces_white, bp = n_pieces_black)
# print board and FEN
print(board)
cat("\n")
cat(fen_from_board(board))
}
generate_fen()
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#FreeBASIC
|
FreeBASIC
|
#include once "matmult.bas"
#include once "rowech.bas"
function matinv( A as Matrix ) as Matrix
dim ret as Matrix, working as Matrix
dim as uinteger i, j
if not ubound( A.m, 1 ) = ubound( A.m, 2 ) then return ret
dim as integer n = ubound(A.m, 1)
redim ret.m( n, n )
working = Matrix( n+1, 2*(n+1) )
for i = 0 to n
for j = 0 to n
working.m(i, j) = A.m(i, j)
next j
working.m(i, i+n+1) = 1
next i
working = rowech(working)
for i = 0 to n
for j = 0 to n
ret.m(i, j) = working.m(i, j+n+1)
next j
next i
return ret
end function
dim as integer i, j
dim as Matrix M = Matrix(3,3)
for i = 0 to 2
for j = 0 to 2
M.m(i, j) = 1 + i*i + 3*j + (i+j) mod 2 'just some arbitrary values
print M.m(i, j),
next j
print
next i
print
M = matinv(M)
for i = 0 to 2
for j = 0 to 2
print M.m(i, j),
next j
print
next i
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Crystal
|
Crystal
|
counter = 0
puts "Enter a maximum number:"
limit = gets
puts "Enter the first integer for factoring:"
first_int = gets
puts "Enter the name of the first integer:"
first_int_name = gets
puts "Enter the second integer for factoring:"
second_int = gets
puts "Enter the name of the second integer:"
second_int_name = gets
puts "Enter the third integer for factoring:"
third_int = gets
puts "Enter the name of the third integer:"
third_int_name = gets
if (limit &&
first_int &&
second_int &&
third_int &&
first_int_name &&
second_int_name &&
third_int_name)
limit = limit.chomp.to_i
first_int = first_int.chomp.to_i
second_int = second_int.chomp.to_i
third_int = third_int.chomp.to_i
while limit > counter
counter += 1
if (counter % first_int) == 0 && (counter % second_int) == 0 && (counter % third_int) == 0
puts first_int_name + second_int_name + third_int_name
elsif (counter % first_int) == 0 && (counter % second_int) == 0
puts first_int_name + second_int_name
elsif (counter % first_int) == 0
puts first_int_name
elsif (counter % second_int) == 0
puts second_int_name
elsif (counter % third_int) == 0
puts third_int_name
else
puts counter
end
end
else
exit
end
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Ursala
|
Ursala
|
#import std
#import nat
hail = @iNC ~&h~=1->x ^C\~& @h ~&h?\~&t successor+ sum@iNiCX
#show+
main =
<
^T(@ixX take/$4; %nLP~~lrxPX; ^|TL/~& :/'...',' has length '--@h+ %nP+ length) hail 27,
^|TL(~&,:/' has sequence length ') %nP~~ nleq$^&r ^(~&,length+ hail)* nrange/1 100000>
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Brainf.2A.2A.2A
|
Brainf***
|
Make room for 26 characters
>>>>>>>>>>>>>
>>>>>>>>>>>>>
Set counter to 26
>>
+++++++++++++
+++++++++++++
Generate the numbers 1 to 26
[-<< Decrement counter
[+<] Add one to each nonzero cell moving right to left
+ Add one to first zero cell encountered
[>]> Return head to counter
]
<<
Add 96 to each cell
[
++++++++++++++++
++++++++++++++++
++++++++++++++++
++++++++++++++++
++++++++++++++++
++++++++++++++++
<]
Print each cell
>[.>]
++++++++++. \n
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Oberon-2
|
Oberon-2
|
MODULE Goodbye;
IMPORT Out;
PROCEDURE World*;
BEGIN
Out.String("Hello world!");Out.Ln
END World;
BEGIN
World;
END Goodbye.
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#VBScript
|
VBScript
|
sub swap( byref x, byref y )
dim temp
temp = x
x = y
y = temp
end sub
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Verbexx
|
Verbexx
|
// user-defined swap verb -- parms are passed by alias, not value, so they can be updated:
'<==> [_a] @FN [_b] { _a _b = _b _a } by_alias: ;
// test out swap verb
@VAR a = 12345;
@VAR b = "*****";
@SAY "a=" a " b=" b;
\b <==> \a; // "\" verb prevents evaluation of a and b here,
// so they can be passed by alias to <==>
@SAY "a=" a " b=" b;
a b = b a; // swap them back, just using the usual = verb
@SAY "a=" a " b=" b;
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
// note: exponent not limited to ints
func newPowGen(e float64) func() float64 {
var i float64
return func() (r float64) {
r = math.Pow(i, e)
i++
return
}
}
// given two functions af, bf, both monotonically increasing, return a
// new function that returns values of af not returned by bf.
func newMonoIncA_NotMonoIncB_Gen(af, bf func() float64) func() float64 {
a, b := af(), bf()
return func() (r float64) {
for {
if a < b {
r = a
a = af()
break
}
if b == a {
a = af()
}
b = bf()
}
return
}
}
func main() {
fGen := newMonoIncA_NotMonoIncB_Gen(newPowGen(2), newPowGen(3))
for i := 0; i < 20; i++ {
fGen()
}
for i := 0; i < 10; i++ {
fmt.Print(fGen(), " ")
}
fmt.Println()
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#TypeScript
|
TypeScript
|
function gcd(a: number, b: number) {
a = Math.abs(a);
b = Math.abs(b);
if (b > a) {
let temp = a;
a = b;
b = temp;
}
while (true) {
a %= b;
if (a === 0) { return b; }
b %= a;
if (b === 0) { return a; }
}
}
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#JavaScript
|
JavaScript
|
function ch960startPos() {
var rank = new Array(8),
// randomizer (our die)
d = function(num) { return Math.floor(Math.random() * ++num) },
emptySquares = function() {
var arr = [];
for (var i = 0; i < 8; i++) if (rank[i] == undefined) arr.push(i);
return arr;
};
// place one bishop on any black square
rank[d(2) * 2] = "♗";
// place the other bishop on any white square
rank[d(2) * 2 + 1] = "♗";
// place the queen on any empty square
rank[emptySquares()[d(5)]] = "♕";
// place one knight on any empty square
rank[emptySquares()[d(4)]] = "♘";
// place the other knight on any empty square
rank[emptySquares()[d(3)]] = "♘";
// place the rooks and the king on the squares left, king in the middle
for (var x = 1; x <= 3; x++) rank[emptySquares()[0]] = x==2 ? "♔" : "♖";
return rank;
}
// testing (10 times)
for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Amazing_Hopper
|
Amazing Hopper
|
#!/usr/bin/hopper
// Archivo Hopper
#include <hopper.h>
#context-free noargs /* Declare a pseudo-function with no argument */
#synon noargs no arguments
#context multiargs /* Declare a pseudo-function with multi arguments */
#proto twoargs(_X_,_Y_) /* Declare a pseudo-function with two arguments. #PROTO need arguments */
main:
no arguments
_two args(2,2) // pseudo-function #proto need "_" sufix
println
{1,2,3,"hola mundo!","\n"}, multiargs
exit(0)
.locals
multiargs:
_PARAMS_={},pushall(_PARAMS_)
[1:3]get(_PARAMS_),stats(SUMMATORY),println
{"Mensaje: "}[4:5]get(_PARAMS_),println
clear(_PARAMS_)
back
twoargs(a,b)
{a}mulby(b)
back
// This function is as useful a s an ashtray on a motorcycle:
no args:
{0}minus(0),kill
back
{0}return
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#C
|
C
|
int noargs(void); /* Declare a function with no argument that returns an integer */
int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */
int twoargs(int ,int); /* Parameter names are optional in a prototype definition */
int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */
int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#C.23
|
C#
|
using System;
abstract class Printer
{
public abstract void Print();
}
class PrinterImpl : Printer
{
public override void Print() {
Console.WriteLine("Hello world!");
}
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#11l
|
11l
|
V _a = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108,
-0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675,
-0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511,
-0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824,
-0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776,
0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049,
0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562,
0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812,
0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119,
0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002
]
F gamma(x)
V y = x - 1.0
V sm = :_a.last
L(n) (:_a.len-2 .. 0).step(-1)
sm = sm * y + :_a[n]
R 1.0 / sm
L(i) 1..10
print(‘#.14’.format(gamma(i / 3.0)))
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. GAPFUL.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPUTATION.
02 N PIC 9(10).
02 N-DIGITS REDEFINES N.
03 ND PIC 9 OCCURS 10 TIMES.
02 DIV-CHECK PIC 9(10)V9(2).
02 DIV-PARTS REDEFINES DIV-CHECK.
03 DIV-INT PIC 9(10).
03 DIV-FRAC PIC 9(2).
02 GAP-AMOUNT PIC 99.
02 GAP-DSOR PIC 99.
02 FIRST-DIGIT PIC 99.
01 OUTPUT-FORMAT.
02 N-OUT PIC Z(10).
PROCEDURE DIVISION.
BEGIN.
DISPLAY "First 30 gapful numbers >= 100:".
MOVE 100 TO N. MOVE 30 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
DISPLAY " ".
DISPLAY "First 15 gapful numbers >= 1000000:".
MOVE 1000000 TO N. MOVE 15 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
DISPLAY " ".
DISPLAY "First 10 gapful numbers >= 1000000000:".
MOVE 1000000000 TO N. MOVE 10 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
STOP RUN.
CHECK-GAPFUL-NUMBER.
SET FIRST-DIGIT TO 1.
INSPECT N TALLYING FIRST-DIGIT FOR LEADING '0'.
COMPUTE GAP-DSOR = ND(FIRST-DIGIT) * 10 + ND(10).
DIVIDE N BY GAP-DSOR GIVING DIV-CHECK.
IF DIV-FRAC IS EQUAL TO 0
MOVE N TO N-OUT
DISPLAY N-OUT
SUBTRACT 1 FROM GAP-AMOUNT.
ADD 1 TO N.
IF GAP-AMOUNT IS GREATER THAN 0
GO TO CHECK-GAPFUL-NUMBER.
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#C.23
|
C#
|
using System;
namespace Rosetta
{
internal class Vector
{
private double[] b;
internal readonly int rows;
internal Vector(int rows)
{
this.rows = rows;
b = new double[rows];
}
internal Vector(double[] initArray)
{
b = (double[])initArray.Clone();
rows = b.Length;
}
internal Vector Clone()
{
Vector v = new Vector(b);
return v;
}
internal double this[int row]
{
get { return b[row]; }
set { b[row] = value; }
}
internal void SwapRows(int r1, int r2)
{
if (r1 == r2) return;
double tmp = b[r1];
b[r1] = b[r2];
b[r2] = tmp;
}
internal double norm(double[] weights)
{
double sum = 0;
for (int i = 0; i < rows; i++)
{
double d = b[i] * weights[i];
sum += d*d;
}
return Math.Sqrt(sum);
}
internal void print()
{
for (int i = 0; i < rows; i++)
Console.WriteLine(b[i]);
Console.WriteLine();
}
public static Vector operator-(Vector lhs, Vector rhs)
{
Vector v = new Vector(lhs.rows);
for (int i = 0; i < lhs.rows; i++)
v[i] = lhs[i] - rhs[i];
return v;
}
}
class Matrix
{
private double[] b;
internal readonly int rows, cols;
internal Matrix(int rows, int cols)
{
this.rows = rows;
this.cols = cols;
b = new double[rows * cols];
}
internal Matrix(int size)
{
this.rows = size;
this.cols = size;
b = new double[rows * cols];
for (int i = 0; i < size; i++)
this[i, i] = 1;
}
internal Matrix(int rows, int cols, double[] initArray)
{
this.rows = rows;
this.cols = cols;
b = (double[])initArray.Clone();
if (b.Length != rows * cols) throw new Exception("bad init array");
}
internal double this[int row, int col]
{
get { return b[row * cols + col]; }
set { b[row * cols + col] = value; }
}
public static Vector operator*(Matrix lhs, Vector rhs)
{
if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector");
Vector v = new Vector(lhs.rows);
for (int i = 0; i < lhs.rows; i++)
{
double sum = 0;
for (int j = 0; j < rhs.rows; j++)
sum += lhs[i,j]*rhs[j];
v[i] = sum;
}
return v;
}
internal void SwapRows(int r1, int r2)
{
if (r1 == r2) return;
int firstR1 = r1 * cols;
int firstR2 = r2 * cols;
for (int i = 0; i < cols; i++)
{
double tmp = b[firstR1 + i];
b[firstR1 + i] = b[firstR2 + i];
b[firstR2 + i] = tmp;
}
}
//with partial pivot
internal void ElimPartial(Vector B)
{
for (int diag = 0; diag < rows; diag++)
{
int max_row = diag;
double max_val = Math.Abs(this[diag, diag]);
double d;
for (int row = diag + 1; row < rows; row++)
if ((d = Math.Abs(this[row, diag])) > max_val)
{
max_row = row;
max_val = d;
}
SwapRows(diag, max_row);
B.SwapRows(diag, max_row);
double invd = 1 / this[diag, diag];
for (int col = diag; col < cols; col++)
this[diag, col] *= invd;
B[diag] *= invd;
for (int row = 0; row < rows; row++)
{
d = this[row, diag];
if (row != diag)
{
for (int col = diag; col < cols; col++)
this[row, col] -= d * this[diag, col];
B[row] -= d * B[diag];
}
}
}
}
internal void print()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
Console.Write(this[i,j].ToString()+" ");
Console.WriteLine();
}
}
}
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Raku
|
Raku
|
sub pick-FEN {
# First we chose how many pieces to place
my $n = (2..32).pick;
# Then we pick $n squares
my @n = (^64).pick($n);
# We try to find suitable king positions on non-adjacent squares.
# If we could not find any, we return recursively
return pick-FEN() unless
my @kings[2] = first -> [$a, $b] {
$a !== $b && abs($a div 8 - $b div 8) | abs($a mod 8 - $b mod 8) > 1
}, (@n X @n);
# We make a list of pieces we can pick (apart from the kings)
my @pieces = <p P n N b B r R q Q>;
# We make a list of two king symbols to pick randomly a black or white king
my @k = <K k>.pick(*);
return (gather for ^64 -> $sq {
if $sq == @kings.any { take @k.shift }
elsif $sq == @n.any {
my $row = 7 - $sq div 8;
take
$row == 7 ?? @pieces.grep(none('P')).pick !!
$row == 0 ?? @pieces.grep(none('p')).pick !!
@pieces.pick;
}
else { take 'ø' }
}).rotor(8)».join».subst(/ø+/,{ .chars }, :g).join('/') ~ ' w - - 0 1';
}
say pick-FEN();
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Generic
|
Generic
|
// The Generic Language is a database compiler. This code is compiled into database then executed out of database.
generic coordinaat
{
ecs;
uuii;
coordinaat() { ecs=+a;uuii=+a;}
coordinaat(ecs_set,uuii_set) { ecs = ecs_set; uuii=uuii_set;}
operaator<(c)
{
iph ecs < c.ecs return troo;
iph c.ecs < ecs return phals;
iph uuii < c.uuii return troo;
return phals;
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals;
iph connpair < this return phals;
return troo;
}
operaator!=(connpair)
{
iph this < connpair return troo;
iph connpair < this return troo;
return phals;
}
too_string()
{
return "(" + ecs.too_string() + "," + uuii.too_string() + ")";
}
print()
{
str = too_string();
str.print();
}
println()
{
str = too_string();
str.println();
}
}
generic nnaatrics
{
s; // this is a set of coordinaat/ualioo pairs.
iteraator; // this field holds an iteraator phor the nnaatrics.
nnaatrics() // no parameters required phor nnaatrics construction.
{
s = nioo set(); // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul; // the iteraator is initially set to nul.
}
nnaatrics(copee) // copee the nnaatrics.
{
s = nioo set(); // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul; // the iteraator is initially set to nul.
r = copee.rouus;
c = copee.cols;
i = 0;
uuiil i < r
{
j = 0;
uuiil j < c
{
this[i,j] = copee[i,j];
j++;
}
i++;
}
}
begin { get { return s.begin; } } // property: used to commence manual iteraashon.
end { get { return s.end; } } // property: used to dephiin the end itenn of iteraashon
operaator<(a) // les than operaator is corld bii the avl tree algorithnns
{ // this operaator innpliis phor instance that you could potenshalee hav sets ou nnaatricss.
iph cees < a.cees // connpair the cee sets phurst.
return troo;
els iph a.cees < cees
return phals;
els // the cee sets are eecuuol thairphor connpair nnaatrics elennents.
{
phurst1 = begin;
lahst1 = end;
phurst2 = a.begin;
lahst2 = a.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
iph phurst1.daata.ualioo < phurst2.daata.ualioo
return troo;
els
{
iph phurst2.daata.ualioo < phurst1.daata.ualioo
return phals;
els
{
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
}
}
return phals;
}
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals;
iph connpair < this return phals;
return troo;
}
operaator!=(connpair)
{
iph this < connpair return troo;
iph connpair < this return troo;
return phals;
}
operaator[](cee_a,cee_b) // this is the nnaatrics indexer.
{
set
{
trii { s >> nioo cee_ualioo(new coordinaat(cee_a,cee_b)); } catch {}
s << nioo cee_ualioo(new coordinaat(nioo integer(cee_a),nioo integer(cee_b)),ualioo);
}
get
{
d = s.get(nioo cee_ualioo(new coordinaat(cee_a,cee_b)));
return d.ualioo;
}
}
operaator>>(coordinaat) // this operaator reennoous an elennent phronn the nnaatrics.
{
s >> nioo cee_ualioo(coordinaat);
return this;
}
iteraat() // and this is how to iterate on the nnaatrics.
{
iph iteraator.nul()
{
iteraator = s.lepht_nnohst;
iph iteraator == s.heder
return nioo iteraator(phals,nioo nun());
els
return nioo iteraator(troo,iteraator.daata.ualioo);
}
els
{
iteraator = iteraator.necst;
iph iteraator == s.heder
{
iteraator = nul;
return nioo iteraator(phals,nioo nun());
}
els
return nioo iteraator(troo,iteraator.daata.ualioo);
}
}
couunt // this property returns a couunt ou elennents in the nnaatrics.
{
get
{
return s.couunt;
}
}
ennptee // is the nnaatrics ennptee?
{
get
{
return s.ennptee;
}
}
lahst // returns the ualioo of the lahst elennent in the nnaatrics.
{
get
{
iph ennptee
throuu "ennptee nnaatrics";
els
return s.lahst.ualioo;
}
}
too_string() // conuerts the nnaatrics too aa string
{
return s.too_string();
}
print() // prints the nnaatrics to the consohl.
{
out = too_string();
out.print();
}
println() // prints the nnaatrics as a liin too the consohl.
{
out = too_string();
out.println();
}
cees // return the set ou cees ou the nnaatrics (a set of coordinaats).
{
get
{
k = nioo set();
phor e : s k << e.cee;
return k;
}
}
operaator+(p)
{
ouut = nioo nnaatrics();
phurst1 = begin;
lahst1 = end;
phurst2 = p.begin;
lahst2 = p.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo + phurst2.daata.ualioo;
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
return ouut;
}
operaator-(p)
{
ouut = nioo nnaatrics();
phurst1 = begin;
lahst1 = end;
phurst2 = p.begin;
lahst2 = p.end;
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs,phurst1.daata.cee.uuii] = phurst1.daata.ualioo - phurst2.daata.ualioo;
phurst1 = phurst1.necst;
phurst2 = phurst2.necst;
}
return ouut;
}
rouus
{
get
{
r = +a;
phurst1 = begin;
lahst1 = end;
uuiil phurst1 != lahst1
{
iph r < phurst1.daata.cee.ecs r = phurst1.daata.cee.ecs;
phurst1 = phurst1.necst;
}
return r + +b;
}
}
cols
{
get
{
c = +a;
phurst1 = begin;
lahst1 = end;
uuiil phurst1 != lahst1
{
iph c < phurst1.daata.cee.uuii c = phurst1.daata.cee.uuii;
phurst1 = phurst1.necst;
}
return c + +b;
}
}
operaator*(o)
{
iph cols != o.rouus throw "rouus-cols nnisnnatch";
reesult = nioo nnaatrics();
rouu_couunt = rouus;
colunn_couunt = o.cols;
loop = cols;
i = +a;
uuiil i < rouu_couunt
{
g = +a;
uuiil g < colunn_couunt
{
sunn = +a.a;
h = +a;
uuiil h < loop
{
a = this[i, h];
b = o[h, g];
nn = a * b;
sunn = sunn + nn;
h++;
}
reesult[i, g] = sunn;
g++;
}
i++;
}
return reesult;
}
suuop_rouus(a, b)
{
c = cols;
i = 0;
uuiil u < cols
{
suuop = this[a, i];
this[a, i] = this[b, i];
this[b, i] = suuop;
i++;
}
}
suuop_colunns(a, b)
{
r = rouus;
i = 0;
uuiil i < rouus
{
suuopp = this[i, a];
this[i, a] = this[i, b];
this[i, b] = suuop;
i++;
}
}
transpohs
{
get
{
reesult = new nnaatrics();
r = rouus;
c = cols;
i=0;
uuiil i < r
{
g = 0;
uuiil g < c
{
reesult[g, i] = this[i, g];
g++;
}
i++;
}
return reesult;
}
}
deternninant
{
get
{
rouu_couunt = rouus;
colunn_count = cols;
if rouu_couunt != colunn_count
throw "not a scuuair nnaatrics";
if rouu_couunt == 0
throw "the nnaatrics is ennptee";
if rouu_couunt == 1
return this[0, 0];
if rouu_couunt == 2
return this[0, 0] * this[1, 1] -
this[0, 1] * this[1, 0];
temp = nioo nnaatrics();
det = 0.0;
parity = 1.0;
j = 0;
uuiil j < rouu_couunt
{
k = 0;
uuiil k < rouu_couunt-1
{
skip_col = phals;
l = 0;
uuiil l < rouu_couunt-1
{
if l == j skip_col = troo;
if skip_col
n = l + 1;
els
n = l;
temp[k, l] = this[k + 1, n];
l++;
}
k++;
}
det = det + parity * this[0, j] * temp.deeternninant;
parity = 0.0 - parity;
j++;
}
return det;
}
}
ad_rouu(a, b)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] + this[b, i];
i++;
}
}
ad_colunn(a, b)
{
c = rouus;
i = 0;
uuiil i < c
{
this[i, a] = this[i, a] + this[i, b];
i++;
}
}
subtract_rouu(a, b)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] - this[b, i];
i++;
}
}
subtract_colunn(a, b)
{
c = rouus;
i = 0;
uuiil i < c
{
this[i, a] = this[i, a] - this[i, b];
i++;
}
}
nnultiplii_rouu(rouu, scalar)
{
c = cols;
i = 0;
uuiil i < c
{
this[rouu, i] = this[rouu, i] * scalar;
i++;
}
}
nnultiplii_colunn(colunn, scalar)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, colunn] = this[i, colunn] * scalar;
i++;
}
}
diuiid_rouu(rouu, scalar)
{
c = cols;
i = 0;
uuiil i < c
{
this[rouu, i] = this[rouu, i] / scalar;
i++;
}
}
diuiid_colunn(colunn, scalar)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, colunn] = this[i, colunn] / scalar;
i++;
}
}
connbiin_rouus_ad(a,b,phactor)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] + phactor * this[b, i];
i++;
}
}
connbiin_rouus_subtract(a,b,phactor)
{
c = cols;
i = 0;
uuiil i < c
{
this[a, i] = this[a, i] - phactor * this[b, i];
i++;
}
}
connbiin_colunns_ad(a,b,phactor)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, a] = this[i, a] + phactor * this[i, b];
i++;
}
}
connbiin_colunns_subtract(a,b,phactor)
{
r = rouus;
i = 0;
uuiil i < r
{
this[i, a] = this[i, a] - phactor * this[i, b];
i++;
}
}
inuers
{
get
{
rouu_couunt = rouus;
colunn_couunt = cols;
iph rouu_couunt != colunn_couunt
throw "nnatrics not scuuair";
els iph rouu_couunt == 0
throw "ennptee nnatrics";
els iph rouu_couunt == 1
{
r = nioo nnaatrics();
r[0, 0] = 1.0 / this[0, 0];
return r;
}
gauss = nioo nnaatrics(this);
i = 0;
uuiil i < rouu_couunt
{
j = 0;
uuiil j < rouu_couunt
{
iph i == j
gauss[i, j + rouu_couunt] = 1.0;
els
gauss[i, j + rouu_couunt] = 0.0;
j++;
}
i++;
}
j = 0;
uuiil j < rouu_couunt
{
iph gauss[j, j] == 0.0
{
k = j + 1;
uuiil k < rouu_couunt
{
if gauss[k, j] != 0.0 {gauss.nnaat.suuop_rouus(j, k); break; }
k++;
}
if k == rouu_couunt throw "nnatrics is singioolar";
}
phactor = gauss[j, j];
iph phactor != 1.0 gauss.diuiid_rouu(j, phactor);
i = j+1;
uuiil i < rouu_couunt
{
gauss.connbiin_rouus_subtract(i, j, gauss[i, j]);
i++;
}
j++;
}
i = rouu_couunt - 1;
uuiil i > 0
{
k = i - 1;
uuiil k >= 0
{
gauss.connbiin_rouus_subtract(k, i, gauss[k, i]);
k--;
}
i--;
}
reesult = nioo nnaatrics();
i = 0;
uuiil i < rouu_couunt
{
j = 0;
uuiil j < rouu_couunt
{
reesult[i, j] = gauss[i, j + rouu_couunt];
j++;
}
i++;
}
return reesult;
}
}
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#D
|
D
|
import core.stdc.stdlib;
import std.stdio;
void main() {
int limit;
write("Max number (>0): ");
readf!"%d\n"(limit);
if (limit <= 0) {
writeln("The max number to consider must be greater than zero.");
exit(1);
}
int terms;
write("Terms (>0): ");
readf!"%d\n"(terms);
if (terms <= 0) {
writeln("The number of terms to consider must be greater than zero.");
exit(1);
}
int[] factors = new int[terms];
string[] words = new string[terms];
for (int i=0; i<terms; ++i) {
write("Factor ", i+1, " and word: ");
readf!"%d %s\n"(factors[i], words[i]);
if (factors[i] <= 0) {
writeln("The factor to consider must be greater than zero.");
exit(1);
}
}
foreach(n; 1..limit+1) {
bool print = true;
for (int i=0; i<terms; ++i) {
if (n % factors[i] == 0) {
write(words[i]);
print = false;
}
}
if (print) {
writeln(n);
} else {
writeln();
}
}
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#VBA
|
VBA
|
Private Function hailstone(ByVal n As Long) As Collection
Dim s As New Collection
s.Add CStr(n), CStr(n)
i = 0
Do While n <> 1
If n Mod 2 = 0 Then
n = n / 2
Else
n = 3 * n + 1
End If
s.Add CStr(n), CStr(n)
Loop
Set hailstone = s
End Function
Private Function hailstone_count(ByVal n As Long)
Dim count As Long: count = 1
Do While n <> 1
If n Mod 2 = 0 Then
n = n / 2
Else
n = 3 * n + 1
End If
count = count + 1
Loop
hailstone_count = count
End Function
Public Sub rosetta()
Dim s As Collection, i As Long
Set s = hailstone(27)
Dim ls As Integer: ls = s.count
Debug.Print "hailstone(27) = ";
For i = 1 To 4
Debug.Print s(i); ", ";
Next i
Debug.Print "... ";
For i = s.count - 4 To s.count - 1
Debug.Print s(i); ", ";
Next i
Debug.Print s(s.count)
Debug.Print "length ="; ls
Dim hmax As Long: hmax = 1
Dim imax As Long: imax = 1
Dim count As Integer
For i = 2 To 100000# - 1
count = hailstone_count(i)
If count > hmax Then
hmax = count
imax = i
End If
Next i
Debug.Print "The longest hailstone sequence under 100,000 is"; imax; "with"; hmax; "elements."
End Sub
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Burlesque
|
Burlesque
|
blsq ) @azr\sh
abcdefghijklmnopqrstuvwxyz
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#C
|
C
|
#include <stdlib.h>
#define N 26
int main() {
unsigned char lower[N];
for (size_t i = 0; i < N; i++) {
lower[i] = i + 'a';
}
return EXIT_SUCCESS;
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Objeck
|
Objeck
|
class Hello {
function : Main(args : String[]) ~ Nil {
"Hello world!"->PrintLine();
}
}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Visual_Basic
|
Visual Basic
|
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim temp = a
a = b
b = temp
End Sub
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Haskell
|
Haskell
|
import Data.List.Ordered
powers :: Int -> [Int]
powers m = map (^ m) [0..]
squares :: [Int]
squares = powers 2
cubes :: [Int]
cubes = powers 3
foo :: [Int]
foo = filter (not . has cubes) squares
main :: IO ()
main = print $ take 10 $ drop 20 foo
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#uBasic.2F4tH
|
uBasic/4tH
|
Print "GCD of 18 : 12 = "; FUNC(_GCD_Iterative_Euclid(18,12))
Print "GCD of 1071 : 1029 = "; FUNC(_GCD_Iterative_Euclid(1071,1029))
Print "GCD of 3528 : 3780 = "; FUNC(_GCD_Iterative_Euclid(3528,3780))
End
_GCD_Iterative_Euclid Param(2)
Local (1)
Do While b@
c@ = a@
a@ = b@
b@ = c@ % b@
Loop
Return (Abs(a@))
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#UNIX_Shell
|
UNIX Shell
|
gcd() {
# Calculate $1 % $2 until $2 becomes zero.
until test 0 -eq "$2"; do
# Parallel assignment: set -- 1 2
set -- "$2" "`expr "$1" % "$2"`"
done
# Echo absolute value of $1.
test 0 -gt "$1" && set -- "`expr 0 - "$1"`"
echo "$1"
}
gcd -47376 87843
# => 987
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Julia
|
Julia
|
function generateposition()
# Placeholder knights
rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘']
lrank = length(rank)
# Check if a space is available
isfree(x::Int) = rank[x] == '♘'
# Place the King
rank[indking = rand(2:lrank-1)] = '♔'
# Place rooks
rank[indrook = rand(filter(isfree, 1:lrank))] = '♖'
if indrook > indking
rank[rand(filter(isfree, 1:indking-1))] = '♖'
else
rank[rand(filter(isfree, indking+1:lrank))] = '♖'
end
# Place bishops
rank[indbish = rand(filter(isfree, 1:8))] = '♗'
pbish = filter(iseven(indbish) ? isodd : iseven, 1:lrank)
rank[rand(filter(isfree, pbish))] = '♗'
# Place queen
rank[rand(filter(isfree, 1:lrank))] = '♕'
return rank
end
@show generateposition()
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Kotlin
|
Kotlin
|
object Chess960 : Iterable<String> {
override fun iterator() = patterns.iterator()
private operator fun invoke(b: String, e: String) {
if (e.length <= 1) {
val s = b + e
if (s.is_valid()) patterns += s
} else {
for (i in 0 until e.length) {
invoke(b + e[i], e.substring(0, i) + e.substring(i + 1))
}
}
}
private fun String.is_valid(): Boolean {
val k = indexOf('K')
return indexOf('R') < k && k < lastIndexOf('R') &&
indexOf('B') % 2 != lastIndexOf('B') % 2
}
private val patterns = sortedSetOf<String>()
init {
invoke("", "KQRRNNBB")
}
}
fun main(args: Array<String>) {
Chess960.forEachIndexed { i, s -> println("$i: $s") }
}
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#C.2B.2B
|
C++
|
int noargs(); // Declare a function with no arguments that returns an integer
int twoargs(int a,int b); // Declare a function with two arguments that returns an integer
int twoargs(int ,int); // Parameter names are optional in a prototype definition
int anyargs(...); // An ellipsis is used to declare a function that accepts varargs
int atleastoneargs(int, ...); // One mandatory integer argument followed by varargs
template<typename T> T declval(T); //A function template
template<typename ...T> tuple<T...> make_tuple(T...); //Function template using parameter pack (since c++11)
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Clojure
|
Clojure
|
(declare foo)
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#360_Assembly
|
360 Assembly
|
GAMMAT CSECT
USING GAMMAT,R13
SAVEAR B STM-SAVEAR(R15)
DC 17F'0'
DC CL8'GAMMAT'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
* ---- CODE
LE F4,=E'0'
LH R2,NI
LOOPI EQU *
AE F4,=E'1' xi=xi+1
LER F0,F4
DE F0,=E'10' x=xi/10
STE F0,X
LE F6,X
SE F6,=E'1' xx=x-1.0
LH R4,NT
BCTR R4,0
SLA R4,2
LE F0,T(R4)
STE F0,SUM sum=t(nt)
LH R3,NT
BCTR R3,0
SH R4,=H'4'
LOOPJ CH R3,=H'1' for j=nt-1 downto 1
BL ENDLOOPJ
LE F0,SUM
MER F0,F6 sum*xx
LE F2,T(R4) t(j)
AER F0,F2
STE F0,SUM sum=sum*xx+t(j)
BCTR R3,0
SH R4,=H'4'
B LOOPJ
ENDLOOPJ EQU *
LE F0,=E'1'
DE F0,SUM
STE F0,GAMMA gamma=1/sum
LE F0,X
BAL R14,CONVERT
MVC BUF(8),CONVERTM
LE F0,GAMMA
BAL R14,CONVERT
MVC BUF+9(13),CONVERTM
WTO MF=(E,WTOMSG)
BCT R2,LOOPI
* ---- END CODE
CNOP 0,4
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
* ---- DATA
NI DC H'30'
NT DC AL2((TEND-T)/4)
T DC E'1.00000000000000000000'
DC E'0.57721566490153286061'
DC E'-0.65587807152025388108'
DC E'-0.04200263503409523553'
DC E'0.16653861138229148950'
DC E'-0.04219773455554433675'
DC E'-0.00962197152787697356'
DC E'0.00721894324666309954'
DC E'-0.00116516759185906511'
DC E'-0.00021524167411495097'
DC E'0.00012805028238811619'
DC E'-0.00002013485478078824'
DC E'-0.00000125049348214267'
DC E'0.00000113302723198170'
DC E'-0.00000020563384169776'
DC E'0.00000000611609510448'
DC E'0.00000000500200764447'
DC E'-0.00000000118127457049'
DC E'0.00000000010434267117'
DC E'0.00000000000778226344'
DC E'-0.00000000000369680562'
DC E'0.00000000000051003703'
DC E'-0.00000000000002058326'
DC E'-0.00000000000000534812'
DC E'0.00000000000000122678'
DC E'-0.00000000000000011813'
DC E'0.00000000000000000119'
DC E'0.00000000000000000141'
DC E'-0.00000000000000000023'
DC E'0.00000000000000000002'
TEND DS 0E
X DS E
SUM DS E
GAMMA DS E
WTOMSG DS 0F
DC AL2(L'BUF),XL2'0000'
BUF DC CL80' '
* Subroutine Convertion Float->Display
CONVERT CNOP 0,4
ME F0,CONVERTC
STE F0,CONVERTF
MVI CONVERTS,X'00'
L R9,CONVERTF
CH R9,=H'0'
BZ CONVERT7
BNL CONVERT1 is negative?
MVI CONVERTS,X'80'
N R9,=X'7FFFFFFF' sign bit
CONVERT1 LR R8,R9
N R8,=X'00FFFFFF'
BNZ CONVERT2
SR R9,R9
B CONVERT7
CONVERT2 LR R8,R9
N R8,=X'FF000000' characteristic
SRL R8,24
CH R8,=H'64'
BH CONVERT3
SR R9,R9
B CONVERT7
CONVERT3 CH R8,=H'72' 2**32
BNH CONVERT4
L R9,=X'7FFFFFFF' biggest
B CONVERT6
CONVERT4 SR R8,R8
SLDL R8,8
CH R8,=H'72'
BL CONVERT5
CH R9,=H'0'
BP CONVERT5
L R9,=X'7FFFFFFF'
B CONVERT6
CONVERT5 SH R8,=H'72'
LCR R8,R8
SLL R8,2
SRL R9,0(R8)
CONVERT6 SR R8,R8
IC R8,CONVERTS
CH R8,=H'0' sign bit set?
BZ CONVERT7
LCR R9,R9
CONVERT7 ST R9,CONVERTB
CVD R9,CONVERTP
MVC CONVERTD,=X'402020202120202020202020'
ED CONVERTD,CONVERTP+2
MVC CONVERTM(6),CONVERTD
MVI CONVERTM+6,C'.'
MVC CONVERTM+7(6),CONVERTD+6
BR R14
*
CONVERTC DC E'1E6' X'45F42400'
CONVERTF DS F
CONVERTB DS F
CONVERTS DS X
CONVERTM DS CL13
CONVERTD DS CL12
CONVERTP DS PL8
*
EQUREGS
EQUREGS REGS=FPR
END GAMMAT
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#AutoHotkey
|
AutoHotkey
|
AutoTrim Off
; User settings
bottompegs := 6
SleepTime := 200
fallspace := 30
; create the board
out := (pad2 := Space(bottompegs*2+1)) "`n"
Loop % bottompegs
{
out .= Space(bottompegs-A_Index+1)
Loop % A_Index
out .= "* "
out .= Space(bottompegs-A_Index+1) . "`n"
}
StringTrimRight, strboard, out, 1 ; remove last newline
Loop % fallspace-1
strboard .= "`n" . pad2
strboard .= "`n"
Loop % bottompegs*2+1
strboard .= "="
; Create Gui
Gui Font, , Consolas
Gui -Caption
Gui Margin, 0, 0
Gui, Add, edit, -VScroll vE, % strboard
Gui Show
Loop
{
ballX := bottompegs+1, BallY := 1
strboard := ChangeChar(strboard, BallX, ballY, "O")
GuiControl,, E, % strboard
sleep SleepTime
; Make ball fall and bounce
Loop % bottompegs
{
strboard := ChangeChar(strboard, BallX, BallY, " ")
ballY += 1
ballX += RandAdd()
; MsgBox % ballX ", " ballY
GuiControl,, E, % strboard := ChangeChar(strboard, ballX, ballY, "O")
sleep SleepTime
}
; now fall to the bottom
While GetChar(strboard, BallX, BallY+1) = A_Space
{
strboard := ChangeChar(strboard, BallX, BallY, " ")
BallY += 1
strboard := ChangeChar(strboard, BallX, BallY, "O")
GuiControl,, E, % strboard
sleep SleepTime
}
}
~Esc::
GuiClose:
ExitApp
Space(n){
If n
return " " Space(n-1)
return ""
}
RandAdd(){
Random, n, 3, 4
return (n=3 ? -1 : 1)
}
GetChar(s, x, y){
Loop Parse, s, `n
if (A_Index = y)
return SubStr(A_LoopField, x, 1)
}
ChangeChar(s, x, y, c){
Loop Parse, s, `n
{
If (A_Index = y)
{
Loop Parse, A_LoopField
If (A_Index = x)
out .= c
else out .= A_LoopField
}
else out .= A_LoopField
out .= "`n"
}
StringTrimRight, out, out, 1 ; removes the last newline
return out
}
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Commodore_BASIC
|
Commodore BASIC
|
100 DEF FNFD(N) = VAL(MID$(STR$(N),2,1))
110 DEF FNLD(N) = N - 10 * INT(N/10)
120 DEF FNBE(N) = 10 * FNFD(N) + FNLD(N)
130 DEF FNGF(N) = (N >= 100) AND (N - FNBE(N)*INT(N/FNBE(N)) = 0)
140 READ S:IF S<0 THEN 260
150 READ C
160 PRINT"THE FIRST"C"GAPFUL NUMBERS >="S":"
170 I=S:F=0
180 IF NOT FNGF(I) THEN 220
190 PRINT I,
200 F=F+1
210 IF F>=C THEN 240
220 I=I+1
230 GOTO 180
240 PRINT:PRINT
250 GOTO 140
260 END
270 DATA 1,30, 1000000,15, 100000000,10
280 DATA -1
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
auto i = elements_.begin();
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), i);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) {
size_t columns = m.columns();
for (size_t k = 0; k < columns; ++k)
std::swap(m(i, k), m(j, k));
}
template <typename scalar_type>
std::vector<scalar_type> gauss_partial(const matrix<scalar_type>& a0,
const std::vector<scalar_type>& b0) {
size_t n = a0.rows();
assert(a0.columns() == n);
assert(b0.size() == n);
// make augmented matrix
matrix<scalar_type> a(n, n + 1);
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j)
a(i, j) = a0(i, j);
a(i, n) = b0[i];
}
// WP algorithm from Gaussian elimination page
// produces row echelon form
for (size_t k = 0; k < n; ++k) {
// Find pivot for column k
size_t max_index = k;
scalar_type max_value = 0;
for (size_t i = k; i < n; ++i) {
// compute scale factor = max abs in row
scalar_type scale_factor = 0;
for (size_t j = k; j < n; ++j)
scale_factor = std::max(std::abs(a(i, j)), scale_factor);
if (scale_factor == 0)
continue;
// scale the abs used to pick the pivot
scalar_type abs = std::abs(a(i, k))/scale_factor;
if (abs > max_value) {
max_index = i;
max_value = abs;
}
}
if (a(max_index, k) == 0)
throw std::runtime_error("matrix is singular");
if (k != max_index)
swap_rows(a, k, max_index);
for (size_t i = k + 1; i < n; ++i) {
scalar_type f = a(i, k)/a(k, k);
for (size_t j = k + 1; j <= n; ++j)
a(i, j) -= a(k, j) * f;
a(i, k) = 0;
}
}
// now back substitute to get result
std::vector<scalar_type> x(n);
for (size_t i = n; i-- > 0; ) {
x[i] = a(i, n);
for (size_t j = i + 1; j < n; ++j)
x[i] -= a(i, j) * x[j];
x[i] /= a(i, i);
}
return x;
}
int main() {
matrix<double> a(6, 6, {
{1.00, 0.00, 0.00, 0.00, 0.00, 0.00},
{1.00, 0.63, 0.39, 0.25, 0.16, 0.10},
{1.00, 1.26, 1.58, 1.98, 2.49, 3.13},
{1.00, 1.88, 3.55, 6.70, 12.62, 23.80},
{1.00, 2.51, 6.32, 15.88, 39.90, 100.28},
{1.00, 3.14, 9.87, 31.01, 97.41, 306.02}
});
std::vector<double> b{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02};
std::vector<double> x{-0.01, 1.602790394502114, -1.6132030599055613,
1.2454941213714368, -0.4909897195846576, 0.065760696175232};
std::vector<double> y(gauss_partial(a, b));
std::cout << std::setprecision(16);
const double epsilon = 1e-14;
for (size_t i = 0; i < y.size(); ++i) {
assert(std::abs(x[i] - y[i]) <= epsilon);
std::cout << y[i] << '\n';
}
return 0;
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#REXX
|
REXX
|
/*REXX program generates a chess position (random pieces & positions) in a FEN format.*/
parse arg seed CBs . /*obtain optional arguments from the CL*/
if datatype(seed,'W') then call random ,,seed /*SEED given for RANDOM repeatability? */
if CBs=='' | CBs=="," then CBs=1 /*CBs: number of generated ChessBoards*/
/* [↓] maybe display any # of boards. */
do boards=1 for abs(CBs) /* [↓] maybe display separator & title*/
if sign(CBs)\==CBs then do; say; say center(' board' boards" ", 79, '▒'); end
@.=.; !.=@. /*initialize the chessboard to be empty*/
do p=1 for random(2, 32) /*generate a random number of chessmen.*/
if p<3 then call piece 'k' /*a king of each color. */
else call piece substr('bnpqr', random(1, 5), 1)
end /*p*/ /* [↑] place a piece on the chessboard*/
call cb /*display the ChessBoard and its FEN.*/
end /*boards*/ /* [↑] CB ≡ ─ ─ */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cb: fen=; do r=8 for 8 by -1; $= /*the board rank (so far).*/
do f=8 for 8 by -1; $= $ || @.r.f /*append the board file. */
end /*f*/
say $ /*display the board rank. */
do e=8 for 8 by -1; $= changestr( copies(., e), $, e) /* . ≡ filler.*/
end /*e*/
fen= fen || $ || left('/', r\==1) /*append / if not 1st rank.*/
end /*r*/ /* [↑] append $ str to FEN*/
say /*display a blank sep. line*/
say 'FEN='fen "w - - 0 1" /*Forsyth─Edwards Notation.*/
return /* [↑] display chessboard.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
piece: parse arg x; if p//2 then upper x; arg ux /*use white if odd P.*/
if CBs<0 & p>2 then if random(1) then upper x /*CBs>0? Use balanced.*/
/*[↓] # isn't changed.*/
do #=0 by 0; r= random(1, 8); f= random(1, 8) /*random rank and file.*/
if @.r.f\==. then iterate /*is position occupied?*/
if (x=='p' & r==1) | (x=="P" & r==8) then iterate /*any promoting pawn? */
/*[↑] skip these pawns*/
if ux=='K' then do rr=r-1 for 3 /*[↓] neighbor ≡ king?*/
do ff=f-1 for 3; if !.rr.ff=='K' then iterate # /*king?*/
end /*rr*/ /*[↑] neighbor ≡ king?*/
end /*ff*/ /*[↑] we're all done. */
@.r.f= x /*put random piece. */
!.r.f= ux; return /* " " " upper*/
end /*#*/ /*#: isn't incremented.*/
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Go
|
Go
|
package main
import "fmt"
type vector = []float64
type matrix []vector
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
// augment by identity matrix to right
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
// remove identity matrix to left
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
// note: this mutates the matrix in place
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func (m matrix) print(title string) {
fmt.Println(title)
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}
a.inverse().print("Inverse of A is:\n")
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Elixir
|
Elixir
|
defmodule General do
def fizzbuzz(input) do
[num | nwords] = String.split(input)
max = String.to_integer(num)
dict = Enum.chunk(nwords, 2) |> Enum.map(fn[n,word] -> {String.to_integer(n),word} end)
Enum.each(1..max, fn i ->
str = Enum.map_join(dict, fn {n,word} -> if rem(i,n)==0, do: word end)
IO.puts if str=="", do: i, else: str
end)
end
end
input = """
105
3 Fizz
5 Buzz
7 Baxx
"""
General.fizzbuzz(input)
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Erlang
|
Erlang
|
%%% @doc Implementation of General FizzBuzz
%%% @see https://rosettacode.org/wiki/General_FizzBuzz
-module(general_fizzbuzz).
-export([run/2]).
-spec run(N :: pos_integer(), Factors :: list(tuple())) -> ok.
fizzbuzz(N, [], []) ->
integer_to_list(N);
fizzbuzz(_, [], Result) ->
lists:flatten(lists:reverse(Result));
fizzbuzz(N, Factors, Result) ->
[{Factor, Output}|FactorsRest] = Factors,
NextResult = case N rem Factor of
0 -> [Output|Result];
_ -> Result
end,
fizzbuzz(N, FactorsRest, NextResult).
run(N, Factors) ->
lists:foreach(
fun(S) -> io:format("~s~n", [S]) end,
[fizzbuzz(X, Factors, []) || X <- lists:seq(1, N)]
).
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#VBScript
|
VBScript
|
'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or
'"e" for the number elements.
Function hailstone_sequence(num,return)
n = num
sequence = num
elements = 1
Do Until n = 1
If n Mod 2 = 0 Then
n = n / 2
Else
n = (3 * n) + 1
End If
sequence = sequence & " " & n
elements = elements + 1
Loop
Select Case return
Case "s"
hailstone_sequence = sequence
Case "e"
hailstone_sequence = elements
End Select
End Function
'test driving.
'show sequence for 27
WScript.StdOut.WriteLine "Sequence for 27: " & hailstone_sequence(27,"s")
WScript.StdOut.WriteLine "Number of Elements: " & hailstone_sequence(27,"e")
WScript.StdOut.WriteBlankLines(1)
'show the number less than 100k with the longest sequence
count = 1
n_elements = 0
n_longest = ""
Do While count < 100000
current_n_elements = hailstone_sequence(count,"e")
If current_n_elements > n_elements Then
n_elements = current_n_elements
n_longest = "Number: " & count & " Length: " & n_elements
End If
count = count + 1
Loop
WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: "
WScript.StdOut.WriteLine n_longest
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#C.23
|
C#
|
using System;
using System.Linq;
internal class Program
{
private static void Main()
{
Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c)));
}
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
int main() {
@autoreleasepool {
NSLog(@"Hello, World!");
}
}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim temp = a
a = b
b = temp
End Sub
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Visual_FoxPro
|
Visual FoxPro
|
Since Visual FoxPro is not strongly typed, this will work with any data types.
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
write("Non-cube Squares (21st to 30th):")
every (k := 0, s := noncubesquares()) do
if(k +:= 1) > 30 then break
else write(20 < k," : ",s)
end
procedure mthpower(m) #: generate i^m for i = 0,1,...
while (/i := 0) | (i +:= 1) do suspend i^m
end
procedure noncubesquares() #: filter for squares that aren't cubes
cu := create mthpower(3) # co-expressions so that we can
sq := create mthpower(2) # ... get our results where we need
repeat {
if c === s then ( c := @cu , s := @sq )
else if s > c then c := @cu
else {
suspend s
s := @sq
}
}
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Ursa
|
Ursa
|
import "math"
out (gcd 40902 24140) endl console
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Ursala
|
Ursala
|
#import nat
gcd = ~&B?\~&Y ~&alh^?\~&arh2faltPrXPRNfabt2RCQ @a ~&ar^?\~&al ^|R/~& ^/~&r remainder
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Lua
|
Lua
|
-- Insert 'str' into 't' at a random position from 'left' to 'right'
function randomInsert (t, str, left, right)
local pos
repeat pos = math.random(left, right) until not t[pos]
t[pos] = str
return pos
end
-- Generate a random Chess960 start position for white major pieces
function chess960 ()
local t, b1, b2 = {}
local kingPos = randomInsert(t, "K", 2, 7)
randomInsert(t, "R", 1, kingPos - 1)
randomInsert(t, "R", kingPos + 1, 8)
b1 = randomInsert(t, "B", 1, 8)
b2 = randomInsert(t, "B", 1, 8)
while (b2 - b1) % 2 == 0 do
t[b2] = false
b2 = randomInsert(t, "B", 1, 8)
end
randomInsert(t, "Q", 1, 8)
randomInsert(t, "N", 1, 8)
randomInsert(t, "N", 1, 8)
return t
end
-- Main procedure
math.randomseed(os.time())
print(table.concat(chess960()))
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#COBOL
|
COBOL
|
*> A subprogram taking no arguments and returning nothing.
PROGRAM-ID. no-args PROTOTYPE.
END PROGRAM no-args.
*> A subprogram taking two 8-digit numbers as arguments, and returning
*> an 8-digit number.
PROGRAM-ID. two-args PROTOTYPE.
DATA DIVISION.
LINKAGE SECTION.
01 arg-1 PIC 9(8).
01 arg-2 PIC 9(8).
01 ret PIC 9(8).
PROCEDURE DIVISION USING arg-1, arg-2 RETURNING ret.
END PROGRAM two-args.
*> A subprogram taking two optional arguments which are 8-digit
*> numbers (passed by reference (the default and compulsory for
*> optional arguments)).
PROGRAM-ID. optional-args PROTOTYPE.
DATA DIVISION.
LINKAGE SECTION.
01 arg-1 PIC 9(8).
01 arg-2 PIC 9(8).
PROCEDURE DIVISION USING OPTIONAL arg-1, OPTIONAL arg-2.
END PROGRAM optional-args.
*> Standard COBOL does not support varargs or named parameters.
*> A function from another language, taking a 32-bit integer by
*> value and returning a 32-bit integer (in Visual COBOL).
PROGRAM-ID. foreign-func PROTOTYPE.
OPTIONS.
ENTRY-CONVENTION some-langauge.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 arg PIC S9(9) USAGE COMP-5.
01 ret PIC S9(9) USAGE COMP-5.
PROCEDURE DIVISION USING arg RETURNING ret.
END PROGRAM foreign-func.
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Go
|
Go
|
package main
import "fmt"
type FCNode struct {
name string
weight int
coverage float64
children []*FCNode
parent *FCNode
}
func newFCN(name string, weight int, coverage float64) *FCNode {
return &FCNode{name, weight, coverage, nil, nil}
}
func (n *FCNode) addChildren(nodes []*FCNode) {
for _, node := range nodes {
node.parent = n
n.children = append(n.children, node)
}
n.updateCoverage()
}
func (n *FCNode) setCoverage(value float64) {
if n.coverage != value {
n.coverage = value
// update any parent's coverage
if n.parent != nil {
n.parent.updateCoverage()
}
}
}
func (n *FCNode) updateCoverage() {
v1 := 0.0
v2 := 0
for _, node := range n.children {
v1 += float64(node.weight) * node.coverage
v2 += node.weight
}
n.setCoverage(v1 / float64(v2))
}
func (n *FCNode) show(level int) {
indent := level * 4
nl := len(n.name) + indent
fmt.Printf("%*s%*s %3d | %8.6f |\n", nl, n.name, 32-nl, "|", n.weight, n.coverage)
if len(n.children) == 0 {
return
}
for _, child := range n.children {
child.show(level + 1)
}
}
var houses = []*FCNode{
newFCN("house1", 40, 0),
newFCN("house2", 60, 0),
}
var house1 = []*FCNode{
newFCN("bedrooms", 1, 0.25),
newFCN("bathrooms", 1, 0),
newFCN("attic", 1, 0.75),
newFCN("kitchen", 1, 0.1),
newFCN("living_rooms", 1, 0),
newFCN("basement", 1, 0),
newFCN("garage", 1, 0),
newFCN("garden", 1, 0.8),
}
var house2 = []*FCNode{
newFCN("upstairs", 1, 0),
newFCN("groundfloor", 1, 0),
newFCN("basement", 1, 0),
}
var h1Bathrooms = []*FCNode{
newFCN("bathroom1", 1, 0.5),
newFCN("bathroom2", 1, 0),
newFCN("outside_lavatory", 1, 1),
}
var h1LivingRooms = []*FCNode{
newFCN("lounge", 1, 0),
newFCN("dining_room", 1, 0),
newFCN("conservatory", 1, 0),
newFCN("playroom", 1, 1),
}
var h2Upstairs = []*FCNode{
newFCN("bedrooms", 1, 0),
newFCN("bathroom", 1, 0),
newFCN("toilet", 1, 0),
newFCN("attics", 1, 0.6),
}
var h2Groundfloor = []*FCNode{
newFCN("kitchen", 1, 0),
newFCN("living_rooms", 1, 0),
newFCN("wet_room_&_toilet", 1, 0),
newFCN("garage", 1, 0),
newFCN("garden", 1, 0.9),
newFCN("hot_tub_suite", 1, 1),
}
var h2Basement = []*FCNode{
newFCN("cellars", 1, 1),
newFCN("wine_cellar", 1, 1),
newFCN("cinema", 1, 0.75),
}
var h2UpstairsBedrooms = []*FCNode{
newFCN("suite_1", 1, 0),
newFCN("suite_2", 1, 0),
newFCN("bedroom_3", 1, 0),
newFCN("bedroom_4", 1, 0),
}
var h2GroundfloorLivingRooms = []*FCNode{
newFCN("lounge", 1, 0),
newFCN("dining_room", 1, 0),
newFCN("conservatory", 1, 0),
newFCN("playroom", 1, 0),
}
func main() {
cleaning := newFCN("cleaning", 1, 0)
house1[1].addChildren(h1Bathrooms)
house1[4].addChildren(h1LivingRooms)
houses[0].addChildren(house1)
h2Upstairs[0].addChildren(h2UpstairsBedrooms)
house2[0].addChildren(h2Upstairs)
h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)
house2[1].addChildren(h2Groundfloor)
house2[2].addChildren(h2Basement)
houses[1].addChildren(house2)
cleaning.addChildren(houses)
topCoverage := cleaning.coverage
fmt.Printf("TOP COVERAGE = %8.6f\n\n", topCoverage)
fmt.Println("NAME HIERARCHY | WEIGHT | COVERAGE |")
cleaning.show(0)
h2Basement[2].setCoverage(1) // change Cinema node coverage to 1
diff := cleaning.coverage - topCoverage
fmt.Println("\nIf the coverage of the Cinema node were increased from 0.75 to 1")
fmt.Print("the top level coverage would increase by ")
fmt.Printf("%8.6f to %8.6f\n", diff, topCoverage+diff)
h2Basement[2].setCoverage(0.75) // restore to original value if required
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Ada
|
Ada
|
function Gamma (X : Long_Float) return Long_Float is
A : constant array (0..29) of Long_Float :=
( 1.00000_00000_00000_00000,
0.57721_56649_01532_86061,
-0.65587_80715_20253_88108,
-0.04200_26350_34095_23553,
0.16653_86113_82291_48950,
-0.04219_77345_55544_33675,
-0.00962_19715_27876_97356,
0.00721_89432_46663_09954,
-0.00116_51675_91859_06511,
-0.00021_52416_74114_95097,
0.00012_80502_82388_11619,
-0.00002_01348_54780_78824,
-0.00000_12504_93482_14267,
0.00000_11330_27231_98170,
-0.00000_02056_33841_69776,
0.00000_00061_16095_10448,
0.00000_00050_02007_64447,
-0.00000_00011_81274_57049,
0.00000_00001_04342_67117,
0.00000_00000_07782_26344,
-0.00000_00000_03696_80562,
0.00000_00000_00510_03703,
-0.00000_00000_00020_58326,
-0.00000_00000_00005_34812,
0.00000_00000_00001_22678,
-0.00000_00000_00000_11813,
0.00000_00000_00000_00119,
0.00000_00000_00000_00141,
-0.00000_00000_00000_00023,
0.00000_00000_00000_00002
);
Y : constant Long_Float := X - 1.0;
Sum : Long_Float := A (A'Last);
begin
for N in reverse A'First..A'Last - 1 loop
Sum := Sum * Y + A (N);
end loop;
return 1.0 / Sum;
end Gamma;
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#BASIC256
|
BASIC256
|
graphsize 150,125
fastgraphics
color black
rect 0,0,graphwidth,graphheight
refresh
N = 10 # number of balls
M = 5 # number of pins in last row
dim ball(N,5) # (pos_x to center, level, x, y, direction}
dim cnt(M+1)
rad = 6
slow = 0.3
diamond = {0,rad,rad,0,0,-rad,-rad,0}
stepx = {rad/sqr(2),rad/2,rad/2,(1-1/sqr(2))*rad,0}
stepy = {(1-1/sqr(2))*rad,rad/2,rad/2,rad/sqr(2),rad}
CX = graphwidth/2 : CY = graphheight/2
iters = 0
# Draw pins
for i = 1 to M
y = 3*rad*i
for j = 1 to i
dx = (j-i\2-1)*4*rad + ((i-1)%2)*2*rad
color purple
stamp CX+dx,y,1.0,diamond
color darkpurple
stamp CX+dx,y,0.6,diamond
next j
next i
gosub saverefresh
R = 0 : C = 0
font "Tahoma",10,50
do
# Release ball
if R<N then
R = R + 1
ball[R-1,2] = CX : ball[R-1,3] = rad*(1-stepx[?]) : ball[R-1,4] = 0
# How many balls are released
color black
text 5,5,(R-1)+" balls"
color green
text 5,5,(R)+" balls"
end if
# Animate balls on this step
for it = 0 to stepx[?]-1
for b = 0 to R-1
gosub moveball
next b
gosub saverefresh
pause slow/stepx[?]
next it
# Where to go on the next step?
for b = 0 to R-1
ball[b,1] = ball[b,1] + 1
if ball[b,1]<=M then
if rand>=0.5 then
ball[b,4] = 1
else
ball[b,4] = -1
end if
ball[b,0] = ball[b,0] + ball[b,4]
else
if ball[b,4]<>0 then
gosub eraseball
i = (ball[b,0]+M)/2
cnt[i] = cnt[i] + 1
ball[b,4] = 0
C = C + 1
end if
end if
next b
# Draw counter
color green
y = 3*rad*(M+1)
for j = 0 to M
dx = (j-(M+1)\2)*4*rad + (M%2)*2*rad
stamp CX+dx,y,{-1.2*rad,0,1.2*rad,0,1.2*rad,2*cnt[j],-1.2*rad,2*cnt[j]}
next j
gosub saverefresh
until C >= N
end
moveball:
if ball[b,1]>M then return
gosub eraseball
if ball[b,4]<>0.0 then
ball[b,2] = ball[b,2]+ball[b,4]*stepx[it]
ball[b,3] = ball[b,3]+stepy[it]
else
ball[b,3] = ball[b,3]+rad
end if
gosub drawball
drawball:
color darkgreen
circle ball[b,2],ball[b,3],rad-1
color green
circle ball[b,2],ball[b,3],rad-2
return
eraseball:
color black
circle ball[b,2],ball[b,3],rad-1
return
saverefresh:
num$ = string(iters)
for k = 1 to 4-length(num$)
num$ = "0"+num$
next k
imgsave num$+"-Galton_box_BASIC-256.png", "PNG"
iters = iters + 1
refresh
return
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#BBC_BASIC
|
BBC BASIC
|
maxBalls% = 10
DIM ballX%(maxBalls%), ballY%(maxBalls%)
VDU 23,22,180;400;8,16,16,128
ORIGIN 180,0
OFF
REM Draw the pins:
GCOL 9
FOR row% = 1 TO 7
FOR col% = 1 TO row%
CIRCLE FILL 40*col% - 20*row% - 20, 800 - 40*row%, 12
NEXT
NEXT row%
REM Animate
last% = 0
tick% = 0
GCOL 3,3
REPEAT
IF RND(10) = 5 IF (tick% - last%) > 10 THEN
FOR ball% = 1 TO maxBalls%
IF ballY%(ball%) = 0 THEN
ballX%(ball%) = 0
ballY%(ball%) = 800
last% = tick%
EXIT FOR
ENDIF
NEXT
ENDIF
FOR ball% = 1 TO maxBalls%
IF ballY%(ball%) CIRCLE FILL ballX%(ball%), ballY%(ball%), 12
IF POINT(ballX%(ball%),ballY%(ball%)-10) = 12 OR ballY%(ball%) < 12 THEN
IF ballY%(ball%) > 500 END
ballY%(ball%) = 0
ENDIF
NEXT
WAIT 2
FOR ball% = 1 TO maxBalls%
IF ballY%(ball%) THEN
CIRCLE FILL ballX%(ball%), ballY%(ball%), 12
ballY%(ball%) -= 4
IF POINT(ballX%(ball%),ballY%(ball%)-10) = 9 THEN
ballX%(ball%) += 40 * (RND(2) - 1.5)
ENDIF
ENDIF
NEXT
tick% += 1
UNTIL FALSE
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Common_Lisp
|
Common Lisp
|
(defun first-digit (n) (parse-integer (string (char (write-to-string n) 0))))
(defun last-digit (n) (mod n 10))
(defun bookend-number (n) (+ (* 10 (first-digit n)) (last-digit n)))
(defun gapfulp (n) (and (>= n 100) (zerop (mod n (bookend-number n)))))
(defun gapfuls-in-range (start size)
(loop for n from start
with include = (gapfulp n)
counting include into found
if include collecting n
until (= found size)))
(defun report-range (range)
(destructuring-bind (start size) range
(format t "The first ~a gapful numbers >= ~a:~% ~a~%~%" size start
(gapfuls-in-range start size))))
(mapcar #'report-range '((1 30) (1000000 15) (1000000000 10)))
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#Common_Lisp
|
Common Lisp
|
(defmacro mapcar-1 (fn n list)
"Maps a function of two parameters where the first one is fixed, over a list"
`(mapcar #'(lambda (l) (funcall ,fn ,n l)) ,list) )
(defun gauss (m)
(labels
((redc (m) ; Reduce to triangular form
(if (null (cdr m))
m
(cons (car m) (mapcar-1 #'cons 0 (redc (mapcar #'cdr (mapcar #'(lambda (r) (mapcar #'- (mapcar-1 #'* (caar m) r)
(mapcar-1 #'* (car r) (car m)))) (cdr m)))))) ))
(rev (m) ; Reverse each row except the last element
(reverse (mapcar #'(lambda (r) (append (reverse (butlast r)) (last r))) m)) ))
(catch 'result
(let ((m1 (redc (rev (redc m)))))
(reverse (mapcar #'(lambda (r) (let ((pivot (find-if-not #'zerop r))) (if pivot (/ (car (last r)) pivot) (throw 'result 'singular)))) m1)) ))))
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Ruby
|
Ruby
|
def hasNK( board, a, b )
for g in -1 .. 1
for f in -1 .. 1
aa = a + f; bb = b + g
if aa.between?( 0, 7 ) && bb.between?( 0, 7 )
p = board[aa + 8 * bb]
if p == "K" || p == "k"; return true; end
end
end
end
return false
end
def generateBoard( board, pieces )
while( pieces.length > 1 )
p = pieces[pieces.length - 1]
pieces = pieces[0...-1]
while( true )
a = rand( 8 ); b = rand( 8 )
if ( ( b == 0 || b == 7 ) && ( p == "P" || p == "p" ) ) ||
( ( p == "k" || p == "K" ) && hasNK( board, a, b ) ); next; end
if board[a + b * 8] == nil; break;end
end
board[a + b * 8] = p
end
end
pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
for i in 0 .. 10
e = pieces.length - 1
while e > 0
p = rand( e ); t = pieces[e];
pieces[e] = pieces[p]; pieces[p] = t; e -= 1
end
end
board = Array.new( 64 ); generateBoard( board, pieces )
puts
e = 0
for j in 0 .. 7
for i in 0 .. 7
if board[i + 8 * j] == nil; e += 1
else
if e > 0; print( e ); e = 0; end
print( board[i + 8 * j] )
end
end
if e > 0; print( e ); e = 0; end
if j < 7; print( "/" ); end
end
print( " w - - 0 1\n" )
for j in 0 .. 7
for i in 0 .. 7
if board[i + j * 8] == nil; print( "." )
else print( board[i + j * 8] ); end
end
puts
end
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Haskell
|
Haskell
|
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
matI::(Num a) => Int -> [[a]]
matI n = [ [fromIntegral.fromEnum $ i == j | j <- [1..n]] | i <- [1..n]]
inversion xs = gauss xs (matI $ length xs)
gauss::[[Double]] -> [[Double]] -> [[Double]]
gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs)
where toR = map $ map toRational
solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]]
solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = []
| otherwise = uncurry solveTriangle $ triangle xs bs
solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]]
solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = []
solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b]
where
val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws)
go [] _ zs = zs
go _ [] zs = zs
go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs
triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]])
triangle xs bs = triang ([],[]) (xs,bs)
where
triang ts (_,[]) = ts
triang ts ([],_) = ts
triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)]
where ((us@(u:tus)):uss,cs:css) = bubble zs
bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]])
bubble (xs,bs) = (go xs, go bs)
where
idmax = snd.maximum.flip zip [0..].map (abs.head) $ xs
go ys = let (us,vs) = splitAt idmax ys in vs ++ us
main = do
let a = [[1, 2, 3], [4, 1, 6], [7, 8, 9]]
let b = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]
putStrLn "inversion a ="
mapM_ print $ inversion a
putStrLn "\ninversion b ="
mapM_ print $ inversion b
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Factor
|
Factor
|
USING: assocs combinators.extras io kernel math math.parser
math.ranges prettyprint sequences splitting ;
IN: rosetta-code.general-fizzbuzz
: prompt ( -- str ) ">" write readln ;
: get-factor ( -- seq )
prompt " " split first2 [ string>number ] dip
{ } 2sequence ;
: get-input ( -- assoc n )
prompt string>number [1,b] [ get-factor ] thrice
{ } 3sequence swap ;
: fizzbuzz ( assoc n -- )
swap dupd [ drop swap mod 0 = ] with assoc-filter
dup empty? [ drop . ] [ nip values concat print ] if ;
: main ( -- ) get-input [ fizzbuzz ] with each ;
MAIN: main
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Forth
|
Forth
|
\ gfb.fs - generalized fizz buzz
: times ( xt n -- )
BEGIN dup WHILE
1- over swap 2>r execute 2r>
REPEAT
2drop
;
\ 'Domain Specific Language' compiling words
\ -- First comment: stack-effect at compile-time
\ -- Second comment: stack efect of compiled sequence
: ]+[ ( u ca u -- ) ( u f -- u f' )
2>r >r ]
]] over [[
r> ]] literal mod 0= IF [[
2r> ]] sliteral type 1+ THEN [ [[
;
: ]fb ( -- xt ) ( u f -- u+1 )
]] IF space ELSE dup u. THEN 1+ ; [[
;
: fb[ ( -- ) ( u -- u 0 ;'u' is START-NUMBER )
:noname 0 ]] literal [ [[
;
\ Usage: START-NUMBER COMPILING-SEQUENCE U times drop ( INCREASED-NUBER )
\ Example:
\ 1 fb[ 3 s" fizz" ]+[ 5 s" buzz" ]+[ 7 s" dizz" ]+[ ]fb 40 times drop
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Visual_Basic
|
Visual Basic
|
Option Explicit
Dim flag As Boolean ' true to print values
Sub main()
Dim longest As Long, n As Long
Dim i As Long, value As Long
' Task 1:
flag = True
i = 27
Debug.Print "The hailstone sequence has length of "; i; " is "; hailstones(i)
' Task 2:
flag = False
longest = 0
For i = 1 To 99999
If longest < hailstones(i) Then
longest = hailstones(i)
value = i
End If
Next i
Debug.Print value; " has the longest sequence of "; longest
End Sub 'main
Function hailstones(n As Long) As Long
Dim m As Long, p As Long
Dim m1 As Long, m2 As Long, m3 As Long, m4 As Long
If flag Then Debug.Print "The sequence for"; n; "is: ";
p = 1
m = n
If flag Then Debug.Print m;
While m > 1
p = p + 1
If (m Mod 2) = 0 Then
m = m / 2
Else
m = 3 * m + 1
End If
If p <= 4 Then If flag Then Debug.Print m;
m4 = m3
m3 = m2
m2 = m1
m1 = m
Wend
If flag Then
If p <= 4 Then
Debug.Print
ElseIf p = 5 Then
Debug.Print m1
ElseIf p = 6 Then
Debug.Print m2; m1
ElseIf p = 7 Then
Debug.Print m3; m2; m1
ElseIf p = 8 Then
Debug.Print m4; m3; m2; m1
Else
Debug.Print "..."; m4; m3; m2; m1
End If
End If
hailstones = p
End Function 'hailstones
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#C.2B.2B
|
C++
|
#include <string>
#include <numeric>
int main() {
std::string lower(26,' ');
std::iota(lower.begin(), lower.end(), 'a');
}
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Clojure
|
Clojure
|
(map char (range (int \a) (inc (int \z))))
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#OCaml
|
OCaml
|
print_endline "Hello world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Wart
|
Wart
|
(swap! x y)
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Wren
|
Wren
|
var swap = Fn.new { |l|
var t = l[0]
l[0] = l[1]
l[1] = t
}
var a = 6
var b = 3
var c = [a, b]
swap.call(c) // pass a list instead of individual variables
a = c[0] // unpack
b = c[1] // ditto
System.print("a is now %(a)")
System.print("b is now %(b)")
System.print()
// all user defined classes are reference types
class Box {
construct new(v) { _v = v }
v { _v }
v=(value) { _v = value }
}
// by passing boxed arguments we can mutate them
var boxSwap = Fn.new { |a, b|
var t = a.v
a.v = b.v
b.v = t
}
var d = Box.new(4)
var e = Box.new(8)
boxSwap.call(d, e)
d = d.v // unbox
e = e.v // ditto
System.print("d is now %(d)")
System.print("e is now %(e)")
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#J
|
J
|
coclass 'mthPower'
N=: 0
create=: 3 :0
M=: y
)
next=: 3 :0
n=. N
N=: N+1
n^M
)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#V
|
V
|
[gcd
[0 >] [dup rollup %]
while
pop
].
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#VBA
|
VBA
|
Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Print[StringJoin[
RandomChoice[
Select[Union[
Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]",
"\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]",
"\[WhiteKnight]", "\[WhiteKnight]"}]],
MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___,
"\[WhiteRook]", ___}] &&
OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]];
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#MiniScript
|
MiniScript
|
// placeholder knights
rank = ["♘"] * 8
// function to get a random free space from a to b, inclusive
randFree = function(a, b)
free = []
for i in range(a, b)
if rank[i] == "♘" then free.push i
end for
return free[rnd * free.len]
end function
// place the king
kingIdx = randFree(1, 6)
rank[kingIdx] = "♔"
// place rooks
rank[randFree(0, kingIdx - 1)] = "♖"
rank[randFree(kingIdx + 1, 7)] = "♖"
// place bishops
bishIdx = randFree(0, 7)
rank[bishIdx] = "♗"
while true
i = randFree(0, 7)
if i % 2 != bishIdx % 2 then break
end while
rank[i] = "♗"
// place queen
rank[randFree(0, 7)] = "♕"
print join(rank, " ")
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#Common_Lisp
|
Common Lisp
|
(declaim (inline no-args))
(declaim (inline one-arg))
(declaim (inline two-args))
(declaim (inline optional-args))
(defun no-args ()
(format nil "no arguments!"))
(defun one-arg (x)
; inserts the value of x into a string
(format nil "~a" x))
(defun two-args (x y)
; same as function `one-arg', but with two arguments
(format nil "~a ~a" x y))
(defun optional-args (x &optional y) ; optional args are denoted with &optional beforehand
; same as function `two-args', but if y is not given it just prints NIL
(format nil "~a ~a~%" x y))
(no-args) ;=> "no arguments!"
(one-arg 1) ;=> "1"
(two-args 1 "example") ;=> "1 example"
(optional-args 1.0) ;=> "1.0 NIL"
(optional-args 1.0 "example") ;=> "1.0 example"
|
http://rosettacode.org/wiki/Function_prototype
|
Function prototype
|
Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
Task
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
An explanation of any placement restrictions for prototype declarations
A prototype declaration for a function that does not require arguments
A prototype declaration for a function that requires two arguments
A prototype declaration for a function that utilizes varargs
A prototype declaration for a function that utilizes optional arguments
A prototype declaration for a function that utilizes named parameters
Example of prototype declarations for subroutines or procedures (if these differ from functions)
An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
|
#D
|
D
|
/// Declare a function with no arguments that returns an integer.
int noArgs();
/// Declare a function with no arguments that returns an integer.
int twoArgs(int a, int b);
/// Parameter names are optional in a prototype definition.
int twoArgs2(int, int);
/// An ellipsis can be used to declare a function that accepts
/// C-style varargs.
int anyArgs(...);
/// One mandatory integer argument followed by C-style varargs.
int atLeastOneArg(int, ...);
/// Declare a function that accepts any number of integers.
void anyInts(int[] a...);
/// Declare a function that accepts D-style varargs.
void anyArgs2(TArgs...)(TArgs args);
/// Declare a function that accepts two or more D-style varargs.
void anyArgs3(TArgs...)(TArgs args) if (TArgs.length > 2);
/// Currently D doesn't support named arguments.
/// One implementation.
int twoArgs(int a, int b) {
return a + b;
}
interface SomeInterface {
void foo();
void foo(int, int);
// Varargs
void foo(...); // C-style.
void foo(int[] a...);
void bar(T...)(T args); // D-style.
// Optional arguments are only supported if a default is provided,
// the default arg(s) has/have to be at the end of the args list.
void foo(int a, int b = 10);
}
void main() {}
|
http://rosettacode.org/wiki/Functional_coverage_tree
|
Functional coverage tree
|
Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional requirements of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
Task Description
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
Calculation
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
Extra Credit
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained
1
−
c
o
v
e
r
a
g
e
{\displaystyle 1-coverage}
for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
|
#Haskell
|
Haskell
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Tree (Forest, Tree (..), foldTree)
import Numeric (showFFloat)
import System.Directory (doesFileExist)
----------------- FUNCTIONAL COVERAGE TREE ---------------
data Coverage = Coverage
{ name :: T.Text,
weight :: Float,
coverage :: Float,
share :: Float
}
deriving (Show)
--------------------------- TEST -------------------------
fp = "./coverageOutline.txt"
main :: IO ()
main =
doesFileExist fp
>>= bool
(print $ "File not found: " <> fp)
(T.readFile fp >>= T.putStrLn . updatedCoverageOutline)
----------------- UPDATED COVERAGE OUTLINE ---------------
updatedCoverageOutline :: T.Text -> T.Text
updatedCoverageOutline s =
let delimiter = "|"
indentedLines = T.lines s
columnNames =
init $
tokenizeWith
delimiter
( head indentedLines
)
in T.unlines
[ tabulation
delimiter
(columnNames <> ["SHARE OF RESIDUE"]),
indentedLinesFromTree
" "
(showCoverage delimiter)
$ withResidueShares 1.0 $
foldTree
weightedCoverage
(parseTreeFromOutline delimiter indentedLines)
]
------ WEIGHTED COVERAGE AND SHARES OF REMAINING WORK ----
weightedCoverage ::
Coverage ->
Forest Coverage ->
Tree Coverage
weightedCoverage x xs =
let cws = ((,) . coverage <*> weight) . rootLabel <$> xs
totalWeight = foldr ((+) . snd) 0 cws
in Node
( x
{ coverage =
foldr
(\(c, w) a -> (c * w) + a)
(coverage x)
cws
/ bool 1 totalWeight (0 < totalWeight)
}
)
xs
withResidueShares :: Float -> Tree Coverage -> Tree Coverage
withResidueShares shareOfTotal tree =
let go fraction node =
let forest = subForest node
weights = weight . rootLabel <$> forest
weightTotal = sum weights
nodeRoot = rootLabel node
in Node
( nodeRoot
{ share =
fraction
* (1 - coverage nodeRoot)
}
)
( zipWith
go
((fraction *) . (/ weightTotal) <$> weights)
forest
)
in go shareOfTotal tree
---------------------- OUTLINE PARSE ---------------------
parseTreeFromOutline :: T.Text -> [T.Text] -> Tree Coverage
parseTreeFromOutline delimiter indentedLines =
partialRecord . tokenizeWith delimiter
<$> head
( forestFromLineIndents $
indentLevelsFromLines $ tail indentedLines
)
forestFromLineIndents :: [(Int, T.Text)] -> [Tree T.Text]
forestFromLineIndents pairs =
let go [] = []
go ((n, s) : xs) =
let (firstTreeLines, rest) = span ((n <) . fst) xs
in Node s (go firstTreeLines) : go rest
in go pairs
indentLevelsFromLines :: [T.Text] -> [(Int, T.Text)]
indentLevelsFromLines xs =
let pairs = T.span isSpace <$> xs
indentUnit =
foldr
( \x a ->
let w = (T.length . fst) x
in bool a w (w < a && 0 < w)
)
(maxBound :: Int)
pairs
in first (flip div indentUnit . T.length) <$> pairs
partialRecord :: [T.Text] -> Coverage
partialRecord xs =
let [name, weightText, coverageText] =
take
3
(xs <> repeat "")
in Coverage
{ name = name,
weight = defaultOrRead 1.0 weightText,
coverage = defaultOrRead 0.0 coverageText,
share = 0.0
}
defaultOrRead :: Float -> T.Text -> Float
defaultOrRead n txt = either (const n) fst $ T.rational txt
tokenizeWith :: T.Text -> T.Text -> [T.Text]
tokenizeWith delimiter = fmap T.strip . T.splitOn delimiter
-------- SERIALISATION OF TREE TO TABULATED OUTLINE ------
indentedLinesFromTree ::
T.Text ->
(T.Text -> a -> T.Text) ->
Tree a ->
T.Text
indentedLinesFromTree tab showRoot tree =
let go indent node =
showRoot indent (rootLabel node) :
(subForest node >>= go (T.append tab indent))
in T.unlines $ go "" tree
showCoverage :: T.Text -> T.Text -> Coverage -> T.Text
showCoverage delimiter indent x =
tabulation
delimiter
( [T.append indent (name x), T.pack (showN 0 (weight x))]
<> (T.pack . showN 4 <$> ([coverage, share] <*> [x]))
)
tabulation :: T.Text -> [T.Text] -> T.Text
tabulation delimiter =
T.intercalate (T.append delimiter " ")
. zipWith (`T.justifyLeft` ' ') [31, 9, 9, 9]
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = (drop . length) <*> (replicate n c <>)
showN :: Int -> Float -> String
showN p n = justifyRight 7 ' ' (showFFloat (Just p) n "")
|
http://rosettacode.org/wiki/Function_frequency
|
Function frequency
|
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).
This is a static analysis: The question is not how often each function is
actually executed at runtime, but how often it is used by the programmer.
Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
|
#ACL2
|
ACL2
|
(in-package "ACL2")
(set-state-ok t)
(defun read-all-objects (limit channel state)
(mv-let (eof obj state)
(read-object channel state)
(if (or eof (zp limit))
(mv nil state)
(mv-let (so-far state)
(read-all-objects (- limit 1) channel state)
(mv (cons obj so-far) state)))))
(defun list-starters (xs)
(cond ((endp xs) nil)
((consp (first xs))
(append (if (symbolp (first (first xs)))
(list (first (first xs)))
nil)
(list-starters (rest (first xs)))
(list-starters (rest xs))))
(t (list-starters (rest xs)))))
(defun invoked-functions (filename state)
(mv-let (channel state)
(open-input-channel filename :object state)
(mv-let (code state)
(read-all-objects 1000 channel state)
(mv (list-starters code) state))))
(defun increment-for (key alist)
(cond ((endp alist) (list (cons key 1)))
((equal key (car (first alist)))
(cons (cons key (1+ (cdr (first alist))))
(rest alist)))
(t (cons (first alist)
(increment-for key (rest alist))))))
(defun symbol-freq-table (symbols)
(if (endp symbols)
nil
(increment-for (first symbols)
(symbol-freq-table (rest symbols)))))
(defun insert-freq-table (pair alist)
(cond ((endp alist)
(list pair))
((> (cdr pair) (cdr (first alist)))
(cons pair alist))
(t (cons (first alist)
(insert-freq-table pair (rest alist))))))
(defun isort-freq-table (alist)
(if (endp alist)
nil
(insert-freq-table (first alist)
(isort-freq-table (rest alist)))))
(defun main (state)
(mv-let (fns state)
(invoked-functions "function-freq.lisp" state)
(mv (take 10 (isort-freq-table
(symbol-freq-table fns))) state)))
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#ALGOL_68
|
ALGOL 68
|
# Coefficients used by the GNU Scientific Library #
[]LONG REAL p = ( LONG 0.99999 99999 99809 93,
LONG 676.52036 81218 851,
-LONG 1259.13921 67224 028,
LONG 771.32342 87776 5313,
-LONG 176.61502 91621 4059,
LONG 12.50734 32786 86905,
-LONG 0.13857 10952 65720 12,
LONG 9.98436 95780 19571 6e-6,
LONG 1.50563 27351 49311 6e-7);
PROC lanczos gamma = (LONG REAL in z)LONG REAL: (
# Reflection formula #
LONG REAL z := in z;
IF z < LONG 0.5 THEN
long pi / (long sin(long pi*z)*lanczos gamma(1-z))
ELSE
z -:= 1;
LONG REAL x := p[1];
FOR i TO UPB p - 1 DO x +:= p[i+1]/(z+i) OD;
LONG REAL t = z + UPB p - LONG 1.5;
long sqrt(2*long pi) * t**(z+LONG 0.5) * long exp(-t) * x
FI
);
PROC taylor gamma = (LONG REAL x)LONG REAL:
BEGIN # good for values between 0 and 1 #
[]LONG REAL a =
( LONG 1.00000 00000 00000 00000,
LONG 0.57721 56649 01532 86061,
-LONG 0.65587 80715 20253 88108,
-LONG 0.04200 26350 34095 23553,
LONG 0.16653 86113 82291 48950,
-LONG 0.04219 77345 55544 33675,
-LONG 0.00962 19715 27876 97356,
LONG 0.00721 89432 46663 09954,
-LONG 0.00116 51675 91859 06511,
-LONG 0.00021 52416 74114 95097,
LONG 0.00012 80502 82388 11619,
-LONG 0.00002 01348 54780 78824,
-LONG 0.00000 12504 93482 14267,
LONG 0.00000 11330 27231 98170,
-LONG 0.00000 02056 33841 69776,
LONG 0.00000 00061 16095 10448,
LONG 0.00000 00050 02007 64447,
-LONG 0.00000 00011 81274 57049,
LONG 0.00000 00001 04342 67117,
LONG 0.00000 00000 07782 26344,
-LONG 0.00000 00000 03696 80562,
LONG 0.00000 00000 00510 03703,
-LONG 0.00000 00000 00020 58326,
-LONG 0.00000 00000 00005 34812,
LONG 0.00000 00000 00001 22678,
-LONG 0.00000 00000 00000 11813,
LONG 0.00000 00000 00000 00119,
LONG 0.00000 00000 00000 00141,
-LONG 0.00000 00000 00000 00023,
LONG 0.00000 00000 00000 00002
);
LONG REAL y = x - 1;
LONG REAL sum := a [UPB a];
FOR n FROM UPB a - 1 DOWNTO LWB a DO
sum := sum * y + a [n]
OD;
1/sum
END # taylor gamma #;
LONG REAL long e = long exp(1);
PROC sterling gamma = (LONG REAL n)LONG REAL:
( # improves for values much greater then 1 #
long sqrt(2*long pi/n)*(n/long e)**n
);
PROC factorial = (LONG INT n)LONG REAL:
(
IF n=0 OR n=1 THEN 1
ELIF n=2 THEN 2
ELSE n*factorial(n-1) FI
);
REF[]LONG REAL fm := NIL;
PROC sponge gamma = (LONG REAL x)LONG REAL:
(
INT a = 12; # alter to get required precision #
REF []LONG REAL fm := NIL;
LONG REAL res;
IF fm :=: REF[]LONG REAL(NIL) THEN
fm := HEAP[0:a-1]LONG REAL;
fm[0] := long sqrt(LONG 2*long pi);
FOR k TO a-1 DO
fm[k] := (((k-1) MOD 2=0) | 1 | -1) * long exp(a-k) *
(a-k) **(k-LONG 0.5) / factorial(k-1)
OD
FI;
res := fm[0];
FOR k TO a-1 DO
res +:= fm[k] / ( x + k )
OD;
res *:= long exp(-(x+a)) * (x+a)**(x + LONG 0.5);
res/x
);
FORMAT real fmt = $g(-real width, real width - 2)$;
FORMAT long real fmt16 = $g(-17, 17 - 2)$; # accurate to about 16 decimal places #
[]STRING methods = ("Genie", "Lanczos", "Sponge", "Taylor","Stirling");
printf(($11xg12xg12xg13xg13xgl$,methods));
FORMAT sample fmt = $"gamma("g(-3,1)")="f(real fmt)n(UPB methods-1)(", "f(long real fmt16))l$;
FORMAT sqr sample fmt = $"gamma("g(-3,1)")**2="f(real fmt)n(UPB methods-1)(", "f(long real fmt16))l$;
FORMAT sample exp fmt = $"gamma("g(-3)")="g(-15,11,0)n(UPB methods-1)(","g(-18,14,0))l$;
PROC sample = (LONG REAL x)[]LONG REAL:
(gamma(SHORTEN x), lanczos gamma(x), sponge gamma(x), taylor gamma(x), sterling gamma(x));
FOR i FROM 1 TO 20 DO
LONG REAL x = i / LONG 10;
printf((sample fmt, x, sample(x)));
IF i = 5 THEN # insert special case of a half #
printf((sqr sample fmt,
x, gamma(SHORTEN x)**2, lanczos gamma(x)**2, sponge gamma(x)**2,
taylor gamma(x)**2, sterling gamma(x)**2))
FI
OD;
FOR x FROM 10 BY 10 TO 70 DO
printf((sample exp fmt, x, sample(x)))
OD
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BALLS 1024
int n, w, h = 45, *x, *y, cnt = 0;
char *b;
#define B(y, x) b[(y)*w + x]
#define C(y, x) ' ' == b[(y)*w + x]
#define V(i) B(y[i], x[i])
inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }
void show_board()
{
int i, j;
for (puts("\033[H"), i = 0; i < h; i++, putchar('\n'))
for (j = 0; j < w; j++, putchar(' '))
printf(B(i, j) == '*' ?
C(i - 1, j) ? "\033[32m%c\033[m" :
"\033[31m%c\033[m" : "%c", B(i, j));
}
void init()
{
int i, j;
puts("\033[H\033[J");
b = malloc(w * h);
memset(b, ' ', w * h);
x = malloc(sizeof(int) * BALLS * 2);
y = x + BALLS;
for (i = 0; i < n; i++)
for (j = -i; j <= i; j += 2)
B(2 * i+2, j + w/2) = '*';
srand(time(0));
}
void move(int idx)
{
int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0;
if (yy < 0) return;
if (yy == h - 1) { y[idx] = -1; return; }
switch(c = B(yy + 1, xx)) {
case ' ': yy++; break;
case '*': sl = 1;
default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1))
if (!rnd(sl++)) o = 1;
if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1))
if (!rnd(sl++)) o = -1;
if (!o) kill = 1;
xx += o;
}
c = V(idx); V(idx) = ' ';
idx[y] = yy, idx[x] = xx;
B(yy, xx) = c;
if (kill) idx[y] = -1;
}
int run(void)
{
static int step = 0;
int i;
for (i = 0; i < cnt; i++) move(i);
if (2 == ++step && cnt < BALLS) {
step = 0;
x[cnt] = w/2;
y[cnt] = 0;
if (V(cnt) != ' ') return 0;
V(cnt) = rnd(80) + 43;
cnt++;
}
return 1;
}
int main(int c, char **v)
{
if (c < 2 || (n = atoi(v[1])) <= 3) n = 5;
if (n >= 20) n = 20;
w = n * 2 + 1;
init();
do { show_board(), usleep(60000); } while (run());
return 0;
}
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Crystal
|
Crystal
|
struct Int
def gapful?
a = self.to_s.chars.map(&.to_i)
self % (a.first*10 + a.last) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, count|
puts "first #{count} gapful numbers >= #{start}:"
puts (start..).each.select(&.gapful?).first(count).to_a, "\n"
end
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#D
|
D
|
import std.stdio, std.math, std.algorithm, std.range, std.numeric,
std.typecons;
Tuple!(double[],"x", string,"err")
gaussPartial(in double[][] a0, in double[] b0) pure /*nothrow*/
in {
assert(a0.length == a0[0].length);
assert(a0.length == b0.length);
assert(a0.all!(row => row.length == a0[0].length));
} body {
enum eps = 1e-6;
immutable m = b0.length;
// Make augmented matrix.
//auto a = a0.zip(b0).map!(c => c[0] ~ c[1]).array; // Not mutable.
auto a = a0.zip(b0).map!(c => [] ~ c[0] ~ c[1]).array;
// Wikipedia algorithm from Gaussian elimination page,
// produces row-eschelon form.
foreach (immutable k; 0 .. a.length) {
// Find pivot for column k and swap.
a[k .. m].minPos!((x, y) => x[k] > y[k]).front.swap(a[k]);
if (a[k][k].abs < eps)
return typeof(return)(null, "singular");
// Do for all rows below pivot.
foreach (immutable i; k + 1 .. m) {
// Do for all remaining elements in current row.
a[i][k+1 .. m+1] -= a[k][k+1 .. m+1] * (a[i][k] / a[k][k]);
a[i][k] = 0; // Fill lower triangular matrix with zeros.
}
}
// End of WP algorithm. Now back substitute to get result.
auto x = new double[m];
foreach_reverse (immutable i; 0 .. m)
x[i] = (a[i][m] - a[i][i+1 .. m].dotProduct(x[i+1 .. m])) / a[i][i];
return typeof(return)(x, null);
}
void main() {
// The test case result is correct to this tolerance.
enum eps = 1e-13;
// Common RC example. Result computed with rational arithmetic
// then converted to double, and so should be about as close to
// correct as double represention allows.
immutable a = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00],
[1.00, 0.63, 0.39, 0.25, 0.16, 0.10],
[1.00, 1.26, 1.58, 1.98, 2.49, 3.13],
[1.00, 1.88, 3.55, 6.70, 12.62, 23.80],
[1.00, 2.51, 6.32, 15.88, 39.90, 100.28],
[1.00, 3.14, 9.87, 31.01, 97.41, 306.02]];
immutable b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02];
immutable r = gaussPartial(a, b);
if (!r.err.empty)
return writeln("Error: ", r.err);
r.x.writeln;
immutable result = [-0.01, 1.602790394502114,
-1.6132030599055613, 1.2454941213714368,
-0.4909897195846576, 0.065760696175232];
foreach (immutable i, immutable xi; result)
if (abs(r.x[i] - xi) > eps)
return writeln("Out of tolerance: ", r.x[i], " ", xi);
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Rust
|
Rust
|
use std::fmt::Write;
use rand::{Rng, distributions::{Distribution, Standard}};
const EMPTY: u8 = b'.';
#[derive(Clone, Debug)]
struct Board {
grid: [[u8; 8]; 8],
}
impl Distribution<Board> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Board {
let mut board = Board::empty();
board.place_kings(rng);
board.place_pieces(rng, b"PPPPPPPP", true);
board.place_pieces(rng, b"pppppppp", true);
board.place_pieces(rng, b"RNBQBNR", false);
board.place_pieces(rng, b"rnbqbnr", false);
board
}
}
impl Board {
fn empty() -> Self {
Board { grid: [[EMPTY; 8]; 8] }
}
fn fen(&self) -> String {
let mut fen = String::new();
let mut count_empty = 0;
for row in &self.grid {
for &ch in row {
print!("{} ", ch as char);
if ch == EMPTY {
count_empty += 1;
} else {
if count_empty > 0 {
write!(fen, "{}", count_empty).unwrap();
count_empty = 0;
}
fen.push(ch as char);
}
}
if count_empty > 0 {
write!(fen, "{}", count_empty).unwrap();
count_empty = 0;
}
fen.push('/');
println!();
}
fen.push_str(" w - - 0 1");
fen
}
fn place_kings<R: Rng + ?Sized>(&mut self, rng: &mut R) {
loop {
let r1: i8 = rng.gen_range(0, 8);
let c1: i8 = rng.gen_range(0, 8);
let r2: i8 = rng.gen_range(0, 8);
let c2: i8 = rng.gen_range(0, 8);
if r1 != r2 && (r1 - r2).abs() > 1 && (c1 - c2).abs() > 1 {
self.grid[r1 as usize][c1 as usize] = b'K';
self.grid[r2 as usize][c2 as usize] = b'k';
return;
}
}
}
fn place_pieces<R: Rng + ?Sized>(&mut self, rng: &mut R, pieces: &[u8], is_pawn: bool) {
let num_to_place = rng.gen_range(0, pieces.len());
for &piece in pieces.iter().take(num_to_place) {
let mut r = rng.gen_range(0, 8);
let mut c = rng.gen_range(0, 8);
while self.grid[r][c] != EMPTY || (is_pawn && (r == 7 || r == 0)) {
r = rng.gen_range(0, 8);
c = rng.gen_range(0, 8);
}
self.grid[r][c] = piece;
}
}
}
fn main() {
let b: Board = rand::random();
println!("{}", b.fen());
}
|
http://rosettacode.org/wiki/Generate_random_chess_position
|
Generate random chess position
|
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);
including the kings, up to 32 pieces of either color can be placed.
There is no requirement for material balance between sides.
The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
it is white's turn.
It's assumed that both sides have lost castling rights and that there is no possibility for en passant (the FEN should thus end in w - - 0 1).
No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
|
#Scala
|
Scala
|
import scala.math.abs
import scala.util.Random
object RandomFen extends App {
val rand = new Random
private def createFen = {
val grid = Array.ofDim[Char](8, 8)
def placeKings(grid: Array[Array[Char]]): Unit = {
var r1, c1, r2, c2 = 0
do {
r1 = rand.nextInt(8)
c1 = rand.nextInt(8)
r2 = rand.nextInt(8)
c2 = rand.nextInt(8)
} while (r1 == r2 || abs(r1 - r2) <= 1 || abs(c1 - c2) <= 1)
grid(r1)(c1) = 'K'
grid(r2)(c2) = 'k'
}
def placePieces(grid: Array[Array[Char]],
pieces: String,
isPawn: Boolean): Unit = {
val numToPlace = rand.nextInt(pieces.length)
for (n <- 0 until numToPlace) {
var r, c = 0
do {
r = rand.nextInt(8)
c = rand.nextInt(8)
} while (grid(r)(c) != 0 || (isPawn && (r == 7 || r == 0)))
grid(r)(c) = pieces(n)
}
}
def toFen(grid: Array[Array[Char]]) = {
val fen = new StringBuilder
var countEmpty = 0
for (r <- grid.indices) {
for (c <- grid.indices) {
val ch = grid(r)(c)
print(f"${if (ch == 0) '.' else ch}%2c ")
if (ch == 0) countEmpty += 1
else {
if (countEmpty > 0) {
fen.append(countEmpty)
countEmpty = 0
}
fen.append(ch)
}
}
if (countEmpty > 0) {
fen.append(countEmpty)
countEmpty = 0
}
fen.append("/")
println()
}
fen.append(" w - - 0 1").toString
}
placeKings(grid)
placePieces(grid, "PPPPPPPP", isPawn = true)
placePieces(grid, "pppppppp", isPawn = true)
placePieces(grid, "RNBQBNR", isPawn = false)
placePieces(grid, "rnbqbnr", isPawn = false)
toFen(grid)
}
println(createFen)
}
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#J
|
J
|
require 'math/misc/linear'
augmentR_I1=: ,. e.@i.@# NB. augment matrix on the right with its Identity matrix
matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#FreeBASIC
|
FreeBASIC
|
' version 01-03-2018
' compile with: fbc -s console
Dim As UInteger f(), factor, c, i, n
Dim As Integer max
Dim As String w(), word
Dim As boolean flag
Do
Input "Enter maximum number, if number < 1 then the program wil end ", max
If max < 1 Then Exit Do
Print
While c = 0 Or c > max
Input "Total number of factors ", c
Wend
c -= 1
ReDim f(c), w(c)
Print
For i = 0 To c
Input "Enter factor and word, separated by a comma ", factor, word
f(i) = factor
w(i) = word
Next
While flag = FALSE
flag = TRUE
For n = 0 To c-1
For i = 1 To c
If f(n) > f(i) Then
flag = FALSE
Swap f(n), f(i)
Swap w(n), w(i)
End If
Next
Next
Wend
For n = 1 To max
flag = FALSE
For i = 0 To c
If n Mod f(i) = 0 Then
flag = TRUE
Print w(i);
End If
Next
Print IIf(flag , "", Str(n))
Next
Exit Do
Loop
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.