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/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Raku
|
Raku
|
# A month has 5 weekends iff it has 31 days and starts on Friday.
my @years = 1900 .. 2100;
my @has31 = 1, 3, 5, 7, 8, 10, 12;
my @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));
say 'Happy month count: ', +@happy;
say 'First happy months: ' ~ @happy[^5];
say 'Last happy months: ' ~ @happy[*-5 .. *];
say 'Dreary years count: ', @years - @happy».year.squish;
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#SuperCollider
|
SuperCollider
|
a = [sin(_), cos(_), { |x| x ** 3 }];
b = [asin(_), acos(_), { |x| x ** (1/3) }];
c = a.collect { |x, i| x <> b[i] };
c.every { |x| x.(0.5) - 0.5 < 0.00001 }
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#Swift
|
Swift
|
import Darwin
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
let funclist = [ { (x: Double) in sin(x) }, { (x: Double) in cos(x) }, { (x: Double) in pow(x, 3) } ]
let funclisti = [ { (x: Double) in asin(x) }, { (x: Double) in acos(x) }, { (x: Double) in cbrt(x) } ]
println(map(zip(funclist, funclisti)) { f, inversef in compose(f, inversef)(0.5) })
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#NewLISP
|
NewLISP
|
> (flat '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#PicoLisp
|
PicoLisp
|
(setq *PermList
(mapcar chop
(quote
"ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB"
"DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA"
"DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ) ) )
(let (Lst (chop "ABCD") L Lst)
(recur (L) # Permute
(if (cdr L)
(do (length L)
(recurse (cdr L))
(rot L) )
(unless (member Lst *PermList) # Check
(prinl Lst) ) ) ) )
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#PowerShell
|
PowerShell
|
function permutation ($array) {
function generate($n, $array, $A) {
if($n -eq 1) {
$array[$A] -join ''
}
else{
for( $i = 0; $i -lt ($n - 1); $i += 1) {
generate ($n - 1) $array $A
if($n % 2 -eq 0){
$i1, $i2 = $i, ($n-1)
$temp = $A[$i1]
$A[$i1] = $A[$i2]
$A[$i2] = $temp
}
else{
$i1, $i2 = 0, ($n-1)
$temp = $A[$i1]
$A[$i1] = $A[$i2]
$A[$i2] = $temp
}
}
generate ($n - 1) $array $A
}
}
$n = $array.Count
if($n -gt 0) {
(generate $n $array (0..($n-1)))
} else {$array}
}
$perm = permutation @('A','B','C', 'D')
$find = @(
"ABCD"
"CABD"
"ACDB"
"DACB"
"BCDA"
"ACBD"
"ADCB"
"CDAB"
"DABC"
"BCAD"
"CADB"
"CDBA"
"CBAD"
"ABDC"
"ADBC"
"BDCA"
"DCBA"
"BACD"
"BADC"
"BDAC"
"CBDA"
"DBCA"
"DCAB"
)
$perm | where{-not $find.Contains($_)}
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Smalltalk
|
Smalltalk
|
Pharo Smalltalk
[ :yr | | firstDay firstSunday |
firstDay := Date year: yr month: 1 day: 1.
firstSunday := firstDay addDays: (1 - firstDay dayOfWeek).
(0 to: 53)
collect: [ :each | firstSunday addDays: (each * 7) ]
thenSelect: [ :each |
(((Date daysInMonth: each monthIndex forYear: yr) - each dayOfMonth) <= 6) and: [ each year = yr ] ] ]
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Stata
|
Stata
|
program last_sundays
args year
clear
qui set obs 12
gen day=dofm(mofd(mdy(_n,1,`year'))+1)-1
qui replace day=day-mod(dow(day),7)
format %td day
list, noobs noheader sep(6)
end
last_sundays 2013
+-----------+
| 27jan2013 |
| 24feb2013 |
| 31mar2013 |
| 28apr2013 |
| 26may2013 |
| 30jun2013 |
|-----------|
| 28jul2013 |
| 25aug2013 |
| 29sep2013 |
| 27oct2013 |
| 24nov2013 |
| 29dec2013 |
+-----------+
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Casio_BASIC
|
Casio BASIC
|
(* FizzBuzz in CDuce *)
let format (n : Int) : Latin1 =
if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz"
else if (n mod 5 = 0) then "Buzz"
else if (n mod 3 = 0) then "Fizz"
else string_of (n);;
let fizz (n : Int, size : Int) : _ =
print (format (n) @ "\n");
if (n = size) then
n = 0 (* do nothing *)
else
fizz(n + 1, size);;
let fizbuzz (size : Int) : _ = fizz (1, size);;
let _ = fizbuzz(100);;
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#REXX
|
REXX
|
/*REXX program finds months that contain five weekends (given a date range). */
month. =31; month.2=0 /*month days; February is skipped. */
month.4=30; month.6=30; month.9=30; month.11=30 /*all the months with thirty-days. */
parse arg yStart yStop . /*get the "start" and "stop" years.*/
if yStart=='' | yStart=="," then yStart= 1900 /*Not specified? Then use the default.*/
if yStop =='' | yStop =="," then yStop = 2100 /* " " " " " " */
years=yStop - yStart + 1 /*calculate the number of yrs in range.*/
haps=0 /*number of five weekends happenings. */
!.=0; @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
do y=yStart to yStop /*process the years specified. */
do m=1 for 12; wd.=0 /*process each month and also each year*/
do d=1 for month.m; dat_= y"-"right(m,2,0)'-'right(d,2,0)
parse upper value date('W', dat_, "I") with ? 3
wd.?=wd.?+1 /*? is the first two chars of weekday.*/
end /*d*/ /*WD.su = number of Sundays in a month.*/
if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate /*five weekends ?*/
say 'There are five weekends in' y date('M', dat_, "I")
haps=haps+1; !.y=1 /*bump counter; indicate yr has 5 WE's.*/
end /*m*/
end /*y*/
say
say "There were " haps ' occurrence's(haps) "of" @5w 'in year's(years) yStart"──►"yStop
say; #=0
do y=yStart to yStop; if !.y then iterate /*skip if OK.*/
#=#+1; say 'Year ' y " doesn't have any" @5wem'.'
end /*y*/
say
say "There are " # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#Tcl
|
Tcl
|
% namespace path tcl::mathfunc ;# to import functions like abs() etc.
% proc cube x {expr {$x**3}}
% proc croot x {expr {$x**(1/3.)}}
% proc compose {f g} {list apply {{f g x} {{*}$f [{*}$g $x]}} $f $g}
% compose abs cube ;# returns a partial command, without argument
apply {{f g x} {{*}$f [{*}$g $x]}} abs cube
% {*}[compose abs cube] -3 ;# applies the partial command to argument -3
27
% set forward [compose [compose sin cos] cube] ;# omitting to print result
% set backward [compose croot [compose acos asin]]
% {*}$forward 0.5
0.8372297964617733
% {*}$backward [{*}$forward 0.5]
0.5000000000000017
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#NGS
|
NGS
|
F flatten_r(a:Arr)
collector {
local kern
F kern(x) collect(x)
F kern(x:Arr) x.each(kern)
kern(a)
}
echo(flatten_r([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]))
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#PureBasic
|
PureBasic
|
Procedure in_List(in.s)
Define.i i, j
Define.s a
Restore data_to_test
For i=1 To 3*8-1
Read.s a
If in=a
ProcedureReturn #True
EndIf
Next i
ProcedureReturn #False
EndProcedure
Define.c z, x, c, v
If OpenConsole()
For z='A' To 'D'
For x='A' To 'D'
If z=x:Continue:EndIf
For c='A' To 'D'
If c=x Or c=z:Continue:EndIf
For v='A' To 'D'
If v=c Or v=x Or v=z:Continue:EndIf
Define.s test=Chr(z)+Chr(x)+Chr(c)+Chr(v)
If Not in_List(test)
PrintN(test+" is missing.")
EndIf
Next
Next
Next
Next
PrintN("Press Enter to exit"):Input()
EndIf
DataSection
data_to_test:
Data.s "ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB"
Data.s "DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA"
Data.s "DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"
EndDataSection
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Swift
|
Swift
|
import Foundation
func lastSundays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 1...12 {
var dateComponents = DateComponents(calendar: calendar,
year: year,
month: month + 1,
day: 0,
hour: 12)
let date = calendar.date(from: dateComponents)!
let weekday = calendar.component(.weekday, from: date)
if weekday != 1 {
dateComponents.day! -= weekday - 1
}
dates.append(calendar.date(from: dateComponents)!)
}
return dates
}
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Tcl
|
Tcl
|
proc lastSundays {{year ""}} {
if {$year eq ""} {
set year [clock format [clock seconds] -gmt 1 -format "%Y"]
}
foreach month {2 3 4 5 6 7 8 9 10 11 12 13} {
set d [clock add [clock scan "$month/1/$year" -gmt 1] -1 day]
while {[clock format $d -gmt 1 -format "%u"] != 7} {
set d [clock add $d -1 day]
}
lappend result [clock format $d -gmt 1 -format "%Y-%m-%d"]
}
return $result
}
puts [join [lastSundays {*}$argv] "\n"]
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Cduce
|
Cduce
|
(* FizzBuzz in CDuce *)
let format (n : Int) : Latin1 =
if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz"
else if (n mod 5 = 0) then "Buzz"
else if (n mod 3 = 0) then "Fizz"
else string_of (n);;
let fizz (n : Int, size : Int) : _ =
print (format (n) @ "\n");
if (n = size) then
n = 0 (* do nothing *)
else
fizz(n + 1, size);;
let fizbuzz (size : Int) : _ = fizz (1, size);;
let _ = fizbuzz(100);;
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Ring
|
Ring
|
sum = 0
month = list(12)
mo = [4,0,0,3,5,1,3,6,2,4,0,2]
mon = [31,28,31,30,31,30,31,31,30,31,30,31]
mont = ["January","February","March","April","May","June",
"July","August","September","October","November","December"]
for year = 1900 to 2100
if year < 2100 leap = year - 1900 else leap = year - 1904 ok
m = ((year-1900)%7) + floor(leap/4) % 7
oldsum = sum
for n = 1 to 12
month[n] = (mo[n] + m) % 7
x = (month[n] + 1) % 7
if x = 2 and mon[n] = 31 sum += 1 see "" + year + "-" + mont[n] + nl ok
next
if sum = oldsum see "" + year + "-" + "(none)" + nl ok
next
see "Total : " + sum + nl
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Ruby
|
Ruby
|
require 'date'
# The only case where the month has 5 weekends is when the last day
# of the month falls on a Sunday and the month has 31 days.
LONG_MONTHS = [1,3,5,7,8,10,12]
YEARS = (1900..2100).to_a
dates = YEARS.product(LONG_MONTHS).map{|y, m| Date.new(y,m,31)}.select(&:sunday?)
years_4w = YEARS - dates.map(&:year)
puts "There are #{dates.size} months with 5 weekends from 1900 to 2100:"
puts dates.first(5).map {|d| d.strftime("%b %Y") }, "..."
puts dates.last(5).map {|d| d.strftime("%b %Y") }
puts "There are #{years_4w.size} years without months with 5 weekends:"
puts years_4w.join(", ")
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#TI-89_BASIC
|
TI-89 BASIC
|
Prgm
Local funs,invs,composed,x,i
Define rc_cube(x) = x^3 © Cannot be local variables
Define rc_curt(x) = x^(1/3)
Define funs = {"sin","cos","rc_cube"}
Define invs = {"sin","cos","rc_curt"}
Define x = 0.5
Disp "x = " & string(x)
For i,1,3
Disp "f=" & invs[i] & " g=" & funs[i] & " f(g(x))=" & string(#(invs[i])(#(funs[i])(x)))
EndFor
DelVar rc_cube,rc_curt © Clean up our globals
EndPrgm
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#TXR
|
TXR
|
(defvar funlist [list sin
cos
(op expt @1 3)])
(defvar invlist [list asin
acos
(op expt @1 (/ 1 3))])
(each ((f funlist) (i invlist))
(prinl [(chain f i) 0.5]))
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Nim
|
Nim
|
type
TreeList[T] = object
case isLeaf: bool
of true: data: T
of false: list: seq[TreeList[T]]
proc L[T](list: varargs[TreeList[T]]): TreeList[T] =
for x in list:
result.list.add x
proc N[T](data: T): TreeList[T] =
TreeList[T](isLeaf: true, data: data)
proc flatten[T](n: TreeList[T]): seq[T] =
if n.isLeaf: result = @[n.data]
else:
for x in n.list:
result.add flatten x
var x = L(L(N 1), N 2, L(L(N 3, N 4), N 5), L(L(L[int]())), L(L(L(N 6))), N 7, N 8, L[int]())
echo flatten(x)
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Python
|
Python
|
from itertools import permutations
given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()
allPerms = [''.join(x) for x in permutations(given[0])]
missing = list(set(allPerms) - set(given)) # ['DBAC']
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#UNIX_Shell
|
UNIX Shell
|
last_sundays() {
local y=$1
for (( m=1; m<=12; ++m )); do
cal $m $y | awk -vy=$y -vm=$m '/^.[0-9]/ {d=$1} END {print y"-"m"-"d}'
done
}
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#VBScript
|
VBScript
|
strYear = WScript.StdIn.ReadLine
For i = 1 To 12
d = DateSerial(strYear, i + 1, 1) - 1
WScript.Echo d - Weekday(d) + 1
Next
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Ceylon
|
Ceylon
|
shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Run_BASIC
|
Run BASIC
|
preYear = 1900
for yyyy = 1900 to 2100
for mm = 1 to 12 ' go thru all 12 months
dayOne$ = mm;"-01-";yyyy ' First day of month
n = date$(dayOne$) ' Days since 1700
dow = 1 + (n mod 7) ' Day of Week month begins
m1 = mm '
n1 = n + 27 ' find end of month starting with 27th day
while m1 = mm ' if month changes we have the end of the month
n1 = n1 + 1
n$ = date$(n1)
m1 = val(left$(n$,2))
wend
mmDays = n1 - n ' Days in the Month
if dow = 4 and mmDays = 31 then ' test for 5 weeks
count = count + 1
print using("###",count);" ";yyyy;"-";left$("0";mm,2)
end if
next mm
if preCount = count then
noCount = noCount + 1 ' count years that have none
print yyyy;" has none ";noCount
end if
preCount = count
next yyyy
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Rust
|
Rust
|
extern crate chrono;
use chrono::prelude::*;
/// Months with 31 days
const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12];
/// Get all the tuples (year, month) in wich there is five Fridays, five Saturdays and five Sundays
/// between the years start and end (inclusive).
fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> {
let mut out = vec![];
for year in start..=end {
for month in LONGMONTHS.iter() {
// Five weekends if a 31-days month starts with a Friday.
if Local.ymd(year, *month, 1).weekday() == Weekday::Fri {
out.push((year, *month));
}
}
}
out
}
fn main() {
let out = five_weekends(1900, 2100);
let len = out.len();
println!(
"There are {} months of which the first and last five are:",
len
);
for (y, m) in &out[..5] {
println!("\t{} / {}", y, m);
}
println!("...");
for (y, m) in &out[(len - 5..)] {
println!("\t{} / {}", y, m);
}
}
#[test]
fn test() {
let out = five_weekends(1900, 2100);
assert_eq!(out.len(), 201);
}
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#Ursala
|
Ursala
|
#import std
#import flo
functions = <sin,cos,times^/~& sqr>
inverses = <asin,acos,math..cbrt>
#cast %eL
main = (gang (+)*p\functions inverses) 0.5
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#Wren
|
Wren
|
var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
var A = [
Fn.new { |x| x.sin },
Fn.new { |x| x.cos },
Fn.new { |x| x * x * x }
]
var B = [
Fn.new { |x| x.asin },
Fn.new { |x| x.acos },
Fn.new { |x| x.pow(1/3) }
]
var x = 0.5
for (i in 0..2) {
System.print(compose.call(A[i], B[i]).call(x))
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
@interface NSArray (FlattenExt)
@property (nonatomic, readonly) NSArray *flattened;
@end
@implementation NSArray (FlattenExt)
-(NSArray *) flattened {
NSMutableArray *flattened = [[NSMutableArray alloc] initWithCapacity:self.count];
for (id object in self) {
if ([object isKindOfClass:[NSArray class]])
[flattened addObjectsFromArray:((NSArray *)object).flattened];
else
[flattened addObject:object];
}
return [flattened autorelease];
}
@end
int main() {
@autoreleasepool {
NSArray *p = @[
@[ @1 ],
@2,
@[ @[@3, @4], @5],
@[ @[ @[ ] ] ],
@[ @[ @[ @6 ] ] ],
@7,
@8,
@[ ] ];
for (id object in unflattened.flattened)
NSLog(@"%@", object);
}
return 0;
}
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Quackery
|
Quackery
|
$ "ABCD CABD ACDB DACB BCDA ACBD
ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD
BADC BDAC CBDA DBCA DCAB" nest$
16 base put
[] swap
witheach [ $->n drop join ]
0 swap witheach ^
number$ echo$
base release
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#R
|
R
|
library(combinat)
permute.me <- c("A", "B", "C", "D")
perms <- permn(permute.me) # list of all permutations
perms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T) # matrix of all permutations
perms3 <- apply(perms2, 1, paste, collapse="") # vector of all permutations
incomplete <- c("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")
setdiff(perms3, incomplete)
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Wren
|
Wren
|
import "os" for Process
import "/date" for Date
var args = Process.arguments
if (args.count != 1) {
Fiber.abort("Please pass just the year to be processed.")
}
var year = Num.fromString(args[0])
System.print("The dates of the last Sundays in the month for %(year) are:")
Date.default = Date.isoDate
for (m in 1..12) {
var d = Date.monthLength(year, m)
var dt = Date.new(year, m, d)
var wd = dt.dayOfWeek
if (wd == 7) {
System.print(dt)
} else {
System.print(dt.addDays(-wd))
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Chapel
|
Chapel
|
proc fizzbuzz(n) {
for i in 1..n do
if i % 15 == 0 then
writeln("FizzBuzz");
else if i % 5 == 0 then
writeln("Buzz");
else if i % 3 == 0 then
writeln("Fizz");
else
writeln(i);
}
fizzbuzz(100);
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Scala
|
Scala
|
import java.util.Calendar._
import java.util.GregorianCalendar
import org.scalatest.{FlatSpec, Matchers}
class FiveWeekends extends FlatSpec with Matchers {
case class YearMonth[T](year: T, month: T)
implicit class CartesianProd[T](val seq: Seq[T]) {
def x(other: Seq[T]) = for(s1 <- seq; s2 <- other) yield YearMonth(year=s1,month=s2)
def -(other: Seq[T]): Seq[T] = seq diff other
}
def has5weekends(ym: { val year: Int; val month: Int}) = {
val date = new GregorianCalendar(ym.year, ym.month-1, 1)
date.get(DAY_OF_WEEK) == FRIDAY && date.getActualMaximum(DAY_OF_MONTH) == 31
}
val expectedFirstFive = Seq(
YearMonth(1901,3), YearMonth(1902,8), YearMonth(1903,5), YearMonth(1904,1), YearMonth(1904,7))
val expectedFinalFive = Seq(
YearMonth(2097,3), YearMonth(2098,8), YearMonth(2099,5), YearMonth(2100,1), YearMonth(2100,10))
val expectedNon5erYears = Seq(1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962,
1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035,
2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096)
"Five Weekend Algorithm" should "match specification" in {
val months = (1900 to 2100) x (1 to 12) filter has5weekends
months.size shouldBe 201
months.take(5) shouldBe expectedFirstFive
months.takeRight(5) shouldBe expectedFinalFive
(1900 to 2100) - months.map(_.year) shouldBe expectedNon5erYears
}
}
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#XBS
|
XBS
|
func cube(x:number):number{
send x^3;
}
func cuberoot(x:number):number{
send x^(1/3);
}
func compose(f:function,g:function):function{
send func(n:number){
send f(g(n));
}
}
const a:[function]=[math.sin,math.cos,cube];
const b:[function]=[math.asin,math.acos,cuberoot];
each a as k,v{
log(compose(v,b[k])(0.5))
}
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#zkl
|
zkl
|
var a=T(fcn(x){ x.toRad().sin() }, fcn(x){ x.toRad().cos() }, fcn(x){ x*x*x} );
var b=T(fcn(x){ x.asin().toDeg() }, fcn(x){ x.acos().toDeg() }, fcn(x){ x.pow(1.0/3) });
var H=Utils.Helpers;
var ab=b.zipWith(H.fcomp,a); //-->list of deferred calculations
ab.run(True,5.0); //-->L(5.0,5.0,5.0)
a.run(True,5.0) //-->L(0.0871557,0.996195,125)
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#OCaml
|
OCaml
|
# let flatten = List.concat ;;
val flatten : 'a list list -> 'a list = <fun>
# let li = [[1]; 2; [[3;4]; 5]; [[[]]]; [[[6]]]; 7; 8; []] ;;
^^^
Error: This expression has type int but is here used with type int list
# (* use another data which can be accepted by the type system *)
flatten [[1]; [2; 3; 4]; []; [5; 6]; [7]; [8]] ;;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8]
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Racket
|
Racket
|
#lang racket
(define almost-all
'([A B C D] [C A B D] [A C D B] [D A C B] [B C D A] [A C B D] [A D C B]
[C D A B] [D A B C] [B C A D] [C A D B] [C D B A] [C B A D] [A B D C]
[A D B C] [B D C A] [D C B A] [B A C D] [B A D C] [B D A C] [C B D A]
[D B C A] [D C A B]))
;; Obvious method:
(for/first ([p (in-permutations (car almost-all))]
#:unless (member p almost-all))
p)
;; -> '(D B A C)
;; For permutations of any set
(define charmap
(for/hash ([x (in-list (car almost-all))] [i (in-naturals)])
(values x i)))
(define size (hash-count charmap))
;; Illustrating approach mentioned in the task description.
;; For each position, character with odd parity at that position.
(require data/bit-vector)
(for/list ([i (in-range size)])
(define parities (make-bit-vector size #f))
(for ([permutation (in-list almost-all)])
(define n (hash-ref charmap (list-ref permutation i)))
(bit-vector-set! parities n (not (bit-vector-ref parities n))))
(for/first ([(c i) charmap] #:when (bit-vector-ref parities i))
c))
;; -> '(D B A C)
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#XPL0
|
XPL0
|
func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat)
int Year, Month, Day; \works for years from 1583 onward
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400)/7);
];
int Year, Month, LastDay, WD;
[Year:= IntIn(8); \from command line
for Month:= 1 to 12 do
[LastDay:= WeekDay(Year, Month+1, 1) - WeekDay(Year, Month, 28);
if LastDay < 0 then LastDay:= LastDay + 7;
LastDay:= LastDay + 27; \ = number of days in Month
WD:= WeekDay(Year, Month, LastDay);
LastDay:= LastDay - WD;
IntOut(0, Year); ChOut(0, ^-);
if Month < 10 then ChOut(0, ^0); IntOut(0, Month); ChOut(0, ^-);
IntOut(0, LastDay); CrLf(0);
];
]
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#zkl
|
zkl
|
var [const] D=Time.Date;
lastDay(2013,D.Sunday)
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Chef
|
Chef
|
main() {
for(i in range(1,100)) {
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz");
else if(i % 3 == 0) println("fizz");
else if(i % 5 == 0) println("buzz");
else print(i);
}
}
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
local
var integer: months is 0;
var time: firstDayInMonth is time.value;
begin
for firstDayInMonth.year range 1900 to 2100 do
for firstDayInMonth.month range 1 to 12 do
if daysInMonth(firstDayInMonth) = 31 and dayOfWeek(firstDayInMonth) = 5 then
writeln(firstDayInMonth.year <& "-" <& firstDayInMonth.month lpad0 2);
incr(months);
end if;
end for;
end for;
writeln("Number of months:" <& months);
end func;
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Oforth
|
Oforth
|
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] expand println
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Raku
|
Raku
|
my @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;
my @perms = <A B C D>.permutations.map: *.join;
.say when none(@givens) for @perms;
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Clay
|
Clay
|
main() {
for(i in range(1,100)) {
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz");
else if(i % 3 == 0) println("fizz");
else if(i % 5 == 0) println("buzz");
else print(i);
}
}
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Sidef
|
Sidef
|
require('DateTime');
var happymonths = [];
var workhardyears = [];
var longmonths = [1, 3, 5, 7, 8, 10, 12];
range(1900, 2100).each { |year|
var countmonths = 0;
longmonths.each { |month|
var dt = %s'DateTime'.new(
year => year,
month => month,
day => 1
);
if (dt.day_of_week == 5) {
countmonths++;
var yearfound = dt.year;
var monthfound = dt.month_name;
happymonths.append(join(" ", yearfound, monthfound));
}
}
if (countmonths == 0) {
workhardyears.append(year);
}
}
say "There are #{happymonths.len} months with 5 full weekends!";
say "The first 5 and the last 5 of them are:";
say happymonths.first(5).join("\n");
say happymonths.last(5).join("\n");
say "No long weekends in the following #{workhardyears.len} years:";
say workhardyears.join(",");
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Ol
|
Ol
|
(define (flatten x)
(cond
((null? x)
'())
((not (pair? x))
(list x))
(else
(append (flatten (car x))
(flatten (cdr x))))))
(print
(flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ())))
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#RapidQ
|
RapidQ
|
Dim PList as QStringList
PList.addItems "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB"
PList.additems "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA"
PList.additems "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
Dim NumChar(4, 65 to 68) as integer
Dim MPerm as string
'Create table with occurences
For x = 0 to PList.Itemcount -1
for y = 1 to 4
Inc(NumChar(y, asc(PList.Item(x)[y])))
next
next
'When a char only occurs 5 times it's the missing one
for x = 1 to 4
for y = 65 to 68
MPerm = MPerm + iif(NumChar(x, y)=5, chr$(y), "")
next
next
showmessage MPerm
'= DBAC
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Clipper
|
Clipper
|
PROCEDURE Main()
LOCAL n
LOCAL cFB
FOR n := 1 TO 100
cFB := ""
AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } )
?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " )
NEXT
RETURN
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Simula
|
Simula
|
! TRANSLATION OF FREEBASIC VERSION ;
BEGIN
INTEGER PROCEDURE WD(M, D, Y); INTEGER M, D, Y;
BEGIN
! ZELLERISH
! 0 = SUNDAY, 1 = MONDAY, 2 = TUESDAY, 3 = WEDNESDAY
! 4 = THURSDAY, 5 = FRIDAY, 6 = SATURDAY
;
IF M < 3 THEN ! IF M = 1 OR M = 2 THEN ;
BEGIN
M := M + 12;
Y := Y - 1
END;
WD := MOD(Y + (Y // 4)
- (Y // 100)
+ (Y // 400)
+ D + ((153 * M + 8) // 5), 7)
END WD;
! ------=< MAIN >=------
! ONLY MONTHS WITH 31 DAY CAN HAVE FIVE WEEKENDS
! THESE MONTHS ARE: JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER
! IN NR: 1, 3, 5, 7, 8, 10, 12
! THE 1E DAY NEEDS TO BE ON A FRIDAY (= 5)
;
TEXT PROCEDURE MONTHNAMES(M); INTEGER M;
MONTHNAMES :- IF M = 1 THEN "JANUARY"
ELSE IF M = 2 THEN "FEBRUARY"
ELSE IF M = 3 THEN "MARCH"
ELSE IF M = 4 THEN "APRIL"
ELSE IF M = 5 THEN "MAY"
ELSE IF M = 6 THEN "JUNE"
ELSE IF M = 7 THEN "JULY"
ELSE IF M = 8 THEN "AUGUST"
ELSE IF M = 9 THEN "SEPTEMBER"
ELSE IF M = 10 THEN "OCTOBER"
ELSE IF M = 11 THEN "NOVEMBER"
ELSE IF M = 12 THEN "DECEMBER"
ELSE NOTEXT;
INTEGER M, YR, TOTAL, I, J;
INTEGER ARRAY YR_WITHOUT(1:200);
TEXT ANSWER;
FOR YR := 1900 STEP 1 UNTIL 2100 DO ! GREGORIAN CALENDAR ;
BEGIN
ANSWER :- NOTEXT;
FOR M := 1 STEP 2 UNTIL 12 DO
BEGIN
IF M = 9 THEN M := 8;
IF WD(M, 1, YR) = 5 THEN
BEGIN
ANSWER :- ANSWER & MONTHNAMES(M) & ", ";
TOTAL := TOTAL + 1
END
END;
IF ANSWER =/= NOTEXT THEN
BEGIN
OUTIMAGE;
OUTINT(YR, 4); OUTTEXT(" | ");
OUTTEXT(ANSWER.SUB(1, ANSWER.LENGTH - 2)) ! GET RID OF EXTRA " ," ;
END
ELSE
BEGIN
I := I + 1;
YR_WITHOUT(I) := YR
END
END;
OUTIMAGE;
OUTTEXT("NR OF MONTH FOR 1900 TO 2100 THAT HAS FIVE WEEKENDS ");
OUTINT(TOTAL, 0);
OUTIMAGE;
OUTIMAGE;
OUTINT(I, 0);
OUTTEXT(" YEARS DON'T HAVE MONTHS WITH FIVE WEEKENDS");
OUTIMAGE;
FOR J := 1 STEP 1 UNTIL I DO
BEGIN
OUTINT(YR_WITHOUT(J), 0); OUTCHAR(' ');
IF MOD(J, 8) = 0 THEN OUTIMAGE
END;
OUTIMAGE
END.
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Stata
|
Stata
|
clear
set obs `=tm(2101m1)-tm(1900m1)'
gen month=tm(1900m1)+_n-1
format %tm month
gen day=dofm(month)
keep if dofm(month+1)-day==31 & dow(day)==5
drop day
count
201
list in f/5, noobs noheader
+--------+
| 1901m3 |
| 1902m8 |
| 1903m5 |
| 1904m1 |
| 1904m7 |
+--------+
list in -5/l, noobs noheader
+---------+
| 2097m3 |
| 2098m8 |
| 2099m5 |
| 2100m1 |
| 2100m10 |
+---------+
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#ooRexx
|
ooRexx
|
sub1 = .array~of(1)
sub2 = .array~of(3, 4)
sub3 = .array~of(sub2, 5)
sub4 = .array~of(.array~of(.array~new))
sub5 = .array~of(.array~of(.array~of(6)))
sub6 = .array~new
-- final list construction
list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6)
-- flatten
flatlist = flattenList(list)
say "["flatlist~toString("line", ", ")"]"
::routine flattenList
use arg list
-- we could use a list or queue, but let's just use an array
accumulator = .array~new
-- now go to the recursive processing version
call flattenSublist list, accumulator
return accumulator
::routine flattenSublist
use arg list, accumulator
-- ask for the items explicitly, since this will allow
-- us to flatten indexed collections as well
do item over list~allItems
-- if the object is some sort of collection, flatten this out rather
-- than add to the accumulator
if item~isA(.collection) then call flattenSublist item, accumulator
else accumulator~append(item)
end
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#REXX
|
REXX
|
/*REXX pgm finds one or more missing permutations from an internal list & displays them.*/
list= 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA',
"DCBA BACD BADC BDAC CBDA DBCA DCAB" /*list that is missing one permutation.*/
@.= /* [↓] needs to be as long as THINGS.*/
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*an uppercase (Latin/Roman) alphabet. */
things= 4 /*number of unique letters to be used. */
bunch = 4 /*number letters to be used at a time. */
do j=1 for things /* [↓] only get a portion of alphabet.*/
$.j= substr(@abcU, j, 1) /*extract just one letter from alphabet*/
end /*j*/ /* [↑] build a letter array for speed.*/
call permSet 1 /*invoke PERMSET subroutine recursively*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
permSet: procedure expose $. @. bunch list things; parse arg ? /*calls self recursively.*/
if ?>bunch then do; _=
do m=1 for bunch /*build a permutation. */
_= _ || @.m /*add permutation──►list.*/
end /*m*/
/* [↓] is in the list? */
if wordpos(_,list)==0 then say _ ' is missing from the list.'
end
else do x=1 for things /*build a permutation. */
do k=1 for ?-1
if @.k==$.x then iterate x /*was permutation built? */
end /*k*/
@.?= $.x /*define as being built. */
call permSet ?+1 /*call self recursively. */
end /*x*/
return
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#CLIPS
|
CLIPS
|
(deffacts count
(count-to 100)
)
(defrule print-numbers
(count-to ?max)
=>
(loop-for-count (?num ?max) do
(if
(= (mod ?num 3) 0)
then
(printout t "Fizz")
)
(if
(= (mod ?num 5) 0)
then
(printout t "Buzz")
)
(if
(and (> (mod ?num 3) 0) (> (mod ?num 5) 0))
then
(printout t ?num)
)
(priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf)
)
)
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Tcl
|
Tcl
|
package require Tcl 8.5
set months {}
set years {}
for {set year 1900} {$year <= 2100} {incr year} {
set count [llength $months]
foreach month {Jan Mar May Jul Aug Oct Dec} {
set date [clock scan "$month/01/$year" -format "%b/%d/%Y" -locale en_US]
if {[clock format $date -format %u] == 5} {
# Month with 31 days that starts on a Friday => has 5 weekends
lappend months "$month $year"
}
}
if {$count == [llength $months]} {
# No change to number of months; year must've been without
lappend years $year
}
}
puts "There are [llength $months] months with five weekends"
puts [join [list {*}[lrange $months 0 4] ... {*}[lrange $months end-4 end]] \n]
puts "There are [llength $years] years without any five-weekend months"
puts [join $years ","]
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Oz
|
Oz
|
{Show {Flatten [[1] 2 [[3 4] 5] [[nil]] [[[6]]] 7 8 nil]}}
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Ring
|
Ring
|
list = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
for a = ascii("A") to ascii("D")
for b = ascii("A") to ascii("D")
for c = ascii("A") to ascii("D")
for d = ascii("A") to ascii("D")
x = char(a) + char(b) + char(c)+ char(d)
if a!=b and a!=c and a!=d and b!=c and b!=d and c!=d
if substr(list,x) = 0 see x + " missing" + nl ok ok
next
next
next
next
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Ruby
|
Ruby
|
given = %w{
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB
}
all = given[0].chars.permutation.collect(&:join)
puts "missing: #{all - given}"
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Clojure
|
Clojure
|
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
LOOP year=1900,2100
LOOP month="1'3'5'7'8'10'12"
SET dayofweek=DATE (number,1,month,year,nummer)
IF (dayofweek==5) PRINT year,"-",month
ENDLOOP
ENDLOOP
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#uBasic.2F4tH
|
uBasic/4tH
|
' ------=< MAIN >=------
' only months with 31 day can have five weekends
' these months are: January, March, May, July, August, October, December
' in nr: 1, 3, 5, 7, 8, 10, 12
' the 1e day needs to be on a friday (= 5)
For y = 1900 To 2100 ' Gregorian calendar
a = 0
For m = 1 To 12 Step 2
If m = 9 Then m = 8
If Func(_wd(m , 1 , y)) = 5 Then
If a Then
Print ", ";
Else
Print y; " | ";
a = 1
EndIf
GoSub m*10
t = t + 1
EndIf
Next
If a Then
Print
Else
i = i + 1
@(i) = y
EndIf
Next
Print
Print "Number of months from 1900 to 2100 that have five weekends: ";t
Print
Print i;" years don't have months with five weekends:"
Print
For j = 1 To i
Print @(j); " ";
If (j % 8) = 0 Then Print
Next
Print
End
_wd Param(3)
' Zellerish
' 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday
' 4 = Thursday, 5 = Friday, 6 = Saturday
If a@ < 3 Then ' If a@ = 1 Or a@ = 2 Then
a@ = a@ + 12
c@ = c@ - 1
EndIf
Return ((c@ + (c@ / 4) - (c@ / 100) + (c@ / 400) + b@ + ((153 * a@ + 8) / 5)) % 7)
10 Print "January"; : Return
20 Print "February"; : Return
30 Print "March"; : Return
40 Print "April"; : Return
50 Print "May"; : Return
60 Print "June"; : Return
70 Print "July"; : Return
80 Print "August"; : Return
90 Print "September"; : Return
100 Print "October"; : Return
110 Print "November"; : Return
120 Print "December"; : Return
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PARI.2FGP
|
PARI/GP
|
flatten(v)={
my(u=[]);
for(i=1,#v,
u=concat(u,if(type(v[i])=="t_VEC",flatten(v[i]),v[i]))
);
u
};
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Run_BASIC
|
Run BASIC
|
list$ = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
for a = asc("A") to asc("D")
for b = asc("A") to asc("D")
for c = asc("A") to asc("D")
for d = asc("A") to asc("D")
x$ = chr$(a) + chr$(b) + chr$(c)+ chr$(d)
for i = 1 to 4 ' make sure each letter is unique
j = instr(x$,mid$(x$,i,1))
if instr(x$,mid$(x$,i,1),j + 1) <> 0 then goto [nxt]
next i
if instr(list$,x$) = 0 then print x$;" missing" ' found missing permutation
[nxt] next d
next c
next b
next a
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#CLU
|
CLU
|
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1, 100) do
out: string := ""
if i // 3 = 0 then out := out || "Fizz" end
if i // 5 = 0 then out := out || "Buzz" end
if string$empty(out) then out := int$unparse(i) end
stream$putl(po, out)
end
end start_up
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#UNIX_Shell
|
UNIX Shell
|
echo "Creating cal-file..."
echo > cal.txt
for ((y=1900; y <= 2100; y++)); do
for ((m=1; m <= 12; m++)); do
#echo $m $y
cal -m $m $y >> cal.txt
done
done
ls -la cal.txt
echo "Looking for month with 5 weekends:"
awk -f 5weekends.awk cal.txt
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Perl
|
Perl
|
sub flatten {
map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_
}
my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []);
print flatten(@lst), "\n";
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Rust
|
Rust
|
const GIVEN_PERMUTATIONS: [&str; 23] = [
"ABCD",
"CABD",
"ACDB",
"DACB",
"BCDA",
"ACBD",
"ADCB",
"CDAB",
"DABC",
"BCAD",
"CADB",
"CDBA",
"CBAD",
"ABDC",
"ADBC",
"BDCA",
"DCBA",
"BACD",
"BADC",
"BDAC",
"CBDA",
"DBCA",
"DCAB"
];
fn main() {
const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len();
let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN];
for permutation in &GIVEN_PERMUTATIONS {
for (i, val) in permutation.bytes().enumerate() {
bytes_result[i] ^= val;
}
}
println!("{}", std::str::from_utf8(&bytes_result).unwrap());
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#CMake
|
CMake
|
foreach(i RANGE 1 100)
math(EXPR off3 "${i} % 3")
math(EXPR off5 "${i} % 5")
if(NOT off3 AND NOT off5)
message(FizzBuzz)
elseif(NOT off3)
message(Fizz)
elseif(NOT off5)
message(Buzz)
else()
message(${i})
endif()
endforeach(i)
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#VBA
|
VBA
|
Option Explicit
Sub Main()
Dim y As Long, m As Long, t As String, cpt As Long, cptm As Long
For y = 1900 To 2100
t = vbNullString
For m = 1 To 12 Step 2
If m = 9 Then m = 8
If Weekday(DateSerial(y, m, 1)) = vbFriday Then
t = t & ", " & m
cptm = cptm + 1
End If
Next
If t <> "" Then
Debug.Print y & t
Else
cpt = cpt + 1
End If
Next
Debug.Print "There is " & cptm & " months with five full weekends from the year 1900 through 2100"
Debug.Print "There is " & cpt & " years which don't have months with five weekends"
End Sub
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Phix
|
Phix
|
?flatten({{1},2,{{3,4},5},{{{}}},{{{6}}},7,8,{}})
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Scala
|
Scala
|
def fat(n: Int) = (2 to n).foldLeft(1)(_*_)
def perm[A](x: Int, a: Seq[A]): Seq[A] = if (x == 0) a else {
val n = a.size
val fatN1 = fat(n - 1)
val fatN = fatN1 * n
val p = x / fatN1 % fatN
val (before, Seq(el, after @ _*)) = a splitAt p
el +: perm(x % fatN1, before ++ after)
}
def findMissingPerm(start: String, perms: Array[String]): String = {
for {
i <- 0 until fat(start.size)
p = perm(i, start).mkString
} if (!perms.contains(p)) return p
""
}
val perms = """ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB""".stripMargin.split("\n")
println(findMissingPerm(perms(0), perms))
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#COBOL
|
COBOL
|
* FIZZBUZZ.COB
* cobc -x -g FIZZBUZZ.COB
*
IDENTIFICATION DIVISION.
PROGRAM-ID. fizzbuzz.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CNT PIC 9(03) VALUE 1.
01 REM PIC 9(03) VALUE 0.
01 QUOTIENT PIC 9(03) VALUE 0.
PROCEDURE DIVISION.
*
PERFORM UNTIL CNT > 100
DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "FizzBuzz " WITH NO ADVANCING
ELSE
DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "Fizz " WITH NO ADVANCING
ELSE
DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "Buzz " WITH NO ADVANCING
ELSE
DISPLAY CNT " " WITH NO ADVANCING
END-IF
END-IF
END-IF
ADD 1 TO CNT
END-PERFORM
DISPLAY ""
STOP RUN.
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#VBScript
|
VBScript
|
For y = 1900 To 2100
For m = 1 To 12
d = DateSerial(y, m + 1, 1) - 1
If Day(d) = 31 And Weekday(d) = vbSunday Then
WScript.Echo y & ", " & MonthName(m)
i = i + 1
End If
Next
Next
WScript.Echo vbCrLf & "Total = " & i & " months"
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#Wren
|
Wren
|
import "/date" for Date
import "/seq" for Lst
var dates = []
var years = []
for (y in 1900..2100) {
var hasFive = false
for (m in 1..12) {
var fri = 0
var sat = 0
var sun = 0
for (d in 1..Date.monthLength(y, m)) {
var d = Date.new(y, m, d)
var dow = d.dayOfWeek
if (dow == 5) {
fri = fri + 1
} else if (dow == 6) {
sat = sat + 1
} else if (dow == 7) {
sun = sun + 1
}
}
var fd = Date.new(y, m, 1)
if (fri == 5 && sat == 5 && sun == 5) {
dates.add(fd)
hasFive = true
}
}
if (!hasFive) years.add(y)
}
Date.default = "mmm|-|yyyy"
System.print("Between 1900 and 2100:-")
System.print(" There are %(dates.count) months that have five full weekends.")
System.print(" The first 5 are:")
for (i in 0..4) System.print(" %(dates[i])")
System.print(" and the last 5 are:")
for (i in -5..-1) System.print(" %(dates[i])")
System.print("\n There are %(years.count) years that do not have at least one five-weekend month, namely:")
var chunks = Lst.chunks(years, 10)
for (i in 0...chunks.count) System.print(" %(chunks[i])")
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Phixmonti
|
Phixmonti
|
1 2 3 10 20 30 3 tolist 4 5 6 3 tolist 2 tolist 1000 "Hello" 6 tolist
dup print nl flatten print
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func string: missingPermutation (in array string: perms) is func
result
var string: missing is "";
local
var integer: pos is 0;
var set of char: chSet is (set of char).EMPTY_SET;
var string: permutation is "";
var char: ch is ' ';
begin
if length(perms) <> 0 then
for key pos range perms[1] do
chSet := (set of char).EMPTY_SET;
for permutation range perms do
ch := permutation[pos];
if ch in chSet then
excl(chSet, ch);
else
incl(chSet, ch);
end if;
end for;
missing &:= min(chSet);
end for;
end if;
end func;
const proc: main is func
begin
writeln(missingPermutation([] ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
"BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")));
end func;
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Sidef
|
Sidef
|
func check_perm(arr) {
var hash = Hash()
hash.set_keys(arr...)
arr.each { |s|
{
var t = (s.substr(1) + s.substr(0, 1))
hash.has_key(t) || return t
} * s.len
}
}
var perms = %w(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB)
say check_perm(perms)
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Coco
|
Coco
|
for i from 1 to 100
console.log do
if i % 15 == 0 then 'FizzBuzz'
else if i % 3 == 0 then 'Fizz'
else if i % 5 == 0 then 'Buzz'
else i
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
func WeekDay(Year, Month, Day); \Return day of week (0=Sat 1=Sun..6=Fri)
int Year, Month, Day;
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);
]; \WeekDay
int MonthTbl, Year, I, C;
[MonthTbl:= [1, 3, 5, 7, 8, 10, 12]; \months with 31 days
C:= 0;
for Year:= 1900 to 2100 do
for I:= 0 to 6 do \for all the 31-day months...
if WeekDay(Year, MonthTbl(I), 1) = 6 then \first of month is a Friday
[C:= C+1; \count this year
if C<=5 or C>201-5 then \show first 5 and last 5 years
[IntOut(0, Year); ChOut(0, ^ );
IntOut(0, MonthTbl(I)); CrLf(0);
];
];
IntOut(0, C); CrLf(0); \show number of years
\Count and show all years that don't have any 5-weekend months
C:= 0;
for Year:= 1900 to 2100 do
[for I:= 0 to 6 do \for all the 31-day months...
if WeekDay(Year, MonthTbl(I), 1) = 6 \Friday\ then
I:= 10; \bail out of 'for' loop
if I<10 then \'for' loop completed
[if (C&$F) = 0 then CrLf(0); \(format 16 years per line)
C:= C+1; \ without finding a 5-weekend
IntOut(0, Year); ChOut(0, ^ ); \ so show the year
];
];
CrLf(0); IntOut(0, C); CrLf(0); \show number of years
]
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#zkl
|
zkl
|
var [const] D=Time.Date, r=L();
foreach y,m in ([1900..2100],[1..12]){
if (D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) r.append(String(y,"-",m))
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PHP
|
PHP
|
/* Note: This code is only for PHP 4.
It won't work on PHP 5 due to the change in behavior of array_merge(). */
while (array_filter($lst, 'is_array'))
$lst = call_user_func_array('array_merge', $lst);
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#TI-83_BASIC
|
TI-83 BASIC
|
"ABCDCABDACDBDACBBCDAACBDADCBCDABDABCBCADCADBCDBACBADABDCADBCBDCADCBABACDBADCBDACCBDADBCADCAB"→Str0
"ABCD"→Str1
length(Str0)→L
[[0,0,0,0][0,0,0,0][0,0,0,0][0,0,0,0]]→[A]
For(I,1,L,4)
For(J,1,4,1)
sub(Str0,I+J-1,1)→Str2
For(K,1,4,1)
sub(Str1,K,1)→Str3
If Str2=Str3
Then
[A](J,K)+1→[A](J,K)
End
End
End
End
Matr►list([A],1,L₁)
min(L₁)→M
" "→Str4
For(I,1,4,1)
For(J,1,4,1)
If [A](I,J)=M
Then
Str4+sub(Str1,J,1)→Str4
End
End
End
sub(Str4,2,4)→Str4
Disp "MISSING"
Disp Str4
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Coconut
|
Coconut
|
def fizzbuzz(n):
case (n % 3, n % 5):
match (0, 0): return "FizzBuzz"
match (0, _): return "Fizz"
match (_, 0): return "Buzz"
else: return n |> str
range(1,101)|> map$(fizzbuzz)|> x -> '\n'.join(x)|> print
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PicoLisp
|
PicoLisp
|
(de flatten (X)
(make # Build a list
(recur (X) # recursively over 'X'
(if (atom X)
(link X) # Put atoms into the result
(mapc recurse X) ) ) ) ) # or recurse on sub-lists
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Tcl
|
Tcl
|
package require struct::list
set have { \
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC \
ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB \
}
struct::list foreachperm element {A B C D} {
set text [join $element ""]
if {$text ni $have} {
puts "Missing permutation(s): $text"
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#CoffeeScript
|
CoffeeScript
|
for i in [1..100]
if i % 15 is 0
console.log "FizzBuzz"
else if i % 3 is 0
console.log "Fizz"
else if i % 5 is 0
console.log "Buzz"
else
console.log i
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Pike
|
Pike
|
array flatten(array a) {
array r = ({ });
foreach (a, mixed n) {
if (arrayp(n)) r += flatten(n);
else r += ({ n });
}
return r;
}
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Ursala
|
Ursala
|
permutations = ~&itB^?a\~&aNC *=ahPfatPRD refer ^C/~&a ~&ar&& ~&arh2falrtPXPRD
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#VBScript
|
VBScript
|
arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_
"CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",_
"BADC", "BDAC", "CBDA", "DBCA", "DCAB")
Dim col(4)
'supposes that a complete column have 6 of each letter.
target = (6*Asc("A")) + (6*Asc("B")) + (6*Asc("C")) + (6*Asc("D"))
missing = ""
For i = 0 To UBound(arrp)
For j = 1 To 4
col(j) = col(j) + Asc(Mid(arrp(i),j,1))
Next
Next
For k = 1 To 4
n = target - col(k)
missing = missing & Chr(n)
Next
WScript.StdOut.WriteLine missing
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#ColdFusion
|
ColdFusion
|
<Cfloop from="1" to="100" index="i">
<Cfif i mod 15 eq 0>FizzBuzz
<Cfelseif i mod 5 eq 0>Fizz
<Cfelseif i mod 3 eq 0>Buzz
<Cfelse><Cfoutput>#i# </Cfoutput>
</Cfif>
</Cfloop>
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PL.2FI
|
PL/I
|
list = translate (list, ' ', '[]' ); /*Produces " 1 , 2, 3,4 , 5 , , 6 , 7, 8, " */
list = Replace(list,'',' '); /*Converts spaces to nothing. Same parameter order as Translate.*/
do while index(list,',,') > 0; /*Is there a double comma anywhere?
list = Replace(list,',',',,'); /*Yes. Convert double commas to single, nullifying empty lists*/
end; /*And search afresh, in case of multiple commas in a row.*/
list = '[' || list || ']'; /*Repackage the list.*/
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#Wren
|
Wren
|
import "./set" for Set
import "./perm" for Perm
var missingPerms = Fn.new { |input, perms|
var s1 = Set.new()
s1.addAll(perms)
var perms2 = Perm.list(input).map { |p| p.join() }
var s2 = Set.new()
s2.addAll(perms2)
return s2.except(s1).toList
}
var input = ["A", "B", "C", "D"]
var perms = [
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
]
var missing = missingPerms.call(input, perms)
if (missing.count == 1) {
System.print("The missing permutation is %(missing[0])")
} else {
System.print("There are %(missing.count) missing permutations, namely:\n")
System.print(missing)
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Comal
|
Comal
|
0010 FOR i#:=1 TO 100 DO
0020 IF i# MOD 15=0 THEN
0030 PRINT "FizzBuzz"
0040 ELIF i# MOD 5=0 THEN
0050 PRINT "Buzz"
0060 ELIF i# MOD 3=0 THEN
0070 PRINT "Fizz"
0080 ELSE
0090 PRINT i#
0100 ENDIF
0110 ENDFOR i#
0120 END
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PostScript
|
PostScript
|
/flatten {
/.f {{type /arraytype eq} {{.f} map aload pop} ift}.
[exch .f]
}.
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#XPL0
|
XPL0
|
code HexIn=26, HexOut=27;
int P, I;
[P:= 0;
for I:= 1 to 24-1 do P:= P xor HexIn(1);
HexOut(0, P);
]
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#zkl
|
zkl
|
var data=L("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB",
"DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA",
"DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
Utils.Helpers.permute(["A".."D"]).apply("concat").copy().remove(data.xplode());
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Comefrom0x10
|
Comefrom0x10
|
fizzbuzz
mod_three = 3
mod_five = 5
comefrom fizzbuzz
n
comefrom fizzbuzz if n is mod_three
comefrom fizzbuzz if n is mod_five
n = n + 1
fizz
comefrom fizzbuzz if n is mod_three
'Fizz'...
mod_three = mod_three + 3
linebreak
# would like to write "unless mod_three is mod_five"
comefrom fizz if mod_three - mod_five - 3
''
buzz
comefrom fizzbuzz if n is mod_five
'Buzz'
mod_five = mod_five + 5
comefrom fizzbuzz if n is 100
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#PowerShell
|
PowerShell
|
function flatten($a) {
if($a.Count -gt 1) {
$a | foreach{ $(flatten $_)}
} else {$a}
}
$a = @(@(1), 2, @(@(3,4), 5), @(@(@())), @(@(@(6))), 7, 8, @())
"$(flatten $a)"
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET l$="ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
20 LET length=LEN l$
30 FOR a= CODE "A" TO CODE "D"
40 FOR b= CODE "A" TO CODE "D"
50 FOR c= CODE "A" TO CODE "D"
60 FOR d= CODE "A" TO CODE "D"
70 LET x$=""
80 IF a=b OR a=c OR a=d OR b=c OR b=d OR c=d THEN GO TO 140
90 LET x$=CHR$ a+CHR$ b+CHR$ c+CHR$ d
100 FOR i=1 TO length STEP 5
110 IF x$=l$(i TO i+3) THEN GO TO 140
120 NEXT i
130 PRINT x$;" is missing"
140 NEXT d: NEXT c: NEXT b: NEXT a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.