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/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
|
#Prolog
|
Prolog
|
:- use_module(library(lambda)).
compose(F,G, FG) :-
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).
cube(X, Y) :-
Y is X ** 3.
cube_root(X, Y) :-
Y is X ** (1/3).
first_class :-
L = [sin, cos, cube],
IL = [asin, acos, cube_root],
% we create the composed functions
maplist(compose, L, IL, Lst),
% we call the functions
maplist(call, Lst, [0.5,0.5,0.5], R),
% we display the results
maplist(writeln, R).
|
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
|
#Lambdatalk
|
Lambdatalk
|
1) Let's create this function
{def A.flatten
{def A.flatten.r
{lambda {:a}
{if {A.empty? :a}
then
else {let { {:b {A.first :a}}
} {if {A.array? :b}
then {A.flatten.r :b}
else :b} }
{A.flatten.r {A.rest :a}} }}}
{lambda {:a}
{A.new {A.flatten.r :a}}}}
-> A.flatten
and test it
{def list
{A.new
{A.new 1}
2
{A.new {A.new 3 4} 5}
{A.new {A.new {A.new }}}
{A.new {A.new {A.new 6}}}
7
8
{A.new}
}}
-> [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
{A.flatten {list}}
-> [1,2,3,4,5,6,7,8]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Run_BASIC
|
Run BASIC
|
input "Number of rows: "; rows
dim colSize(rows)
for col=1 to rows
colSize(col) = len(str$(col + rows * (rows-1)/2))
next
thisNum = 1
for r = 1 to rows
for col = 1 to r
print right$( " "+str$(thisNum), colSize(col)); " ";
thisNum = thisNum + 1
next
print
next
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Rust
|
Rust
|
fn main() {
floyds_triangle(5);
floyds_triangle(14);
}
fn floyds_triangle(n: u32) {
let mut triangle: Vec<Vec<String>> = Vec::new();
let mut current = 0;
for i in 1..=n {
let mut v = Vec::new();
for _ in 0..i {
current += 1;
v.push(current);
}
let row = v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
triangle.push(row);
}
for row in &triangle {
let arranged_row: Vec<_> = row
.iter()
.enumerate()
.map(|(i, number)| {
let space_len = triangle.last().unwrap()[i].len() - number.len() + 1;
let spaces = " ".repeat(space_len);
let mut padded_number = spaces;
padded_number.push_str(&number);
padded_number
})
.collect();
println!("{}", arranged_row.join(""))
}
}
|
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)
|
#Maple
|
Maple
|
lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]:
perm := table():
for letter in "ABCD" do
perm[letter] := 0:
end do:
for item in lst do
for letter in "ABCD" do
perm[letter] += StringTools:-FirstFromLeft(letter, item):
end do:
end do:
print(StringTools:-Join(ListTools:-Flatten([indices(perm)], 4)[sort(map(x->60-x, ListTools:-Flatten([entries(perm)],4)),'output=permutation')], "")):
|
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)
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
ProvidedSet = {"ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD",
"ADCB" , "CDAB", "DABC", "BCAD" , "CADB", "CDBA" , "CBAD" , "ABDC",
"ADBC" , "BDCA", "DCBA" , "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB"};
Complement[StringJoin /@ Permutations@Characters@First@#, #] &@ProvidedSet
->{"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
|
#PHP
|
PHP
|
<?php
// Created with PHP 7.0
function printLastSundayOfAllMonth($year)
{
$months = array(
'January', 'February', 'March', 'April', 'June', 'July',
'August', 'September', 'October', 'November', 'December');
foreach ($months as $month) {
echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month . ' ' . $year)) . "\n";
}
}
printLastSundayOfAllMonth($argv[1]);
|
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
|
#Befunge
|
Befunge
|
for i = 0; i <= 100; i++
out = ""
if i % 3 == 0
out = "Fizz"
end
if i % 5 == 0
out = out + "Buzz"
end
if out == ""
out = i
end
print(out)
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
|
#Perl
|
Perl
|
#!/usr/bin/perl -w
use DateTime ;
my @happymonths ;
my @workhardyears ;
my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ;
my @years = 1900..2100 ;
foreach my $year ( @years ) {
my $countmonths = 0 ;
foreach my $month ( @longmonths ) {
my $dt = DateTime->new( year => $year ,
month => $month ,
day => 1 ) ;
if ( $dt->day_of_week == 5 ) {
$countmonths++ ;
my $yearfound = $dt->year ;
my $monthfound = $dt->month_name ;
push ( @happymonths , "$yearfound $monthfound" ) ;
}
}
if ( $countmonths == 0 ) {
push ( @workhardyears, $year ) ;
}
}
print "There are " . @happymonths . " months with 5 full weekends!\n" ;
print "The first 5 and the last 5 of them are:\n" ;
foreach my $i ( 0..4 ) {
print "$happymonths[ $i ]\n" ;
}
foreach my $i ( -5..-1 ) {
print "$happymonths[ $i ]\n" ;
}
print "No long weekends in the following " . @workhardyears . " years:\n" ;
map { print "$_\n" } @workhardyears ;
|
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
|
#Python
|
Python
|
>>> # Some built in functions and their inverses
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> # First class functions allow run-time creation of functions from functions
>>> # return function compose(f,g)(x) == f(g(x))
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> # first class functions should be able to be members of collection types
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> # Apply functions from lists as easily as integers
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 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
|
#Lasso
|
Lasso
|
local(original = json_deserialize('[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]'))
#original
'<br />'
(with item in delve(#original)
select #item) -> asstaticarray
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Scala
|
Scala
|
def floydstriangle( n:Int ) = {
val s = (1 to n)
val t = s map {i => (s.take(i-1).sum) + 1}
(s zip t) foreach { n =>
var m = n._2;
for( i <- 0 until n._1 ) {
val w = (t.last + i).toString.length + 1 // Column width from last row
print(" " + m takeRight w )
m+=1
}
print("\n")
}
}
// Test
floydstriangle(5)
floydstriangle(14)
|
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)
|
#MATLAB
|
MATLAB
|
function perm = findMissingPerms(list)
permsList = perms(list(1,:)); %Generate all permutations of the 4 letters
perm = []; %This is the functions return value if the list is not missing a permutation
%Normally the rest of this would be vectorized, but because this is
%done on a vector of strings, the vectorized functions will only access
%one character at a time. So, in order for this to work we have to use
%loops.
for i = (1:size(permsList,1))
found = false;
for j = (1:size(list,1))
if (permsList(i,:) == list(j,:))
found = true;
break
end
end
if not(found)
perm = permsList(i,:);
return
end
end %for
end %fingMissingPerms
|
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
|
#PicoLisp
|
PicoLisp
|
(de lastSundays (Y)
(for M 12
(prinl
(dat$
(find '((D) (= "Sunday" (day D)))
(mapcar '((D) (date Y M D)) `(range 31 22)) )
"-" ) ) ) )
|
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
|
#PowerShell
|
PowerShell
|
function last-dayofweek {
param(
[Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year,
[String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek
)
$date = (Get-Date -Year $year -Month 1 -Day 1)
while($date.DayOfWeek -ne $dayofweek) {$date = $date.AddDays(1)}
while($date.year -eq $year) {
if($date.Month -ne $date.AddDays(7).Month) {$date.ToString("yyyy-dd-MM")}
$date = $date.AddDays(7)
}
}
last-dayofweek 2013 "Sunday"
|
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
|
#blz
|
blz
|
for i = 0; i <= 100; i++
out = ""
if i % 3 == 0
out = "Fizz"
end
if i % 5 == 0
out = out + "Buzz"
end
if out == ""
out = i
end
print(out)
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
|
#Phix
|
Phix
|
with javascript_semantics
sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"}
integer y,m,
nmonths = 0
string months
sequence res = {},
none = {}
for y=1900 to 2100 do
months = ""
for m=1 to 12 do
if string(m31[m])
and day_of_week(y,m,1,true)="Friday" then
if length(months)!=0 then months &= ", " end if
months &= m31[m]
nmonths += 1
end if
end for
if length(months)=0 then
none = append(none,y)
else
res = append(res,sprintf("%d : %s\n",{y,months}))
end if
end for
printf(1,"Found %d months with five full weekends\n",nmonths)
res[6..-6] = {" ...\n"}
puts(1,join(res,""))
printf(1,"Found %d years with no month having 5 weekends:\n",{length(none)})
none[6..-6] = {".."}
?none
|
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
|
#R
|
R
|
cube <- function(x) x^3
croot <- function(x) x^(1/3)
compose <- function(f, g) function(x){f(g(x))}
f1 <- c(sin, cos, cube)
f2 <- c(asin, acos, croot)
for(i in 1:3) {
print(compose(f1[[i]], f2[[i]])(.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
|
#Racket
|
Racket
|
#lang racket
(define (compose f g) (λ (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 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
|
#LFE
|
LFE
|
> (: lists flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const proc: writeFloyd (in integer: rows) is func
local
var integer: number is 1;
var integer: numBeforeLastLine is 0;
var integer: line is 0;
var integer: column is 0;
begin
numBeforeLastLine := rows * pred(rows) div 2;
for line range 1 to rows do
for column range 1 to line do
if column <> 1 then
write(" ");
end if;
write(number lpad length(str(numBeforeLastLine + column)));
incr(number);
end for;
writeln;
end for;
end func;
const proc: main is func
begin
writeFloyd(5);
writeFloyd(14);
end func;
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Sidef
|
Sidef
|
func floyd(rows, n=1) {
var max = Math.range_sum(1, rows)
var widths = (max-rows .. max-1 -> map{.+n->to_s.len})
{ |r|
say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}'
} << 1..rows
}
floyd(5) # or: floyd(5, 88)
floyd(14) # or: floyd(14, 900)
|
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)
|
#Nim
|
Nim
|
import strutils
proc missingPermutation(arr: openArray[string]): string =
result = ""
if arr.len == 0: return
if arr.len == 1: return arr[0][1] & arr[0][0]
for pos in 0 ..< arr[0].len:
var s: set[char] = {}
for permutation in arr:
let c = permutation[pos]
if c in s: s.excl c
else: s.incl c
for c in s: result.add c
const given = """ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB""".splitWhiteSpace()
echo missingPermutation(given)
|
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)
|
#OCaml
|
OCaml
|
(* insert x at all positions into li and return the list of results *)
let rec insert x = function
| [] -> [[x]]
| a::m as li -> (x::li) :: (List.map (fun y -> a::y) (insert x m))
(* list of all permutations of li *)
let permutations li =
List.fold_right (fun a z -> List.concat (List.map (insert a) z)) li [[]]
(* convert a string to a char list *)
let chars_of_string s =
let cl = ref [] in
String.iter (fun c -> cl := c :: !cl) s;
(List.rev !cl)
(* convert a char list to a string *)
let string_of_chars cl =
String.concat "" (List.map (String.make 1) cl)
|
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
|
#PureBasic
|
PureBasic
|
Procedure LastSundayOfEachMonth(yyyy.i,List lfem.i())
Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1
NewList d.i()
For d=1 To 365
dv=AddDate(dv,#PB_Date_Day,1)
If DayOfWeek(dv)=0
AddElement(d()) : d()=dv
EndIf
Next
dv=0
For mv=1 To 12
ForEach d()
If dv<d() And Month(d())=mv
dv=d()
EndIf
Next
AddElement(lfem()) : lfem()=dv
Next
EndProcedure
NewList lf.i()
Define y.i
OpenConsole("Last Sunday of each month")
Print("Input Year [ 1971 < y < 2038 ]: ")
y=Val(Input())
If y>1971 And y<2038
PrintN("Last Sunday of each month...")
LastSundayOfEachMonth(y,lf())
ForEach lf()
PrintN(FormatDate("%dd.%mm.%yyyy",lf()))
Next
EndIf
Print("...End")
Input()
|
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
|
#Boo
|
Boo
|
def fizzbuzz(size):
for i in range(1, size):
if i%15 == 0:
print 'FizzBuzz'
elif i%5 == 0:
print 'Buzz'
elif i%3 == 0:
print 'Fizz'
else:
print i
fizzbuzz(101)
|
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
|
#Picat
|
Picat
|
go ?=>
println("Months with five weekends:"),
FiveWeekends = [ [Year,Month] : Year in 1900..2100, Month in [1,3,5,7,8,10,12], dow(Year,Month,1) == 5],
WLen = FiveWeekends.len,
println(take(FiveWeekends,5)),
println("..."),
println(drop(FiveWeekends,WLen-5)),
println(len=WLen),
nl,
println("Years w/o five weekends:"),
FiveWeekendYears = [Year : [Year,_] in FiveWeekends].remove_dups,
NoHitYears = [Year : Year in 1900..2100, not member(Year,FiveWeekendYears)],
NHLen = NoHitYears.len,
println(take(NoHitYears,5)),
println("..."),
println(drop(NoHitYears,NHLen-5)),
println(len=NHLen),
nl.
go => true.
% Day of week, Sakamoto's method
dow(Y, M, D) = R =>
T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
if M < 3 then
Y := Y - 1
end,
R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.
% Days in a month.
max_days_in_month(Year,Month) = Days =>
if member(Month, [1,3,5,7,8,10,12]) then
Days = 31
elseif member(Month,[4,6,9,11]) then
Days = 30
else
if leap_year(Year) then
Days = 29
else
Days = 28
end
end.
leap_year(Year) =>
(Year mod 4 == 0, Year mod 100 != 0)
;
Year mod 400 == 0.
|
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
|
#PicoLisp
|
PicoLisp
|
(setq Lst
(make
(for Y (range 1900 2100)
(for M (range 1 12)
(and
(date Y M 31)
(= "Friday" (day (date Y M 1)))
(link (list (get *Mon M) Y)) ) ) ) ) )
(prinl "There are " (length Lst) " months with five weekends:")
(mapc println (head 5 Lst))
(prinl "...")
(mapc println (tail 5 Lst))
(prinl)
(setq Lst (diff (range 1900 2100) (uniq (mapcar cadr Lst))))
(prinl "There are " (length Lst) " years with no five-weekend months:")
(println Lst)
|
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
|
#Raku
|
Raku
|
sub infix:<∘> (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } }
my \𝐴 = &sin, &cos, { $_ ** <3/1> }
my \𝐵 = &asin, &acos, { $_ ** <1/3> }
say .(.5) for 𝐴 Z∘ 𝐵
|
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
|
#REBOL
|
REBOL
|
rebol [
Title: "First Class Functions"
URL: http://rosettacode.org/wiki/First-class_functions
]
; Functions "foo" and "bar" are used to prove that composition
; actually took place by attaching their signatures to the result.
foo: func [x][reform ["foo:" x]]
bar: func [x][reform ["bar:" x]]
cube: func [x][x * x * x]
croot: func [x][power x 1 / 3]
; "compose" means something else in REBOL, so I "fashion" an alternative.
fashion: func [f1 f2][
do compose/deep [func [x][(:f1) (:f2) x]]]
A: [foo sine cosine cube]
B: [bar arcsine arccosine croot]
while [not tail? A][
fn: fashion get A/1 get B/1
source fn ; Prove that functions actually got composed.
print [fn 0.5 crlf]
A: next A B: next B ; Advance to next pair.
]
|
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
|
#Logo
|
Logo
|
to flatten :l
if not list? :l [output :l]
if empty? :l [output []]
output sentence flatten first :l flatten butfirst :l
end
; using a template iterator (map combining results into a sentence)
to flatten :l
output map.se [ifelse or not list? ? empty? ? [?] [flatten ?]] :l
end
make "a [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]
show flatten :a
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#SPL
|
SPL
|
floyd(5)
floyd(14)
floyd(n)=
k = 0
> r, 1..n
s = ""
> j, 1..r
k += 1
f = ">"+#.upper(#.log10((n-1)*n/2+j+1)+1)+">"
s += #.str(k,f)
<
#.output(s)
<
.
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Tcl
|
Tcl
|
proc floydTriangle n {
# Compute the column widths
for {set i [expr {$n*($n-1)/2+1}]} {$i <= $n*($n+1)/2} {incr i} {
lappend w [string length $i]
}
# Print the triangle
for {set i 0; set j 1} {$j <= $n} {incr j} {
for {set p -1; set k 0} {$k < $j} {incr k} {
puts -nonewline [format "%*d " [lindex $w [incr p]] [incr i]]
}
puts ""
}
}
# Demonstration
puts "Floyd 5:"
floydTriangle 5
puts "Floyd 14:"
floydTriangle 14
|
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)
|
#Octave
|
Octave
|
given = [ 'ABCD';'CABD';'ACDB';'DACB'; ...
'BCDA';'ACBD';'ADCB';'CDAB'; ...
'DABC';'BCAD';'CADB';'CDBA'; ...
'CBAD';'ABDC';'ADBC';'BDCA'; ...
'DCBA';'BACD';'BADC';'BDAC'; ...
'CBDA';'DBCA';'DCAB' ];
val = 4.^(3:-1:0)';
there = 1+(toascii(given)-toascii('A'))*val;
every = 1+perms(0:3)*val;
bits = zeros(max(every),1);
bits(every) = 1;
bits(there) = 0;
missing = dec2base(find(bits)-1,'ABCD')
|
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
|
#Python
|
Python
|
import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))
|
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
|
#QuickBASIC_4.5
|
QuickBASIC 4.5
|
' PROGRAM Last Sundays in Quick BASIC 4.5 (LASTSQB1)
' This program will calculate the last Sundays of each month in a given year.
' It works assigning the year in the command prompt
' Usage: LASTSQB1 Year
' In the IDE, be sure to assign the COMMAND$ value in the Run menu.
' Var
DIM iWY AS INTEGER
DIM A AS STRING
DIM iWM AS INTEGER
DIM iWD AS INTEGER
DIM strF AS STRING
' SUBs and FUNCTIONs
DECLARE FUNCTION LastSundayOfMonth% (WhichMonth AS INTEGER, WhichYear AS INTEGER)
DECLARE FUNCTION FirstDayOfWeekOnMonth% (WhichMonth AS INTEGER, WhichYear AS INTEGER)
' Gets the year from the command line
iWY = VAL(COMMAND$)
' Verifies if given year is in the range.
' If so, runs the program. If not, shows an error message.
IF iWY >= 1753 AND iWY <= 2078 THEN
PRINT "Last Sundays of each month on year:"; iWY
strF = "####_-0#_-##"
FOR iWM = 1 TO 12
IF iWM > 9 THEN strF = "####_-##_-##"
iWD = LastSundayOfMonth(iWM, iWY)
PRINT USING strF; iWY; iWM; iWD
NEXT iWM
ELSE
PRINT "Incorrect year."
PRINT "Usage: LASTSQB1 Year"
PRINT
PRINT "Where Year is a value between 1753 and 2078."
END IF
PRINT
PRINT "End of program"
END
FUNCTION FirstDayOfWeekOnMonth% (WhichMonth AS INTEGER, WhichYear AS INTEGER)
' Adapted from Ray Thomas' SUB GetDay
' taken from his program Calandar.BAS
' available in his site http://brisray.com
' Var
DIM iDay AS INTEGER
DIM iMonth AS INTEGER
DIM iYear AS INTEGER
DIM iCentury AS INTEGER
DIM iDoW AS INTEGER
DIM strNewYear AS STRING
' Get the first day of the month
iDay = 1
iMonth = WhichMonth
iYear = WhichYear
' For any date in Jan or Feb add 12 to the month and
' subtract 1 from the year
IF iMonth < 3 THEN
iMonth = iMonth + 12
iYear = iYear - 1
END IF
' Add 1 to the month and multiply by 2.61
' Drop the fraction (not round) afterwards
iMonth = iMonth + 1
iMonth = FIX(iMonth * 2.61)
' Add Day, Month and the last two digits of the year
strNewYear = LTRIM$(STR$(iYear))
iYear = VAL(RIGHT$(strNewYear, 2))
iDoW = iDay + iMonth + iYear
iCentury = VAL(LEFT$(strNewYear, 2))
' Add a quarter of the last two digits of the year
' (truncated not rounded)
iYear = FIX(iYear / 4)
iDoW = iDoW + iYear
' Add the following factors for the year
IF iCentury = 18 THEN iCentury = 2
IF iCentury = 19 THEN iCentury = 0
IF iCentury = 20 THEN iCentury = 6
IF iCentury = 21 THEN iCentury = 4
iDoW = iDoW + iCentury
' The day of the week is the modulus of iDoY divided by 7
iDoW = (iDoW MOD 7) + 1
' The returned value will be between 1 and 7. 1 is Sunday.
FirstDayOfWeekOnMonth = iDoW
END FUNCTION
FUNCTION LastSundayOfMonth% (WhichMonth AS INTEGER, WhichYear AS INTEGER)
' Var
DIM iLDoM AS INTEGER
DIM iFDoWoM AS INTEGER
SELECT CASE WhichMonth
CASE 1, 3, 5, 7, 8, 10, 12
iLDoM = 31
CASE 2
iLDoM = 28 + ABS((WhichYear MOD 4 = 0 AND WhichYear MOD 100 OR WhichYear MOD 400 = 0) <> 0)
CASE ELSE
iLDoM = 30
END SELECT
' Get first Sunday
' All I have to do is to sum the days if the first of the given month
' is not Sunday.
iFDoWoM = 1 + ((ABS(FirstDayOfWeekOnMonth(WhichMonth, WhichYear) - 7) + 1) MOD 7)
' Get the last Sunday
' I add as many days in multiples of 7 to get the last Sunday
' in the given amount of days in month
iFDoWoM = iFDoWoM + (7 * ((iLDoM - iFDoWoM) \ 7))
' Returns the last sunday of the given month and year
LastSundayOfMonth = iFDoWoM
END FUNCTION
|
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
|
#BQN
|
BQN
|
(∾´∾⟜"Fizz"‿"Buzz"/˜·(¬∨´)⊸∾0=3‿5|⊢)¨1+↕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
|
#Pike
|
Pike
|
int(0..1) weekends(object day)
{
return (<5,6,7>)[day->week_day()];
}
int(0..1) has5(object month)
{
return sizeof(filter(month->days(), weekends))==15;
}
object range = Calendar.Year(1900)->distance(Calendar.Year(2101));
array have5 = filter(range->months(), has5);
write("found %d months:\n%{%s\n%}...\n%{%s\n%}",
sizeof(have5), have5[..4]->format_nice(), have5[<4..]->format_nice());
array rest = range->years() - have5->year();
write("%d years without any 5 weekend month:\n %{%d,%}\n", sizeof(rest), rest->year_no());
|
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
|
#REXX
|
REXX
|
/*REXX program demonstrates first─class functions (as a list of the names of functions).*/
A = 'd2x square sin cos' /*a list of functions to demonstrate.*/
B = 'x2d sqrt Asin Acos' /*the inverse functions of above list. */
w=digits() /*W: width of numbers to be displayed.*/
/* [↓] collection of A & B functions*/
do j=1 for words(A); say; say /*step through the list; 2 blank lines*/
say center("number",w) center('function', 3*w+1) center("inverse", 4*w)
say copies("─" ,w) copies("─", 3*w+1) copies("─", 4*w)
if j<2 then call test j, 20 60 500 /*functions X2D, D2X: integers only. */
else call test j, 0 0.5 1 2 /*all other functions: floating point.*/
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Acos: procedure; parse arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x)
r2r: return arg(1) // (pi()*2) /*normalize radians ──► 1 unit circle*/
square: return arg(1) ** 2
pi: pi=3.14159265358979323846264338327950288419716939937510582097494459230; return pi
tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13
tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x
AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' || x
AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' || x
/*──────────────────────────────────────────────────────────────────────────────────────*/
Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x
if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z
do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end
return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x=r2r(x); a=abs(x); Hpi=pi*.5
numeric fuzz min(6,digits()-3); if a=pi() then return -1
if a=Hpi | a=Hpi*3 then return 0 ; if a=pi()/3 then return .5
if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits()-3)
if abs(x)=pi() then return 0; return .sinCos(x,x,1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
.sinCos: parse arg z 1 p,_,i; x=x*x
do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
invoke: parse arg fn,v; q='"'; if datatype(v,"N") then q=
_=fn || '('q || v || q")"; interpret 'func='_; return func
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
h=d+6; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1
/*──────────────────────────────────────────────────────────────────────────────────────*/
test: procedure expose A B w; parse arg fu,xList; d=digits() /*xList: numbers. */
do k=1 for words(xList); x=word(xList, k)
numeric digits d+5 /*higher precision.*/
fun=word(A, fu); funV=invoke(fun, x) ; fun@=_
inv=word(B, fu); invV=invoke(inv, funV); inv@=_
numeric digits d /*restore precision*/
if datatype(funV, 'N') then funV=funV/1 /*round to digits()*/
if datatype(invV, 'N') then invV=invV/1 /*round to digits()*/
say center(x, w) right(fun@, 2*w)'='left(left('', funV>=0)funV, w),
right(inv@, 3*w)'='left(left('', invV>=0)invV, w)
end /*k*/
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
|
#Logtalk
|
Logtalk
|
flatten(List, Flatted) :-
flatten(List, [], Flatted).
flatten(Var, Tail, [Var| Tail]) :-
var(Var),
!.
flatten([], Flatted, Flatted) :-
!.
flatten([Head| Tail], List, Flatted) :-
!,
flatten(Tail, List, Aux),
flatten(Head, Aux, Flatted).
flatten(Head, Tail, [Head| Tail]).
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#TXR
|
TXR
|
(defun flotri (n)
(let* ((last (trunc (* n (+ n 1)) 2))
(colw (mapcar [chain tostring length]
(range (- last n -1) last)))
(x 0))
(each ((r (range* 0 n)))
(each ((c (range 0 r)))
(format t " ~*a" [colw c] (inc x)))
(put-line))))
(defun usage (msg)
(put-line `error: @msg`)
(put-line `usage:\n@(ldiff *full-args* *args*) <smallish-positive-integer>`)
(exit 1))
(tree-case *args*
((num blah . etc) (usage "too many arguments"))
((num) (flotri (int-str num)))
(() (usage "need an argument")))
|
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)
|
#Oz
|
Oz
|
declare
GivenPermutations =
["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
"CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"]
%% four distinct variables between "A" and "D":
proc {Description Root}
Root = {FD.list 4 &A#&D}
{FD.distinct Root}
{FD.distribute naiv Root}
end
AllPermutations = {SearchAll Description}
in
for P in AllPermutations do
if {Not {Member P GivenPermutations}} then
{System.showInfo "Missing: "#P}
end
end
|
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
|
#Quackery
|
Quackery
|
[ over 3 < if [ 1 - ]
dup 4 / over +
over 100 / -
swap 400 / +
swap 1 -
[ table
0 3 2 5 0 3
5 1 4 6 2 4 ]
+ + 7 mod ] is dayofweek ( day month year --> weekday )
[ dup 400 mod 0 = iff
[ drop true ] done
dup 100 mod 0 = iff
[ drop false ] done
4 mod 0 = ] is leap ( year --> b )
[ swap 1 -
[ table
31 [ dup leap 28 + ]
31 30 31 30 31 31 30
31 30 31 ]
do nip ] is monthdays ( month year --> n )
[ number$
2 times
[ char - join
over 10 < if
[ char 0 join ]
swap number$ join ]
echo$ ] is echoymd ( day month year --> )
[ dip
[ 2dup monthdays
dup temp put
unrot dayofweek ]
- dup 0 < if [ 7 + ]
temp take swap - ] is lastwkday ( month year wkd --> n )
[ temp put
12 times
[ i^ 1+ over
2dup temp share lastwkday
unrot echoymd cr ]
drop temp release ] is lastwkdays ( year wkd --> )
[ 0 lastwkdays ] is lastsundays ( year --> )
2013 lastsundays
|
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
|
#R
|
R
|
last_sundays <- function(year) {
for (month in 1:12) {
if (month == 12) {
date <- as.Date(paste0(year,"-",12,"-",31))
} else {
date <- as.Date(paste0(year,"-",month+1,"-",1))-1
}
while (weekdays(date) != "Sunday") {
date <- date - 1
}
print(date)
}
}
last_sundays(2004)
|
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
|
#Bracmat
|
Bracmat
|
0:?i&whl'(1+!i:<101:?i&out$(mod$(!i.3):0&(mod$(!i.5):0&FizzBuzz|Fizz)|mod$(!i.5):0&Buzz|!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
|
#PL.2FI
|
PL/I
|
weekends: procedure options (main); /* 28/11/2011 */
declare tally fixed initial (0);
declare (d, dend, dn) fixed (10);
declare (date_start, date_end) picture '99999999';
declare Leap fixed (1);
date_start = '01011900';
do date_start = date_start to '01012100';
d = days(date_start, 'DDMMYYYY');
date_end = date_start + 30110000;
dend = days(date_end, 'DDMMYYYY');
Leap = dend-d-364;
do dn = d, d+59+Leap, d+120+Leap, d+181+Leap, d+212+Leap,
d+273+Leap, d+334+Leap;
if weekday(dn) = 6 then
do;
put skip list (daystodate(dn, 'MmmYYYY') || ' has 5 weekends' );
tally = tally + 1;
end;
end;
end;
put skip list ('Total number of months having 3-day weekends =', tally);
end weekends;
|
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
|
#PowerShell
|
PowerShell
|
$fiveWeekends = @()
$yearsWithout = @()
foreach ($y in 1900..2100) {
$hasFiveWeekendMonth = $FALSE
foreach ($m in @("01","03","05","07","08",10,12)) {
if ((Get-Date "$y-$m-1").DayOfWeek -eq "Friday") {
$fiveWeekends += "$y-$m"
$hasFiveWeekendMonth = $TRUE
}
}
if ($hasFiveWeekendMonth -eq $FALSE) {
$yearsWithout += $y
}
}
Write-Output "Between the years 1900 and 2100, inclusive, there are $($fiveWeekends.count) months with five full weekends:"
Write-Output "$($fiveWeekends[0..4] -join ","),...,$($fiveWeekends[-5..-1] -join ",")"
Write-Output ""
Write-Output "Extra Credit: these $($yearsWithout.count) years have no such month:"
Write-Output ($yearsWithout -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
|
#Ruby
|
Ruby
|
cube = proc{|x| x ** 3}
croot = proc{|x| x ** (1.quo 3)}
compose = proc {|f,g| proc {|x| f[g[x]]}}
funclist = [Math.method(:sin), Math.method(:cos), cube]
invlist = [Math.method(:asin), Math.method(:acos), croot]
puts funclist.zip(invlist).map {|f, invf| compose[invf, f][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
|
#Rust
|
Rust
|
#![feature(conservative_impl_trait)]
fn main() {
let cube = |x: f64| x.powi(3);
let cube_root = |x: f64| x.powf(1.0 / 3.0);
let flist : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ];
let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];
let result = flist.iter()
.zip(&invlist)
.map(|(f,i)| compose(f,i)(0.5))
.collect::<Vec<_>>();
println!("{:?}", result);
}
fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V
where F: 'a + Fn(T) -> U,
G: 'a + Fn(U) -> V,
{
move |x| g(f(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
|
#Lua
|
Lua
|
function flatten(list)
if type(list) ~= "table" then return {list} end
local flat_list = {}
for _, elem in ipairs(list) do
for _, val in ipairs(flatten(elem)) do
flat_list[#flat_list + 1] = val
end
end
return flat_list
end
test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
print(table.concat(flatten(test_list), ","))
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#VBA
|
VBA
|
Option Explicit
Dim o As String
Sub floyd(L As Integer)
Dim r, c, m, n As Integer
n = L * (L - 1) / 2
m = 1
For r = 1 To L
o = o & vbCrLf
For c = 1 To r
o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " "
m = m + 1
Next
Next
End Sub
Sub triangle()
o = "5 lines"
Call floyd(5)
o = o & vbCrLf & "14 lines"
Call floyd(14)
With Selection
.Font.Name = "Courier New"
.TypeText Text:=o
End With
End Sub
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#VBScript
|
VBScript
|
' Read the number of rows to use..
intRows = WScript.StdIn.ReadLine
' Get the first number of the final row so we can calculate widths...
intLastRowStart = (intRows ^ 2 - intRows) \ 2 + 1
For i = 1 To intRows
intLastRow = intLastRowStart
For j = 1 To i
k = k + 1
WScript.StdOut.Write Space(Len(intLastRow) - Len(k)) & k & " "
intLastRow = intLastRow + 1
Next
WScript.StdOut.WriteLine ""
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)
|
#PARI.2FGP
|
PARI/GP
|
v=["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"];
v=apply(u->permtonum(apply(n->n-64,Vec(Vecsmall(u)))),v);
t=numtoperm(4, binomial(4!,2)-sum(i=1,#v,v[i]));
Strchr(apply(n->n+64,t))
|
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
|
#Racket
|
Racket
|
#lang racket
(require srfi/19 math)
(define (days-in-month m y)
(define lengths #(0 31 #f 31 30 31 30 31 31 30 31 30 31))
(define d (vector-ref lengths m))
(or d (days-in-feb y)))
(define (leap-year? y)
(and (divides? 4 y)
(or (not (divides? 100 y))
(divides? 400 y))))
(define (days-in-feb y)
(if (leap-year? y) 29 28))
(define (last-day-in-month m y)
(make-date 0 0 0 0 (days-in-month m y) m y 0))
(define (week-day date)
(define days #(sun mon tue wed thu fri sat))
(vector-ref days (date-week-day date)))
(define (last-sundays y)
(for/list ([m (in-range 1 13)])
(prev-sunday (last-day-in-month m y))))
(define 24hours (make-time time-duration 0 (* 24 60 60)))
(define (prev-day d)
(time-utc->date
(subtract-duration
(date->time-utc d) 24hours)))
(define (prev-sunday d)
(if (eq? (week-day d) 'sun)
d
(prev-sunday (prev-day d))))
(for ([d (last-sundays 2013)])
(displayln (~a (date->string d "~a ~d ~b ~Y"))))
|
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
|
#Raku
|
Raku
|
sub MAIN ($year = Date.today.year) {
for 1..12 -> $month {
my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month);
say $month-end - $month-end.day-of-week % 7;
}
}
|
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
|
#Brainf.2A.2A.2A
|
Brainf***
|
1.to 100 { n |
true? n % 15 == 0
{ p "FizzBuzz" }
{ true? n % 3 == 0
{ p "Fizz" }
{ true? n % 5 == 0
{ p "Buzz" }
{ p n }
}
}
}
|
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
|
#Prolog
|
Prolog
|
main() :-
weekends(1900, 2100, FiveWeekendList, RemainderWeekendList),
length(FiveWeekendList, FiveLen),
maplist(write, ["Total five weekend months:", FiveLen, '\n']),
slice(FiveWeekendList, 5, FirstFiveList),
maplist(write, ["First five {year,month} pairs:", FirstFiveList, '\n']),
slice(FiveWeekendList, -5, LastFiveList),
maplist(write, ["Last five {year,month} pairs:", LastFiveList, '\n']),
maplist(take_year, FiveWeekendList, FiveYearList),
list_to_set(FiveYearList, FiveYearSet),
maplist(take_year, RemainderWeekendList, RemainderYearList),
list_to_set(RemainderYearList, RemainderYearSet),
subtract(RemainderYearSet, FiveYearSet, NonFiveWeekendSet),
length(NonFiveWeekendSet, NonFiveWeekendLen),
maplist(write, ["Total years with no five weekend months:", NonFiveWeekendLen, '\n']),
writeln(NonFiveWeekendSet).
weekends(StartYear, EndYear, FiveWeekendList, RemainderWeekendList) :-
numlist(StartYear, EndYear, YearList),
numlist(1, 12, MonthList),
pair(YearList, MonthList, YearMonthList),
partition(has_five_weekends, YearMonthList, FiveWeekendList, RemainderWeekendList).
has_five_weekends({Year, Month}) :-
long_month(Month),
starts_on_a_friday(Year, Month).
starts_on_a_friday(Year, Month) :-
Date = date(Year, Month, 1),
day_of_the_week(Date, DayOfTheWeek),
DayOfTheWeek == 5.
take_year({Year, _}, Year).
long_month(1).
long_month(3).
long_month(5).
long_month(7).
long_month(8).
long_month(10).
long_month(12).
% Helpers
% https://stackoverflow.com/a/7739806
pair(L1, L2, Pairs):-findall({A,B}, (member(A, L1), member(B, L2)), Pairs).
slice(_, 0, []).
slice(List, N, NList):-
N < 0,
N1 is abs(N),
last_n_elements(List, N1, NList).
slice(List, N, NList):-
N > 0,
first_n_elements(List, N, NList).
first_n_elements(List, N, FirstN):-
length(FirstN, N),
append(FirstN, _, List).
last_n_elements(List, N, LastN) :-
length(LastN, N),
append(_, LastN, List).
|
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
|
#Scala
|
Scala
|
import math._
// functions as values
val cube = (x: Double) => x * x * x
val cuberoot = (x: Double) => pow(x, 1 / 3d)
// higher order function, as a method
def compose[A,B,C](f: B => C, g: A => B) = (x: A) => f(g(x))
// partially applied functions in Lists
val fun = List(sin _, cos _, cube)
val inv = List(asin _, acos _, cuberoot)
// composing functions from the above Lists
val comp = (fun, inv).zipped map (_ compose _)
// output results of applying the functions
comp foreach {f => print(f(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
|
#Maple
|
Maple
|
L := [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]:
with(ListTools):
Flatten(L);
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Text
Module Module1
Function MakeTriangle(rows As Integer) As String
Dim maxValue As Integer = (rows * (rows + 1)) / 2
Dim digit = 0
Dim output As New StringBuilder
For row = 1 To rows
For column = 0 To row - 1
Dim colMaxDigit = (maxValue - rows) + column + 1
If column > 0 Then
output.Append(" ")
End If
digit = digit + 1
output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length))
Next
output.AppendLine()
Next
Return output.ToString()
End Function
Sub Main()
Dim args = Environment.GetCommandLineArgs()
Dim count As Integer
If args.Length > 1 AndAlso Integer.TryParse(args(1), count) AndAlso count > 0 Then
Console.WriteLine(MakeTriangle(count))
Else
Console.WriteLine(MakeTriangle(5))
Console.WriteLine()
Console.WriteLine(MakeTriangle(14))
End If
End Sub
End Module
|
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)
|
#Pascal
|
Pascal
|
program MissPerm;
{$MODE DELPHI} //for result
const
maxcol = 4;
type
tmissPerm = 1..23;
tcol = 1..maxcol;
tResString = String[maxcol];
const
Given_Permutations : array [tmissPerm] of tResString =
('ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD',
'ADCB', 'CDAB', 'DABC', 'BCAD', 'CADB', 'CDBA',
'CBAD', 'ABDC', 'ADBC', 'BDCA', 'DCBA', 'BACD',
'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB');
chOfs = Ord('A')-1;
var
SumElemCol: array[tcol,tcol] of NativeInt;
function fib(n: NativeUint): NativeUint;
var
i : NativeUint;
Begin
result := 1;
For i := 2 to n do
result:= result*i;
end;
function CountOccurences: tresString;
//count the number of every letter in every column
//should be (colmax-1)! => 6
//the missing should count (colmax-1)! -1 => 5
var
fibN_1 : NativeUint;
row, col: NativeInt;
Begin
For row := low(tmissPerm) to High(tmissPerm) do
For col := low(tcol) to High(tcol) do
inc(SumElemCol[col,ORD(Given_Permutations[row,col])-chOfs]);
//search the missing
fibN_1 := fib(maxcol-1)-1;
setlength(result,maxcol);
For col := low(tcol) to High(tcol) do
For row := low(tcol) to High(tcol) do
IF SumElemCol[col,row]=fibN_1 then
result[col]:= ansichar(row+chOfs);
end;
function CheckXOR: tresString;
var
row,col: NativeUint;
Begin
setlength(result,maxcol);
fillchar(result[1],maxcol,#0);
For row := low(tmissPerm) to High(tmissPerm) do
For col := low(tcol) to High(tcol) do
result[col] := ansichar(ord(result[col]) XOR ord(Given_Permutations[row,col]));
end;
Begin
writeln(CountOccurences,' is missing');
writeln(CheckXOR,' is missing');
end.
|
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
|
#REBOL
|
REBOL
|
#!/usr/bin/env rebol
last-sundays-of-year: function [
"Return series of last sunday (date!) for each month of the year"
year [integer!] "which year?"
][
d: to-date reduce [1 1 year] ; start with first day of year
collect [
repeat month 12 [
d/month: month + 1 ; move to start of next month
keep d - d/weekday ; calculate last sunday & keep
]
]
]
foreach sunday last-sundays-of-year to-integer system/script/args [print sunday]
|
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
|
#REXX
|
REXX
|
/*REXX program displays dates of last Sundays of each month for any year*/
parse arg yyyy
do j=1 for 12
_ = lastDOW('Sunday', j, yyyy)
say right(_,4)'-'right(j,2,0)"-"left(word(_,2),2)
end /*j*/
exit /*stick a fork in it, we're done.*/
/*┌────────────────────────────────────────────────────────────────────┐
│ lastDOW: procedure to return the date of the last day-of-week of │
│ any particular month of any particular year. │
│ │
│ The day-of-week must be specified (it can be in any case, │
│ (lower-/mixed-/upper-case) as an English name of the spelled day │
│ of the week, with a minimum length that causes no ambiguity. │
│ I.E.: W for Wednesday, Sa for Saturday, Su for Sunday ... │
│ │
│ The month can be specified as an integer 1 ──► 12 │
│ 1=January 2=February 3=March ... 12=December │
│ or the English name of the month, with a minimum length that │
│ causes no ambiguity. I.E.: Jun for June, D for December. │
│ If omitted [or an asterisk(*)], the current month is used. │
│ │
│ The year is specified as an integer or just the last two digits │
│ (two digit years are assumed to be in the current century, and │
│ there is no windowing for a two-digit year). │
│ If omitted [or an asterisk(*)], the current year is used. │
│ Years < 100 must be specified with (at least 2) leading zeroes.│
│ │
│ Method used: find the "day number" of the 1st of the next month, │
│ then subtract one (this gives the "day number" of the last day of │
│ the month, bypassing the leapday mess). The last day-of-week is │
│ then obtained straightforwardly, or via subtraction. │
└────────────────────────────────────────────────────────────────────┘*/
lastdow: procedure; arg dow .,mm .,yy . /*DOW = day of week*/
parse arg a.1,a.2,a.3 /*orig args, errmsg*/
if mm=='' | mm=='*' then mm=left(date('U'),2) /*use default month*/
if yy=='' | yy=='*' then yy=left(date('S'),4) /*use default year */
if length(yy)==2 then yy=left(date('S'),2)yy /*append century. */
/*Note mandatory leading blank in strings below.*/
$=" Monday TUesday Wednesday THursday Friday SAturday SUnday"
!=" JAnuary February MARch APril MAY JUNe JULy AUgust September",
" October November December"
upper $ ! /*uppercase strings*/
if dow=='' then call .er "wasn't specified",1
if arg()>3 then call .er 'arguments specified',4
do j=1 for 3 /*any plural args ?*/
if words(arg(j))>1 then call .er 'is illegal:',j
end
dw=pos(' 'dow,$) /*find day-of-week*/
if dw==0 then call .er 'is invalid:',1
if dw\==lastpos(' 'dow,$) then call .er 'is ambigious:',1
if datatype(mm,'month') then /*if MM is alpha...*/
do
m=pos(' 'mm,!) /*maybe its good...*/
if m==0 then call .er 'is invalid:',1
if m\==lastpos(' 'mm,!) then call .er 'is ambigious:',2
mm=wordpos(word(substr(!,m),1),!)-1 /*now, use true Mon*/
end
if \datatype(mm,'W') then call .er "isn't an integer:",2
if \datatype(yy,'W') then call .er "isn't an integer:",3
if mm<1 | mm>12 then call .er "isn't in range 1──►12:",2
if yy=0 then call .er "can't be 0 (zero):",3
if yy<0 then call .er "can't be negative:",3
if yy>9999 then call .er "can't be > 9999:",3
tdow=wordpos(word(substr($,dw),1),$)-1 /*target DOW, 0──►6*/
/*day# of last dom.*/
_=date('B',right(yy+(mm=12),4)right(mm//12+1,2,0)"01",'S')-1
?=_//7 /*calc. DOW, 0──►6*/
if ?\==tdow then _=_-?-7+tdow+7*(?>tdow) /*not DOW? Adjust.*/
return date('weekday',_,"B") date(,_,'B') /*return the answer*/
.er: arg ,_;say; say '***error!*** (in LASTDOW)';say /*tell error, and */
say word('day-of-week month year excess',arg(2)) arg(1) a._
say; exit 13 /*... then exit. */
|
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
|
#Brat
|
Brat
|
1.to 100 { n |
true? n % 15 == 0
{ p "FizzBuzz" }
{ true? n % 3 == 0
{ p "Fizz" }
{ true? n % 5 == 0
{ p "Buzz" }
{ p n }
}
}
}
|
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
|
#PureBasic
|
PureBasic
|
Procedure DateG(year.w, month.b, day)
;Returns the number of days before or after the earliest reference date
;in PureBasic's Date Library (1 Jan 1970) based on an assumed Gregorian calendar calculation
Protected days
days = (year) * 365 + (month - 1) * 31 + day - 1 - 719527 ;DAYS_UNTIL_1970_01_01 = 719527
If month >= 3
days - Int(0.4 * month + 2.3)
Else
year - 1
EndIf
days + Int(year/4) - Int(year/100) + Int(year/400)
ProcedureReturn days
EndProcedure
Procedure startsOnFriday(year, month)
;0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
Protected referenceDay = DayOfWeek(Date(1970, 1, 1, 0, 0, 0)) ;link to the first day in the PureBasic's date library
Protected resultDay = (((DateG(year, month, 1) + referenceDay) % 7) + 7) % 7
If resultDay = 5
ProcedureReturn #True
EndIf
EndProcedure
Procedure has31Days(month)
Select month
Case 1, 3, 5, 7 To 8, 10, 12
ProcedureReturn #True
EndSelect
EndProcedure
Procedure checkMonths(year)
Protected month, count
For month = 1 To 12
If startsOnFriday(year, month) And has31Days(month)
count + 1
PrintN(Str(year) + " " + Str(month))
EndIf
Next
ProcedureReturn count
EndProcedure
Procedure fiveWeekends()
Protected startYear = 1900, endYear = 2100, year, monthTotal, total
NewList yearsWithoutFiveWeekends()
For year = startYear To endYear
monthTotal = checkMonths(year)
total + monthTotal
;extra credit
If monthTotal = 0
AddElement(yearsWithoutFiveWeekends())
yearsWithoutFiveWeekends() = year
EndIf
Next
PrintN("Total number of months: " + Str(total) + #CRLF$)
PrintN("Years with no five-weekend months: " + Str(ListSize(yearsWithoutFiveWeekends())) )
EndProcedure
If OpenConsole()
fiveWeekends()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
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
|
#Scheme
|
Scheme
|
(define (compose f g) (lambda (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
(define function (list sin cos cube))
(define inverse (list asin acos cube-root))
(define x 0.5)
(define (go f g)
(if (not (or (null? f)
(null? g)))
(begin (display ((compose (car f) (car g)) x))
(newline)
(go (cdr f) (cdr g)))))
(go function inverse)
|
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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Flatten[{{1}, 2, {{3, 4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var floyd = Fn.new { |n|
var k = 1
for (i in 1..n) {
for (j in 1..i) {
Fmt.write("$*d ", (j < 9) ? 2 : 3, k)
k = k + 1
}
System.print()
}
}
System.print("Floyd(5):")
floyd.call(5)
System.print("\nFloyd(14):")
floyd.call(14)
|
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)
|
#Perl
|
Perl
|
sub check_perm {
my %hash; @hash{@_} = ();
for my $s (@_) { exists $hash{$_} or return $_
for map substr($s,1) . substr($s,0,1), (1..length $s); }
}
# Check and display
@perms = qw(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB);
print check_perm(@perms), "\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
|
#Ring
|
Ring
|
see "What year to calculate (yyyy) : "
give year
see "Last Sundays in " + year + " are on :" + nl
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]
if year < 2100 leap = year - 1900 else leap = year - 1904 ok
m = ((year-1900)%7) + floor(leap/4) % 7
for n = 1 to 12
month[n] = (mo[n] + m) % 7
next
for n = 1 to 12
for i = (mon[n] - 6) to mon[n]
x = (month[n] + i) % 7
if n < 10 strn = "0" + string(n) else strn = string(n) ok
if x = 4 see year + "-" + strn + "-" + string(i) + nl ok
next
next
|
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
|
#Ruby
|
Ruby
|
require 'date'
def last_sundays_of_year(year = Date.today.year)
(1..12).map do |month|
d = Date.new(year, month, -1) # -1 means "last".
d - d.wday
end
end
puts last_sundays_of_year(2013)
|
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
|
#BrightScript_.28for_Roku.29
|
BrightScript (for Roku)
|
FOR i = 1 TO 100
fz = i MOD 3 = 0
bz = i MOD 5 = 0
IF fz OR bz
IF fz AND NOT bz: str = "Fizz"
ELSEIF bz AND NOT fz: str = "Buzz"
ELSE str = "FizzBuzz"
END IF
ELSE
str = i.ToStr()
END IF
? str
END FOR
|
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
|
#Python
|
Python
|
from datetime import timedelta, date
DAY = timedelta(days=1)
START, STOP = date(1900, 1, 1), date(2101, 1, 1)
WEEKEND = {6, 5, 4} # Sunday is day 6
FMT = '%Y %m(%B)'
def fiveweekendspermonth(start=START, stop=STOP):
'Compute months with five weekends between dates'
when = start
lastmonth = weekenddays = 0
fiveweekends = []
while when < stop:
year, mon, _mday, _h, _m, _s, wday, _yday, _isdst = when.timetuple()
if mon != lastmonth:
if weekenddays >= 15:
fiveweekends.append(when - DAY)
weekenddays = 0
lastmonth = mon
if wday in WEEKEND:
weekenddays += 1
when += DAY
return fiveweekends
dates = fiveweekendspermonth()
indent = ' '
print('There are %s months of which the first and last five are:' % len(dates))
print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[:5]))
print(indent +'...')
print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[-5:]))
print('\nThere are %i years in the range that do not have months with five weekends'
% len(set(range(START.year, STOP.year)) - {d.year for d in dates}))
|
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
|
#Sidef
|
Sidef
|
func compose(f,g) {
func (*args) {
f(g(args...))
}
}
var cube = func(a) { a.pow(3) }
var croot = func(a) { a.root(3) }
var flist1 = [Num.method(:sin), Num.method(:cos), cube]
var flist2 = [Num.method(:asin), Num.method(:acos), croot]
for a,b (flist1 ~Z flist2) {
say compose(a, b)(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
|
#Slate
|
Slate
|
m@(Method traits) ** n@(Method traits)
"Answers a new Method whose effect is that of calling the first method
on the results of the second method applied to whatever arguments are passed.
This composition is associative, i.e. (a ** b) ** c = a ** (b ** c).
When the second method, n, does not take a *rest option or the first takes
more than one input, then the output is chunked into groups for its
consumption. E.g.:
#; `er ** #; `er applyTo: {'a'. 'b'. 'c'. 'd'} => 'abcd'
#; `er ** #name `er applyTo: {#a. #/}. => 'a/'"
[
n acceptsAdditionalArguments \/ [m arity = 1]
ifTrue:
[[| *args | m applyTo: {n applyTo: args}]]
ifFalse:
[[| *args |
m applyTo:
([| :stream |
args do: [| *each | stream nextPut: (n applyTo: each)]
inGroupsOf: n arity] writingAs: {})]]
].
#**`er asMethod: #compose: on: {Method traits. Method traits}.
|
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
|
#Maxima
|
Maxima
|
flatten([[[1, 2, 3], 4, [5, [6, 7]], 8], [[9, 10], 11], 12]);
/* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */
|
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
|
#Mercury
|
Mercury
|
:- module flatten_a_list.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list.
:- type tree(T)
---> leaf(T)
; node(list(tree(T))).
:- func flatten(tree(T)) = list(T).
flatten(leaf(X)) = [X].
flatten(node(Xs)) = condense(map(flatten, Xs)).
main(!IO) :-
List = node([
node([leaf(1)]),
leaf(2),
node([node([leaf(3), leaf(4)]), leaf(5)]),
node([node([node([])])]),
node([node([node([leaf(6)])])]),
leaf(7),
leaf(8),
node([])
]),
io.print_line(flatten(List), !IO).
:- end_module flatten_a_list.
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \include 'code' declarations
func IntLen(N); \Return number of digits in a positive integer
int N;
int I;
for I:= 1 to 20 do
[N:= N/10; if N=0 then return I];
proc Floyd(N); \Display Floyd's triangle
int N;
int M, Row, Col;
real F;
[M:= (N-1+1)*(N-1)/2; \last Floyd number on second to last row
F:= 1.0; \Floyd number counter
for Row:= 1 to N do
[for Col:= 1 to Row do
[Format(IntLen(M+Col)+1, 0); RlOut(0, F); F:= F+1.0];
CrLf(0);
];
]; \Floyd
[Floyd(5);
Floyd(14);
]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#zkl
|
zkl
|
fcn lcNum(row){(row*(row+1)/2+1)} // lazy caterer's sequence
fcn floydsTriangle(rows){
fmt:=[lcNum(rows-1)..lcNum(rows)-1].pump(String,fcn(n){
String("%",n.toString().len(),"d ")}); // eg "%2d %2d %3d %3d"
foreach row in (rows){
ns:=[lcNum(row)..lcNum(row+1)-1].walk(); // eg L(4.5,6)
fmt[0,ns.len()*4].fmt(ns.xplode()).println(); // eg "%2d %2d %2d ".fmt(4,5,6)
}
}
floydsTriangle(5); println();
floydsTriangle(14);
|
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)
|
#Phix
|
Phix
|
with javascript_semantics
constant perms = {"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"}
-- 1: sum of letters
sequence r = repeat(0,4)
for i=1 to length(perms) do
r = sq_add(r,perms[i])
end for
r = sq_sub(max(r)+'A',r)
printf(1,"%s\n",{r})
-- based on the notion that missing = sum(full)-sum(partial) would be true,
-- and that sum(full) would be like {M,M,M,M} rather than a mix of numbers.
-- the final step is equivalent to eg {1528,1530,1531,1529}
-- max-r[i] -> { 3, 1, 0, 2}
-- to chars -> { D, B, A, C}
-- (but obviously both done in one line)
-- 2: the xor trick
r = repeat(0,4)
for i=1 to length(perms) do
r = sq_xor_bits(r,perms[i])
end for
printf(1,"%s\n",{r})
-- (relies on the missing chars being present an odd number of times, non-missing chars an even number of times)
-- 3: find least frequent letters
r = " "
for i=1 to length(r) do
sequence count = repeat(0,4)
for j=1 to length(perms) do
integer cdx = perms[j][i]-'A'+1
count[cdx] += 1
end for
r[i] = smallest(count,1)+'A'-1
end for
printf(1,"%s\n",{r})
-- (relies on the assumption that a full set would have each letter occurring the same number of times in each position)
-- (smallest(count,1) returns the index position of the smallest, rather than it's value)
-- 4: test all permutations
for i=1 to factorial(4) do
r = permute(i,"ABCD")
if not find(r,perms) then exit end if
end for
printf(1,"%s\n",{r})
-- (relies on brute force(!) - but this is the only method that could be made to cope with >1 omission)
|
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
|
#Run_BASIC
|
Run BASIC
|
input "What year to calculate (yyyy) : ";year
print "Last Sundays in ";year;" are:"
dim month(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"
if year < 2100 then leap = year - 1900 else leap = year - 1904
m = ((year-1900) mod 7) + int(leap/4) mod 7
for n = 1 to 12
month(n) = (val(word$(mo$,n)) + m) mod 7
month(n) = (val(word$(mo$,n)) + m) mod 7
next
for n = 1 to 12
for i = (val(word$(mon$,n)) - 6) to val(word$(mon$,n))
x = (month(n) + i) mod 7
if x = 4 then print year ; "-";right$("0"+str$(n),2);"-" ; i
next
next
|
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
|
#Rust
|
Rust
|
use std::env::args;
use time::{Date, Duration};
fn main() {
let year = args().nth(1).unwrap().parse::<i32>().unwrap();
(1..=12)
.map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1))
.filter_map(|date| date.ok())
.for_each(|date| {
let days_back =
Duration::days(((date.weekday().number_from_sunday() as i64 + 5) % 7) + 1);
println!("{}", date - days_back);
});
}
|
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
|
#C
|
C
|
int i = 0 ; char B[88] ;
while ( i++ < 100 )
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B );
|
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
|
#Quackery
|
Quackery
|
[ over 3 < if [ 1 - ]
dup 4 / over +
over 100 / -
swap 400 / +
swap 1 -
[ table
0 3 2 5 0 3
5 1 4 6 2 4 ]
+ + 7 mod ] is dayofweek ( day month year --> weekday )
[ 1 -
[ table
$ "January" $ "February"
$ "March" $ "April"
$ "May" $ "June"
$ "July" $ "August"
$ "September" $ "October"
$ "November" $ "December" ]
do ] is monthname ( monthnumber --> $ )
[] [] temp put
201 times
[ true temp put
i^ 1900 +
' [ 1 3 5 7 8 10 12 ]
witheach
[ 2dup swap
1 unrot dayofweek
5 = iff
[ false temp replace
over join nested
swap dip join ]
else drop ]
temp take iff
[ temp take
swap join
temp put ]
else drop ]
temp take swap
say "There are "
dup size echo
say " months with five weekends."
cr cr
5 split swap
say "Five weekends: "
witheach
[ do swap
monthname echo$
sp echo
i if say ", " ]
cr say " ..."
cr space 15 of echo$
-5 split nip
witheach
[ do swap
monthname echo$
sp echo
i if say ", " ]
cr cr
say "Years without five weekends: "
witheach
[ echo
i if say ", "
i^ 8 mod 7 = if
[ cr space 29 of echo$ ] ]
|
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
|
#R
|
R
|
ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12),
function(month) paste(1900:2100, month, 1, sep = "-")))
ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b %Y")
message("There are ", length(ms), " months with five weekends.")
message("The first five: ", paste(ms[1:5], collapse = ", "))
message("The last five: ", paste(tail(ms, 5), collapse = ", "))
|
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
|
#Smalltalk
|
Smalltalk
|
|forward reverse composer compounds|
"commodities"
Number extend [
cube [ ^self raisedTo: 3 ]
].
Number extend [
cubeRoot [ ^self raisedTo: (1 / 3) ]
].
forward := #( #cos #sin #cube ).
reverse := #( #arcCos #arcSin #cubeRoot ).
composer := [ :f :g | [ :x | f value: (g value: x) ] ].
"let us create composed funcs"
compounds := OrderedCollection new.
1 to: 3 do: [ :i |
compounds add: ([ :j | composer value: [ :x | x perform: (forward at: j) ]
value: [ :x | x perform: (reverse at: j) ] ] value: i)
].
compounds do: [ :r | (r value: 0.5) displayNl ].
|
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
|
#min
|
min
|
(
=a
(a 'quotation? any?)
(a => #a) while a
) :deep-flatten
((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()) deep-flatten puts!
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET n=10: LET j=1: LET col=1
20 FOR r=1 TO n
30 FOR j=j TO j+r-1
40 PRINT TAB (col);j;
50 LET col=col+3
60 NEXT j
70 PRINT
80 LET col=1
90 NEXT 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)
|
#PHP
|
PHP
|
<?php
$finalres = Array();
function permut($arr,$result=array()){
global $finalres;
if(empty($arr)){
$finalres[] = implode("",$result);
}else{
foreach($arr as $key => $val){
$newArr = $arr;
$newres = $result;
$newres[] = $val;
unset($newArr[$key]);
permut($newArr,$newres);
}
}
}
$givenPerms = Array("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
$given = Array("A","B","C","D");
permut($given);
print_r(array_diff($finalres,$givenPerms)); // Array ( [20] => 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
|
#S-BASIC
|
S-BASIC
|
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
comment
return day of week (Sun = 0, Mon = 1, etc.) for a
given Gregorian calendar date using Zeller's congruence
end
function dayofweek (mo, da, yr = integer) = integer
var y, c, z = integer
if mo < 3 then
begin
mo = mo + 10
yr = yr - 1
end
else mo = mo - 2
y = mod(yr,100)
c = int(yr / 100)
z = int((26 * mo - 2) / 10)
z = z + da + y + int(y/4) + int(c/4) - 2 * c + 777
z = mod(z,7)
end = z
rem - return true if y is a leap year
function isleap(y = integer) = integer
end = mod(y,4)=0 and mod(y,100)<>0 or mod(y,400)=0
rem - return number of days in specified month
function monthdays(m, y = integer) = integer
var n = integer
if m = 2 then
if isleap(y) then
n = 29
else
n = 28
else if (m = 4) or (m = 6) or (m = 9) or (m = 11) then
n = 30
else
n = 31
end = n
comment
return the day of the month corresponding to the last
occurrence of weekday k (Sun=0, Mon=1, etc.) in the given
month and year
end
function lastkday(k, m, y = integer) = integer
var d, w = integer
rem - determine weekday for last day of the month
d = monthdays(m, y)
w = dayofweek(m, d, y)
rem - back up as needed to desired weekday
if w >= k then
d = d - (w - k)
else
d = d - (7 - (k - w))
end = d
rem - return abbreviated month name
function shortmonth (m = integer) = string
end = mid("JanFebMarAprMayJunJulAugSepOctNovDec", m*3-2, 3)
rem - main program starts here
$constant SUNDAY = 0
var m, y = integer
input "Display last Sundays in what year"; y
for m = 1 to 12
print shortmonth(m);" ";lastkday(SUNDAY, m, y)
next m
end
|
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
|
#Scala
|
Scala
|
object FindTheLastSundayOfEachMonth extends App {
import java.util.Calendar._
val cal = getInstance
def lastSundaysOf(year: Int) =
(JANUARY to DECEMBER).map{month =>
cal.set(year, month + 1, 1) // first day of next month
(1 to 7).find{_ => cal.add(DAY_OF_MONTH, -1); cal.get(DAY_OF_WEEK) == SUNDAY}
cal.getTime
}
val year = args.headOption.map(_.toInt).getOrElse(cal.get(YEAR))
val fmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
println(lastSundaysOf(year).map(fmt.format) mkString "\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
|
#C.23
|
C#
|
class Program
{
public void FizzBuzzGo()
{
Boolean Fizz = false;
Boolean Buzz = false;
for (int count = 1; count <= 100; count ++)
{
Fizz = count % 3 == 0;
Buzz = count % 5 == 0;
if (Fizz && Buzz)
{
Console.WriteLine("Fizz Buzz");
listBox1.Items.Add("Fizz Buzz");
}
else if (Fizz)
{
Console.WriteLine("Fizz");
listBox1.Items.Add("Fizz");
}
else if (Buzz)
{
Console.WriteLine("Buzz");
listBox1.Items.Add("Buzz");
}
else
{
Console.WriteLine(count);
listBox1.Items.Add(count);
}
}
}
}
|
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
|
#Racket
|
Racket
|
#lang racket
(require srfi/19)
(define long-months '(1 3 5 7 8 10 12))
(define days #(sun mon tue wed thu fri sat))
(define (week-day date)
(vector-ref days (date-week-day date)))
(define (five-weekends-a-month start end)
(for*/list ([year (in-range start (+ end 1))]
[month long-months]
[date (in-value (make-date 0 0 0 0 31 month year 0))]
#:when (eq? (week-day date) 'sun))
date))
(define weekends (five-weekends-a-month 1900 2100))
(define count (length weekends))
(displayln (~a "There are " count " months with five weekends."))
(displayln "The first five are: ")
(for ([w (take weekends 5)])
(displayln (date->string w "~b ~Y")))
(displayln "The last five are: ")
(for ([w (drop weekends (- count 5))])
(displayln (date->string w "~b ~Y")))
|
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
|
#Standard_ML
|
Standard ML
|
- fun cube x = Math.pow(x, 3.0);
val cube = fn : real -> real
- fun croot x = Math.pow(x, 1.0 / 3.0);
val croot = fn : real -> real
- fun compose (f, g) = fn x => f (g x); (* this is already implemented in Standard ML as the "o" operator
= we could have written "fun compose (f, g) x = f (g x)" but we show this for clarity *)
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b
- val funclist = [Math.sin, Math.cos, cube];
val funclist = [fn,fn,fn] : (real -> real) list
- val funclisti = [Math.asin, Math.acos, croot];
val funclisti = [fn,fn,fn] : (real -> real) list
- ListPair.map (fn (f, inversef) => (compose (inversef, f)) 0.5) (funclist, funclisti);
val it = [0.5,0.5,0.500000000001] : real list
|
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
|
#Stata
|
Stata
|
function _sin(x) {
return(sin(x))
}
function _asin(x) {
return(asin(x))
}
function _cos(x) {
return(cos(x))
}
function _acos(x) {
return(acos(x))
}
function cube(x) {
return(x*x*x)
}
function cuberoot(x) {
return(sign(x)*abs(x)^(1/3))
}
function compose(f,g,x) {
return((*f)((*g)(x)))
}
a=&_sin(),&_cos(),&cube()
b=&_asin(),&_acos(),&cuberoot()
for(i=1;i<=length(a);i++) {
printf("%10.5f\n",compose(a[i],b[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
|
#Mirah
|
Mirah
|
import java.util.ArrayList
import java.util.List
import java.util.Collection
def flatten(list: Collection)
flatten(list, ArrayList.new)
end
def flatten(source: Collection, result: List)
source.each do |x|
if x.kind_of?(Collection)
flatten(Collection(x), result)
else
result.add(x)
result # if branches must return same type
end
end
result
end
# creating a list-of-list-of-list fails currently, so constructor calls are needed
source = [[1], 2, [[3, 4], 5], [[ArrayList.new]], [[[6]]], 7, 8, ArrayList.new]
puts flatten(source)
|
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)
|
#Picat
|
Picat
|
P1 = ["ABCD","CABD","ACDB","DACB","BCDA","ACBD",
"ADCB","CDAB","DABC","BCAD","CADB","CDBA",
"CBAD","ABDC","ADBC","BDCA","DCBA","BACD",
"BADC","BDAC","CBDA","DBCA","DCAB"],
Perms = permutations("ABCD"),
% ...
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
const proc: main is func
local
var integer: weekday is 1; # 1 for monday, 2 for tuesday, and so on up to 7 for sunday.
var integer: year is 0;
var integer: month is 1;
var time: aDate is time.value;
var time: selected is time.value;
begin
if length(argv(PROGRAM)) <> 2 then
writeln("usage: lastWeekdayInMonth weekday year");
writeln(" weekday: 1 for monday, 2 for tuesday, and so on up to 7 for sunday.");
else
weekday := integer parse (argv(PROGRAM)[1]);
year := integer parse (argv(PROGRAM)[2]);
for month range 1 to 12 do
aDate := date(year, month, 1);
while aDate.month = month do
if dayOfWeek(aDate) = weekday then
selected := aDate;
end if;
aDate +:= 1 . DAYS;
end while;
writeln(strDate(selected));
end for;
end if;
end func;
|
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
|
#Sidef
|
Sidef
|
var dt = require('DateTime');
var (year=2016) = ARGV.map{.to_i}...
for i in (1 .. 12) {
var date = dt.last_day_of_month(
year => year,
month => i
);
while (date.dow != 7) {
date = date.subtract(days => 1);
}
say date.ymd;
}
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <chrono>
int main()
{
int fizz = 0, buzz = 0, fizzbuzz = 0;
bool isFizz = false;
auto startTime = std::chrono::high_resolution_clock::now();
for (unsigned int i = 1; i <= 4000000000; i++) {
isFizz = false;
if (i % 3 == 0) {
isFizz = true;
fizz++;
}
if (i % 5 == 0) {
if (isFizz) {
fizz--;
fizzbuzz++;
}
else {
buzz++;
}
}
}
auto endTime = std::chrono::high_resolution_clock::now();
auto totalTime = endTime - startTime;
printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1)));
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.