Cheryl's birthday: Difference between revisions

Added FreeBASIC
m (Thundergnat moved page Cheryl's Birthday to Cheryl's birthday: Follow normal task title capitalization policy)
(Added FreeBASIC)
(27 intermediate revisions by 20 users not shown)
Line 27:
* [https://en.wikipedia.org/wiki/Tuple_relational_calculus, Tuple Relational Calculus]
<br><br>
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">T Date
String month
Int day
F (month, day)
.month = month
.day = day
 
V dates = [Date(‘May’, 15), Date(‘May’, 16), Date(‘May’, 19), Date(‘June’, 17), Date(‘June’, 18),
Date(‘July’, 14), Date(‘July’, 16), Date(‘August’, 14), Date(‘August’, 15), Date(‘August’, 17)]
 
DefaultDict[Int, Set[String]] monthTable
L(date) dates
monthTable[date.day].add(date.month)
 
DefaultDict[String, Set[Int]] dayTable
L(date) dates
dayTable[date.month].add(date.day)
 
Set[String] possibleMonths
Set[Int] possibleDays
 
L(month, days) dayTable
I days.len > 1
possibleMonths.add(month)
 
L(month, days) dayTable
L(day) days
I monthTable[day].len == 1
possibleMonths.remove(month)
print(‘After first Albert's sentence, possible months are ’Array(possibleMonths).join(‘, ’)‘.’)
 
L(day, months) monthTable
I months.len > 1
possibleDays.add(day)
 
Set[Int] impossibleDays
L(day) possibleDays
I monthTable[day].intersection(possibleMonths).len > 1
impossibleDays.add(day)
L(day) impossibleDays
possibleDays.remove(day)
print(‘After Bernard's sentence, possible days are ’Array(possibleDays).join(‘, ’)‘.’)
 
Set[String] impossibleMonths
L(month) possibleMonths
I dayTable[month].intersection(possibleDays).len > 1
impossibleMonths.add(month)
L(month) impossibleMonths
possibleMonths.remove(month)
 
assert(possibleMonths.len == 1)
V month = possibleMonths.pop()
print(‘After second Albert's sentence, remaining month is ’month‘...’)
 
possibleDays = possibleDays.intersection(dayTable[month])
assert(possibleDays.len == 1)
V day = possibleDays.pop()
print(‘and thus remaining day is ’day‘.’)
 
print()
print(‘So birthday date is ’month‘ ’day‘.’)</syntaxhighlight>
 
{{out}}
<pre>
After first Albert's sentence, possible months are August, July.
After Bernard's sentence, possible days are 15, 16, 17.
After second Albert's sentence, remaining month is July...
and thus remaining day is 16.
 
So birthday date is July 16.
</pre>
 
=={{Header|Ada}}==
{{trans|C}}
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Main is
type Months is
(January, February, March, April, May, June, July, August, September,
November, December);
type day_num is range 1 .. 31;
type birthdate is record
Month : Months;
Day : day_num;
Active : Boolean;
end record;
 
type birthday_list is array (Positive range <>) of birthdate;
 
Possible_birthdates : birthday_list :=
((May, 15, True), (May, 16, True), (May, 19, True), (June, 17, True),
(June, 18, True), (July, 14, True), (July, 16, True), (August, 14, True),
(August, 15, True), (August, 17, True));
 
procedure print_answer is
begin
for the_day of Possible_birthdates loop
if the_day.Active then
Put_Line (the_day.Month'Image & "," & the_day.Day'Image);
end if;
end loop;
end print_answer;
 
procedure print_remaining is
count : Natural := 0;
begin
for date of Possible_birthdates loop
if date.Active then
count := count + 1;
end if;
end loop;
Put_Line (count'Image & " remaining.");
end print_remaining;
 
-- the month cannot have a unique day
procedure first_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
count := 0;
for next_day of Possible_birthdates loop
if first_day.Day = next_day.Day then
count := count + 1;
end if;
end loop;
 
if count = 1 then
for the_day of Possible_birthdates loop
if the_day.Active and then first_day.Month = the_day.Month then
the_day.Active := False;
end if;
end loop;
end if;
end loop;
end first_pass;
 
-- the day must now be unique
procedure second_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
if first_day.Active then
count := 0;
for next_day of Possible_birthdates loop
if next_day.Active then
if next_day.Day = first_day.Day then
count := count + 1;
end if;
end if;
end loop;
 
if count > 1 then
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Day = first_day.Day then
next_day.Active := False;
end if;
end loop;
end if;
end if;
end loop;
end second_pass;
 
-- the month must now be unique
procedure third_pass is
count : Natural;
begin
for first_day of Possible_birthdates loop
if first_day.Active then
count := 0;
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Month = first_day.Month
then
count := count + 1;
end if;
end loop;
if count > 1 then
for next_day of Possible_birthdates loop
if next_day.Active and then next_day.Month = first_day.Month
then
next_day.Active := False;
end if;
end loop;
end if;
end if;
end loop;
end third_pass;
 
begin
print_remaining;
first_pass;
 
print_remaining;
second_pass;
 
print_remaining;
third_pass;
 
print_answer;
end Main;</syntaxhighlight>
{{out}}
<pre>
10 remaining.
5 remaining.
3 remaining.
JULY, 16
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<syntaxhighlight lang="algol68">
BEGIN # Cheryl's birthday puzzle #
 
[ 1 : 4, 1 : 6 ]INT dates # non-zero indicates a possible date #
:= ( ( 0, 15, 16, 0, 0, 19 ) # may #
, ( 0, 0, 0, 17, 18, 0 ) # june #
, ( 14, 0, 16, 0, 0, 0 ) # july #
, ( 14, 15, 0, 17, 0, 0 ) # august #
);
[]STRING month name = ( "May", "June", "July", "August" );
print( ( "Cheryl tells Albert the month and Bernard the day", newline ) );
print( ( "Albert doesn't know the date and knows Bernard doesn't either", newline ) );
FOR d TO 2 UPB dates DO # elimiate the months with unique days #
INT day count := 0;
INT day := 0;
INT month := 0;
FOR m TO 1 UPB dates DO
IF dates[ m, d ] /= 0 THEN
day count +:= 1;
day := dates[ m, d ];
month := m
FI
OD;
IF day count = 1 THEN
print( ( " Eliminating ", month name[ month ], ", ", whole( day, 0 ), "th is unique", newline ) );
FOR p TO 2 UPB dates DO dates[ month, p ] := 0 OD
FI
OD;
print( ( "Bernard now knows the date", newline ) );
FOR d TO 2 UPB dates DO # eliminate the days that aren't unique #
INT day count := 0;
INT day := 0;
INT month := 0;
FOR m TO 1 UPB dates DO
IF dates[ m, d ] /= 0 THEN
day count +:= 1;
day := dates[ m, d ];
month := m
FI
OD;
IF day count > 1 THEN
print( ( " Eliminating ", whole( day, 0 ), "th, it is non-unique", newline ) );
FOR p TO 1 UPB dates DO dates[ p, d ] := 0 OD
FI
OD;
print( ( "Albert now knows the date", newline ) );
FOR m TO 1 UPB dates DO # eliminate months with non-unique days #
INT day count := 0;
INT day := 0;
INT month := 0;
FOR d TO 2 UPB dates DO
IF dates[ m, d ] /= 0 THEN
day count +:= 1;
day := dates[ m, d ];
month := m
FI
OD;
IF day count > 1 THEN
print( ( " Eliminating ", month name[ m ], ", it has multiple days", newline ) );
FOR p TO 2 UPB dates DO dates[ m, p ] := 0 OD
FI
OD;
print( ( "Cheryl's birthday: " ) ); # show the solution(s) #
FOR m TO 1 UPB dates DO
FOR d TO 2 UPB dates DO
IF dates[ m, d ] /= 0 THEN
print( ( " ", month name[ m ], " ", whole( dates[ m, d ], 0 ), "th" ) )
FI
OD
OD;
print( ( newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
Cheryl tells Albert the month and Bernard the day
Albert doesn't know the date and knows Bernard doesn't either
Eliminating June, 18th is unique
Eliminating May, 19th is unique
Bernard now knows the date
Eliminating 14th, it is non-unique
Albert now knows the date
Eliminating August, it has multiple days
Cheryl's birthday: July 16th
</pre>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 650 ⟶ 947:
filteredArrayUsingPredicate:(ca's ¬
NSPredicate's predicateWithFormat:"0 < length")) as list
end |words|</langsyntaxhighlight>
{{Out}}
<pre>"[('july', '16')]"</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">dates: [
[May 15] [May 16] [May 19]
[June 17] [June 18]
[July 14] [July 16]
[August 14] [August 15] [August 17]
]
 
print ["possible dates:" dates]
 
print "\n(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too."
print "\t-> meaning: the month cannot have a unique day"
dates: filter dates 'd [
in? d\0 map select dates 'dd [
1 = size select dates 'pd -> pd\1=dd\1
] 'dd -> dd\0
]
print ["\t-> remaining:" dates]
 
print "\n(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now."
print "\t-> meaning: the day must be unique"
dates: select dates 'd [
1 = size select dates 'pd -> pd\1=d\1
]
print ["\t-> remaining:" dates]
 
print "\n(3) Albert: Then I also know when Cheryl's birthday is."
print "\t-> meaning: the month must be unique"
dates: select dates 'd [
1 = size select dates 'pd -> pd\0=d\0
]
print ["\t-> remaining:" dates]
 
print ["\nCheryl's birthday:" first dates]</syntaxhighlight>
 
{{out}}
 
<pre>possible dates: [[May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August 17]]
 
(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
-> meaning: the month cannot have a unique day
-> remaining: [[July 14] [July 16] [August 14] [August 15] [August 17]]
 
(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
-> meaning: the day must be unique
-> remaining: [[July 16] [August 15] [August 17]]
 
(3) Albert: Then I also know when Cheryl's birthday is.
-> meaning: the month must be unique
-> remaining: [[July 16]]
 
Cheryl's birthday: [July 16]</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">oDates:= {"May" : [ 15, 16, 19]
,"Jun" : [ 17, 18]
,"Jul" : [14, 16]
,"Aug" : [14, 15, 17]}
 
filter1(oDates)
filter2(oDates)
filter3(oDates)
MsgBox % result := checkAnswer(oDates)
return
 
filter1(ByRef oDates){ ; remove months that has a unique day in it.
for d, obj in MonthsOfDay(oDates)
if (obj.count() = 1)
for m, bool in obj
oDates.Remove(m)
}
 
filter2(ByRef oDates){ ; remove non-unique days from remaining months.
for d, obj in MonthsOfDay(oDates)
if (obj.count() > 1)
for m, bool in obj
for i, day in oDates[m]
if (day=d)
oDates[m].Remove(i)
}
 
filter3(ByRef oDates){ ; remove months that has multiple days from remaining months.
oRemove := []
for m, obj in oDates
if obj.count() > 1
oRemove.Push(m)
for i, m in oRemove
oDates.Remove(m)
}
 
MonthsOfDay(oDates){ ; create a list of months per day.
MonthsOfDay := []
for m, obj in oDates
for i, d in obj
MonthsOfDay[d, m] := 1
return MonthsOfDay
}
 
checkAnswer(oDates){ ; check unique answer if any.
if oDates.count()>1
return false
for m, obj in oDates
if obj.count() > 1
return false
else
return m " " obj.1
}</syntaxhighlight>
{{out}}
<pre>Jul 16</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f CHERYLS_BIRTHDAY.AWK [-v debug={0|1}]
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
debug += 0
PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1
n = split("05/15,05/16,05/19,06/17,06/18,07/14,07/16,08/14,08/15,08/17",arr,",")
for (i=1; i<=n; i++) { # move dates to a more friendly structure
mmdd_arr[arr[i]] = ""
}
print("Cheryl offers these ten MM/DD choices:")
cb_show_dates()
printf("Cheryl then tells Albert her birth 'month' and Bernard her birth 'day'.\n\n")
print("1. Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.")
cb_filter1()
print("2. Bernard: At first I don't know when Cheryl's birthday is, but I know now.")
cb_filter2()
print("3. Albert: Then I also know when Cheryl's birthday is.")
cb_filter3()
exit(0)
}
function cb_filter1( i,j) {
print("deduction: the month cannot have a unique day, leaving:")
cb_load_arrays(4)
for (j in arr1) {
if (arr1[j] == 1) {
if (debug) { printf("unique day %s\n",j) }
arr3[arr2[j]] = ""
}
}
cb_remove_dates()
}
function cb_filter2( i,j) {
print("deduction: the day must be unique, leaving:")
cb_load_arrays(4)
for (j in arr1) {
if (arr1[j] > 1) {
if (debug) { printf("non-unique day %s\n",j) }
arr3[j] = ""
}
}
cb_remove_dates("...")
}
function cb_filter3( i,j) {
print("deduction: the month must be unique, leaving:")
cb_load_arrays(1)
for (j in arr1) {
if (arr1[j] > 1) {
if (debug) { printf("non-unique month %s\n",j) }
arr3[j] = ""
}
}
cb_remove_dates()
}
function cb_load_arrays(col, i,key) {
delete arr1
delete arr2
delete arr3
for (i in mmdd_arr) {
key = substr(i,col,2)
arr1[key]++
arr2[key] = substr(i,1,2)
}
}
function cb_remove_dates(pattern, i,j) {
for (j in arr3) {
for (i in mmdd_arr) {
if (i ~ ("^" pattern j)) {
if (debug) { printf("removing %s\n",i) }
delete mmdd_arr[i]
}
}
}
cb_show_dates()
}
function cb_show_dates( i) {
if (debug) { printf("%d remaining\n",length(mmdd_arr)) }
for (i in mmdd_arr) {
printf("%s ",i)
}
printf("\n\n")
}
</syntaxhighlight>
{{out}}
<pre>
Cheryl offers these ten MM/DD choices:
05/15 05/16 05/19 06/17 06/18 07/14 07/16 08/14 08/15 08/17
 
Cheryl then tells Albert her birth 'month' and Bernard her birth 'day'.
 
1. Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
deduction: the month cannot have a unique day, leaving:
07/14 07/16 08/14 08/15 08/17
 
2. Bernard: At first I don't know when Cheryl's birthday is, but I know now.
deduction: the day must be unique, leaving:
07/16 08/15 08/17
 
3. Albert: Then I also know when Cheryl's birthday is.
deduction: the month must be unique, leaving:
07/16
</pre>
=={{header|C}}==
{{trans|C#}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
 
Line 781 ⟶ 1,293:
printAnswer();
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>10 remaining.
Line 787 ⟶ 1,299:
3 remaining.
Jul, 16</pre>
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">public static class CherylsBirthday
=={{header|C sharp}}==
<lang csharp>public static class CherylsBirthday
{
public static void Main() {
Line 818 ⟶ 1,329:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 826 ⟶ 1,337:
(July, 16)
</pre>
 
=={{header|C++}}==
{{trans|Go}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 939 ⟶ 1,449:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Cheryl's birthday is Jul 16</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
;; Author: Amir Teymuri, Saturday 20.10.2018
 
Line 974 ⟶ 1,483:
 
(cheryls-birthday *possible-dates*) ;; => ((16 . JULY))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.algorithm.iteration : filter, joiner, map;
import std.algorithm.searching : canFind;
import std.algorithm.sorting : sort;
Line 1,016 ⟶ 1,524:
// print the result
writeln(birthDay.month, " ", birthDay.day);
}</langsyntaxhighlight>
{{out}}
<pre>jul 16</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//Find Cheryl's Birthday. Nigel Galloway: October 23rd., 2018
type Month = |May |June |July |August
Line 1,031 ⟶ 1,538:
let _,e = List.concat g |> List.groupBy fst |> fN
printfn "%A" e
</syntaxhighlight>
</lang>
{{out}}
<pre>
[[(July, 16)]]
</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs calendar.english fry io kernel prettyprint
sequences sets.extras ;
 
Line 1,063 ⟶ 1,569:
 
! print a date that looks like { { 16 7 } }
first first2 month-name write bl .</langsyntaxhighlight>
{{out}}
<pre>
July 16
</pre>
 
=={{header|FreeBASIC}}==
{{trans|ALGOL 68}}
<syntaxhighlight lang="vbnet">Dim As Integer i, j, contarDias, dia, mes
Dim fechas(1 To 4, 1 To 6) As Integer => {{0, 15, 16, 0, 0, 19}, {0, 0, 0, 17, 18, 0}, {14, 0, 16, 0, 0, 0}, {14, 15, 0, 17, 0, 0}}
Dim nombreMes(1 To 4) As String => {"May", "June", "July", "August"}
 
Print "Cheryl tells Albert the month and Bernard the day"
Print "Albert doesn't know the date and knows Bernard doesn't either"
 
' elimiate the months with unique days
For i = 1 To 6
contarDias = 0
dia = 0
mes = 0
For j = 1 To 4
If fechas(j, i) <> 0 Then
contarDias += 1
dia = fechas(j, i)
mes = j
End If
Next j
If contarDias = 1 Then
Print " Eliminating "; nombreMes(mes); ", "; Str(dia); "th is unique"
For j = 1 To 6
fechas(mes, j) = 0
Next j
End If
Next i
 
Print "Bernard now knows the date"
 
' eliminate the days that aren't unique
For i = 1 To 6
contarDias = 0
dia = 0
mes = 0
For j = 1 To 4
If fechas(j, i) <> 0 Then
contarDias += 1
dia = fechas(j, i)
mes = j
End If
Next j
If contarDias > 1 Then
Print " Eliminating "; Str(dia); "th, it is non-unique"
For j = 1 To 4
fechas(j, i) = 0
Next j
End If
Next i
 
Print "Albert now knows the date"
 
' eliminate months with non-unique days
For i = 1 To 4
contarDias = 0
dia = 0
mes = 0
For j = 1 To 6
If fechas(i, j) <> 0 Then
contarDias += 1
dia = fechas(i, j)
mes = i
End If
Next j
If contarDias > 1 Then
Print " Eliminating "; nombreMes(i); ", it has multiple days"
For j = 1 To 6
fechas(i, j) = 0
Next j
End If
Next i
 
Print "Cheryl's birthday: ";
For i = 1 To 4
For j = 1 To 6
If fechas(i, j) <> 0 Then
Print " "; nombreMes(i); " "; Str(fechas(i, j)); "th"
End If
Next j
Next i
 
Sleep</syntaxhighlight>
{{out}}
<pre>Same as ALGOL 68 entry.</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,165 ⟶ 1,757:
fmt.Println("Something went wrong!")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,171 ⟶ 1,763:
Cheryl's birthday is July 16
</pre>
=={{header|Fortran}}==
{{trans|C}}
<syntaxhighlight lang="fortran">
program code_translation
implicit none
character(len=3), dimension(13) :: months = ["ERR", "Jan", "Feb", "Mar", "Apr", "May",&
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
type :: Date
integer :: month, day
logical :: active
end type Date
type(Date), dimension(10) :: dates = [Date(5,15,.true.), Date(5,16,.true.), Date(5,19,.true.), &
Date(6,17,.true.), Date(6,18,.true.), &
Date(7,14,.true.), Date(7,16,.true.), &
Date(8,14,.true.), Date(8,15,.true.), Date(8,17,.true.)]
integer, parameter :: UPPER_BOUND = size(dates)
write(*,*) 'possible dates: [[May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August &
17]]'
write(*,*)
write(*,*) '(1) Albert: I don''t know when Cheryl''s birthday is, but I know that Bernard does not know too.'
write(*,*) ' -> meaning: the month cannot have a unique day'
write(*,*) ' -> remaining: [[July 14] [July 16] [August 14] [August 15] [August 17]] '
write(*,*)
write(*,*) "(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now."
write(*,*) ' -> meaning: the day must be unique'
write(*,*) ' -> remaining: [[July 16] [August 15] [August 17]] '
write(*,*)
write(*,*) '(3) Albert: Then I also know when Cheryl''s birthday is.'
write(*,*) ' -> meaning: the month must be unique'
write(*,*) ' -> remaining: [[July 16]] '
 
call printRemaining()
! the month cannot have a unique day
call firstPass()
call printRemaining()
! the day must now be unique
call secondPass()
call printRemaining()
! the month must now be unique
call thirdPass()
call printAnswer()
 
contains
 
subroutine printRemaining()
integer :: i, c
do i = 1, UPPER_BOUND
if (dates(i)%active) then
write(*,'(a,1x,i0,1x)',advance="no") months(dates(i)%month+1),dates(i)%day
c = c + 1
end if
end do
!
write(*,*)
end subroutine printRemaining
 
subroutine printAnswer()
integer :: i
write(*,'(a)',advance ='no') 'Cheryl''s birtday is on '
do i = 1, UPPER_BOUND
if (dates(i)%active) then
write(*,'(a,1a1,i0)') trim(months(dates(i)%month+1)), ",", dates(i)%day
end if
end do
end subroutine printAnswer
 
subroutine firstPass()
! the month cannot have a unique day
integer :: i, j, c
do i = 1, UPPER_BOUND
c = 0
do j = 1, UPPER_BOUND
if (dates(j)%day == dates(i)%day) then
c = c + 1
end if
end do
if (c == 1) then
do j = 1, UPPER_BOUND
if (.not. dates(j)%active) cycle
if (dates(j)%month == dates(i)%month) then
dates(j)%active = .false.
end if
end do
end if
end do
end subroutine firstPass
 
subroutine secondPass()
! the day must now be unique
integer :: i, j, c
do i = 1, UPPER_BOUND
if (.not. dates(i)%active) cycle
c = 0
do j = 1, UPPER_BOUND
if (.not. dates(j)%active) cycle
if (dates(j)%day == dates(i)%day) then
c = c + 1
end if
end do
if (c > 1) then
do j = 1, UPPER_BOUND
if (.not. dates(j)%active) cycle
if (dates(j)%day == dates(i)%day) then
dates(j)%active = .false.
end if
end do
end if
end do
end subroutine secondPass
 
subroutine thirdPass()
! the month must now be unique
integer :: i, j, c
do i = 1, UPPER_BOUND
if (.not. dates(i)%active) cycle
c = 0
do j = 1, UPPER_BOUND
if (.not. dates(j)%active) cycle
if (dates(j)%month == dates(i)%month) then
c = c + 1
end if
end do
if (c > 1) then
do j = 1, UPPER_BOUND
if (.not. dates(j)%active) cycle
if (dates(j)%month == dates(i)%month) then
dates(j)%active = .false.
end if
end do
end if
end do
end subroutine thirdPass
 
end program code_translation
</syntaxhighlight>
{{out}}
<pre>
possible dates: [[May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August 17]]
 
(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
-> meaning: the month cannot have a unique day
-> remaining: [[July 14] [July 16] [August 14] [August 15] [August 17]]
 
(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
-> meaning: the day must be unique
-> remaining: [[July 16] [August 15] [August 17]]
 
(3) Albert: Then I also know when Cheryl's birthday is.
-> meaning: the month must be unique
-> remaining: [[July 16]]
May 15 May 16 May 19 Jun 17 Jun 18 Jul 14 Jul 16 Aug 14 Aug 15 Aug 17
Jul 14 Jul 16 Aug 14 Aug 15 Aug 17
Jul 16 Aug 15 Aug 17
Cheryl's birthday is on Jul,16
</Pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.time.Month
 
class Main {
Line 1,247 ⟶ 1,994:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>There are 10 candidates remaining.
Line 1,254 ⟶ 2,001:
There are 1 candidates remaining.
Cheryl's birthday is JULY 16</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
import Data.List as L (filter, groupBy, head, length, sortOn)
Line 1,327 ⟶ 2,073:
M.fromList $
((,) . fst . L.head) <*> fmap snd <$>
L.groupBy (on (==) fst) (L.sortOn fst xs)</langsyntaxhighlight>
{{Out}}
<pre>[("July","16")]</pre>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">Dates=: <;._2cutLF noun define
15 May
16 May
Line 1,346 ⟶ 2,091:
)
 
getDayMonth=: |:@:(' '&splitstringcut&>) NB. retrieve lists of days and months from dates
keep=: adverb def '] #~ u' NB. apply mask to filter dates
 
Line 1,356 ⟶ 2,101:
 
uniqueMonth=: ~.@] #~ (1=#)/.~ NB. list of months with 1 unique day
isUniqueMonth=: (] e. uniqueMonth)/@getDayMonth NB. mask of dates with a month that has 1 unique day</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> isUniqueMonth keep isUniqueDayInMonth keep isMonthWithoutUniqueDay keep Dates
+-------+
|16 July|
+-------+</langsyntaxhighlight>
 
===Alternative Approach===
Line 1,367 ⟶ 2,112:
The concepts here are the same, of course, it's just the presentation that's different.
 
<langsyntaxhighlight Jlang="j">possible=: cut;._2 'May 15, May 16, May 19, June 17, June 18, July 14, July 16, August 14, August 15, August 17,'
 
Albert=: {."1 NB. Albert knows month
Line 1,384 ⟶ 2,129:
possibleB=. (days e. days-.invaliddays)# possibleA
 
NB. our understanding of Albert's secondunderstanding of Bernard's understanding of Albert's first pass
months=: {."1 possibleB
invalidmonths=: (1<#/.~months)#~.months
echo ;:inv (months e. months -. invalidmonths)#possibleB</langsyntaxhighlight>
 
This gives us the July 16 result we were expecting
Line 1,393 ⟶ 2,138:
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">import java.time.Month;
import java.util.Collection;
import java.util.List;
Line 1,478 ⟶ 2,223:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>There are 10 candidates remaining.
Line 1,485 ⟶ 2,230:
There are 1 candidates remaining.
Cheryl's birthday is JULY 16</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,663 ⟶ 2,407:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[["July","16"]]</pre>
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
A Birthday is represented by a JSON object {month, day} where {month:0} represents January.
<syntaxhighlight lang="jq">def count(stream; cond):
reduce stream as $i (0; if $i|cond then .+1 else . end);
 
def Months: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
 
# tostring
def birthday: "\(Months[.month-1]) \(.day)";
 
# Input: a Birthday
def monthUniqueIn($bds):
.month as $thisMonth
| count( $bds[]; .month == $thisMonth) == 1;
 
# Input: a Birthday
def dayUniqueIn($bds):
.day as $thisDay
| count( $bds[]; .day == $thisDay) == 1;
 
# Input: a Birthday
def monthWithUniqueDayIn($bds):
.month as $thisMonth
| any( $bds[]; $thisMonth == .month and dayUniqueIn($bds));
def choices: [
{month: 5, day: 15}, {month: 5, day: 16}, {month: 5, day: 19}, {month: 6, day: 17},
{month: 6, day: 18}, {month: 7, day: 14}, {month: 7, day: 16}, {month: 8, day: 14},
{month: 8, day: 15}, {month: 8, day: 17}
];
# Albert knows the month but doesn't know the day,
# so the month can't be unique within the choices.
def filter1:
. as $in
| map(select( monthUniqueIn($in) | not));
# Albert also knows that Bernard doesn't know the answer,
# so the month can't have a unique day.
def filter2:
. as $in
| map(select( monthWithUniqueDayIn($in) | not));
# Bernard now knows the answer,
# so the day must be unique within the remaining choices.
def filter3:
. as $in
| map(select( dayUniqueIn($in) ));
# Albert now knows the answer too.
# So the month must be unique within the remaining choices.
def filter4:
. as $in
| map(select( monthUniqueIn($in) ));
 
def solve:
(choices | filter1 | filter2 | filter3 | filter4) as $bds
| if $bds|length == 1
then "Cheryl's birthday is \($bds[0]|birthday)."
else "Whoops!"
end;
 
solve</syntaxhighlight>
{{out}}
<pre>
Cheryl's birthday is July 16.
</pre>
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const dates = [[15, "May"], [16, "May"], [19, "May"], [17, "June"], [18, "June"],
[14, "July"], [16, "July"], [14, "August"], [15, "August"], [17, "August"]]
Line 1,683 ⟶ 2,500:
 
println("Cheryl's birthday is $(bday[2]) $(bday[1]).")
</langsyntaxhighlight>{{out}}
<pre>
Cheryl's birthday is July 16.
</pre>
 
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.2.71
 
val months = listOf(
Line 1,740 ⟶ 2,556:
else
println("Something went wrong!")
}</langsyntaxhighlight>
 
{{output}}
Line 1,746 ⟶ 2,562:
Cheryl's birthday is July 16
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Cheryl's Birthday in Lua 6/15/2020 db
 
local function Date(mon,day)
Line 1,818 ⟶ 2,633:
if count(subset) > 1 then apply(subset, invalidate) end
end)
listValidChoices()</langsyntaxhighlight>
{{out}}
<pre>Cheryl offers these ten choices:
Line 1,831 ⟶ 2,646:
3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:
July 16</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
<syntaxhighlight lang="mathematica">opts = Tuples[{{"May"}, {15, 16, 19}}]~Join~Tuples[{{"June"}, {17, 18}}]~Join~Tuples[{{"July"}, {14, 16}}]~Join~Tuples[{{"August"}, {14, 15, 17}}];
monthsdelete = Select[GatherBy[opts, Last], Length /* EqualTo[1]][[All, 1, 1]];
opts = DeleteCases[opts, {Alternatives @@ monthsdelete, _}]
removedates = Catenate@Select[GatherBy[opts, Last], Length /* GreaterThan[1]];
opts = DeleteCases[opts, Alternatives @@ removedates]
Select[GatherBy[opts, First], Length /* EqualTo[1]]</syntaxhighlight>
{{out}}
<pre>{{"July", 14}, {"July", 16}, {"August", 14}, {"August", 15}, {"August", 17}}
{{"July", 16}, {"August", 15}, {"August", 17}}
{{{"July", 16}}}</pre>
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import tables
import sets
import strformat
Line 1,909 ⟶ 2,734:
 
echo ""
echo fmt"So birthday date is {month} {day}."</langsyntaxhighlight>
 
{{out}}
Line 1,918 ⟶ 2,743:
 
So birthday date is July 16</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub filter {
my($test,@dates) = @_;
my(%M,%D,@filtered);
Line 1,959 ⟶ 2,783:
 
my ($m, $d) = split '-', $dates[0];
print "Cheryl's birthday is $months[$m] $d.\n";</langsyntaxhighlight>
{{out}}
<pre>Cheryl's birthday is July 16.</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- demo\rosetta\Cheryls_Birthday.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Cheryls_Birthday.exw</span>
sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
{7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">choices</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">19</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">18</span><span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">14</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">14</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">}}</span>
sequence mwud = repeat(false,12) -- months with unique days
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mwud</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- months with unique days</span>
for step=1 to 4 do
sequence {months,days} = columnize(choices)
<span style="color: #008080;">for</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
bool impossible = false
<span style="color: #004080;">sequence</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">months</span><span style="color: #0000FF;">,</span><span style="color: #000000;">days</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">)</span>
for i=length(choices) to 1 by -1 do
<span style="color: #004080;">bool</span> <span style="color: #000000;">impossible</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
integer {m,d} = choices[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
switch step do
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">choices</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
case 1: mwud[m] += (sum(sq_eq(days,d))=1)
<span style="color: #008080;">switch</span> <span style="color: #000000;">step</span> <span style="color: #008080;">do</span>
case 2: impossible = mwud[m]
<span style="color: #008080;">case</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">mwud</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
case 3: impossible = (sum(sq_eq(days,d))!=1)
<span style="color: #008080;">case</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">impossible</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mwud</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
case 4: impossible = (sum(sq_eq(months,m))!=1)
<span style="color: #008080;">case</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">impossible</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">))!=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
end switch
<span style="color: #008080;">case</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">impossible</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">months</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">))!=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
if impossible then
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
choices[i..i] = {}
<span style="color: #008080;">if</span> <span style="color: #000000;">impossible</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">choices</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
?choices</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
Iterating backwards down the choices array simplifies element removal.<br>
<span style="color: #0000FF;">?</span><span style="color: #000000;">choices</span>
<!--</syntaxhighlight>-->
Iterating backwards down the choices array simplifies element removal, or more accurately removes the need for "not increment i".<br>
Step 1&2 is months with unique days, step 3 is days with unique months, step 4 is unique months.
{{out}}
Line 1,996 ⟶ 2,822:
=== functional/filter ===
(this can also be found in demo\rosetta\Cheryls_Birthday.exw)
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum MONTH, DAY
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">enum</span> <span style="color: #000000;">MONTH</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">DAY</span>
function unique_month(sequence si, months)
return sum(sq_eq(months,si[MONTH]))=1
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">unique_month</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">months</span><span style="color: #0000FF;">)</span>
function unique_day(sequence si, days)
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">months</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">[</span><span style="color: #000000;">MONTH</span><span style="color: #0000FF;">]))=</span><span style="color: #000000;">1</span>
return sum(sq_eq(days,si[DAY]))=1
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function
 
<span style="color: #008080;">function</span> <span style="color: #000000;">unique_day</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">days</span><span style="color: #0000FF;">)</span>
function month_without_unique_day(sequence si, months_with_unique_day)
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">[</span><span style="color: #000000;">DAY</span><span style="color: #0000FF;">]))=</span><span style="color: #000000;">1</span>
return not find(si[MONTH],months_with_unique_day)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function
 
sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},
{7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}}
<span style="color: #008080;">function</span> <span style="color: #000000;">month_without_unique_day</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">months_with_unique_day</span><span style="color: #0000FF;">)</span>
-- Albert knows the month but does not know the day.
<span style="color: #008080;">return</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">[</span><span style="color: #000000;">MONTH</span><span style="color: #0000FF;">],</span><span style="color: #000000;">months_with_unique_day</span><span style="color: #0000FF;">)</span>
-- So the month cannot be unique within the choices.
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
-- However this step would change nothing, hence omit it.
-- (obvs. non_unique_month() would be as above, but !=1)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">choices</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">19</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">18</span><span style="color: #0000FF;">},</span>
--choices = filter(choices,non_unique_month,vslice(choices,MONTH))
<span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">14</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">14</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">17</span><span style="color: #0000FF;">}}</span>
 
-- Albert also knows that Bernard doesn't know the answer.
<span style="color: #000080;font-style:italic;">-- SoAlbert knows the month cannotbut havedoes anot uniqueknow the day.
-- So the month cannot be unique within the choices.
sequence unique_days = filter(choices,unique_day,vslice(choices,DAY))
-- However this step would change nothing, hence omit it.
sequence months_with_unique_day = unique(vslice(unique_days,MONTH))
-- (obvs. non_unique_month() would be as above, but !=1)
 
--choices = filter(choices,month_without_unique_daynon_unique_month,months_with_unique_dayvslice(choices,MONTH))
 
-- BernardAlbert nowalso knows that Bernard doesn't know the answer.
-- So the daymonth mustcannot behave a unique within the remaining choicesday.</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">unique_days</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unique_day</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DAY</span><span style="color: #0000FF;">))</span>
choices = filter(choices,unique_day,vslice(choices,DAY))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">months_with_unique_day</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #000000;">unique_days</span><span style="color: #0000FF;">,</span><span style="color: #000000;">MONTH</span><span style="color: #0000FF;">))</span>
 
-- Albert now knows the answer too.
<span style="color: #000000;">choices</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">month_without_unique_day</span><span style="color: #0000FF;">,</span><span style="color: #000000;">months_with_unique_day</span><span style="color: #0000FF;">)</span>
-- So the month must be unique within the remaining choices.
choices = filter(choices,unique_month,vslice(choices,MONTH))
<span style="color: #000080;font-style:italic;">-- Bernard now knows the answer.
 
-- So the day must be unique within the remaining choices.</span>
if length(choices)!=1 then crash("Something went wrong!") end if
<span style="color: #000000;">choices</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unique_day</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DAY</span><span style="color: #0000FF;">))</span>
 
include builtins\timedate.e
<span style="color: #000080;font-style:italic;">-- Albert now knows the answer too.
timedate td = repeat(0,6)
-- So the month must be unique within the remaining choices.</span>
{td[DT_MONTH],td[DT_DAY]} = choices[1]
<span style="color: #000000;">choices</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unique_month</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">MONTH</span><span style="color: #0000FF;">))</span>
printf(1,"Cheryl's birthday is %s\n", {format_timedate(td,"Mmmm ddth")})</lang>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">choices</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Something went wrong!"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">timedate</span> <span style="color: #000000;">td</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">td</span><span style="color: #0000FF;">[</span><span style="color: #004600;">DT_MONTH</span><span style="color: #0000FF;">],</span><span style="color: #000000;">td</span><span style="color: #0000FF;">[</span><span style="color: #004600;">DT_DAY</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">choices</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Cheryl's birthday is %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">format_timedate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">td</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Mmmm ddth"</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Cheryl's birthday is July 16th
</pre>
 
=={{header|Python}}==
===Functional===
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Cheryl's Birthday'''
 
from itertools import groupby
Line 2,175 ⟶ 3,003:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[('July', '16')]</pre>
=={{header|R}}==
{{libheader|dplyr}}
<syntaxhighlight lang="r">options <- dplyr::tibble(mon = rep(c("May", "June", "July", "August"),times = c(3,2,2,3)),
day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17))
 
okMonths <- c()
# Albert's first clue - it is a month with no unique day
for (i in unique(options$mon)){
if(all(options$day[options$mon == i] %in% options$day[options$mon != i])) {okMonths <- c(okMonths, i)}
}
 
okDays <- c()
# Bernard's clue - it is a day that only occurs once in the remaining dates
for (i in unique(options$day)){
if(!all(options$mon[options$day == i] %in% options$mon[(options$mon %in% okMonths)])) {okDays <- c(okDays, i)}
}
 
remaining <- options[(options$mon %in% okMonths) & (options$day %in% okDays), ]
# Albert's second clue - must be a month with only one un-eliminated date
for(i in unique(remaining$mon)){
if(sum(remaining$mon == i) == 1) {print(remaining[remaining$mon == i,])}
}</syntaxhighlight>
{{Out}}
<pre># A tibble: 1 x 2
mon day
<chr> <dbl>
1 July 16</pre>
=={{header|Racket}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="racket">#lang racket
 
(define ((is x #:key [key identity]) y) (equal? (key x) (key y)))
Line 2,210 ⟶ 3,064:
;; Albert now knows the answer too.
;; So the month must be unique within the remaining choices
[filter (unique albert)])</langsyntaxhighlight>
 
{{out}}
Line 2,216 ⟶ 3,070:
'((July 16))
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>my @dates =
{ :15day, :5month },
{ :16day, :5month },
Line 2,243 ⟶ 3,096:
my @months = <'' January February March April May June July August September October November December>;
 
say "Cheryl's birthday is { @months[$birthday<month>] } {$birthday<day>}.";</langsyntaxhighlight>
{{out}}
<pre>Cheryl's birthday is July 16.</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm finds Cheryl's birth date based on a person knowing the birth month, another */
/*──────────────────────── person knowing the birth day, given a list of possible dates.*/
$= 'May-15 May-16 May-19 June-17 June-18 July-14 July-16 August-14 August-15 August-17'
Line 2,282 ⟶ 3,134:
end /*k*/
end /*j*/
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
Cheryl's birthday is July 16
</pre>
 
=={{header|Ruby}}==
{{trans|C#}}
<langsyntaxhighlight lang="ruby">dates = [
["May", 15],
["May", 16],
Line 2,324 ⟶ 3,175:
.map { |k,v| v }
.flatten
print dates</langsyntaxhighlight>
{{out}}
<pre>10 remaining
Line 2,330 ⟶ 3,181:
3 remaining
["July", 16]</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
// This version is based on the Go version on Rosettacode
 
#[derive(PartialEq, Debug, Copy, Clone)]
enum Month {
May,
June,
July,
August,
}
 
#[derive(PartialEq, Debug, Copy, Clone)]
struct Birthday {
month: Month,
day: u8,
}
 
impl Birthday {
fn month_unique_in(&self, birthdays: &[Birthday]) -> bool {
birthdays
.iter()
.filter(|birthday| birthday.month == self.month)
.count()
== 1
}
 
fn day_unique_in(&self, birthdays: &[Birthday]) -> bool {
birthdays
.iter()
.filter(|birthday| birthday.day == self.day)
.count()
== 1
}
 
fn month_with_unique_day_in(&self, birthdays: &[Birthday]) -> bool {
birthdays
.iter()
.any(|birthday| self.month == birthday.month && birthday.day_unique_in(birthdays))
}
}
 
fn solution() -> Option<Birthday> {
let mut choices: Vec<Birthday> = vec![
Birthday {
month: Month::May,
day: 15,
},
Birthday {
month: Month::May,
day: 16,
},
Birthday {
month: Month::May,
day: 19,
},
Birthday {
month: Month::June,
day: 17,
},
Birthday {
month: Month::June,
day: 18,
},
Birthday {
month: Month::July,
day: 14,
},
Birthday {
month: Month::July,
day: 16,
},
Birthday {
month: Month::August,
day: 14,
},
Birthday {
month: Month::August,
day: 15,
},
Birthday {
month: Month::August,
day: 17,
},
];
 
// Albert knows the month but doesn't know the day.
// So the month can't be unique within the choices.
let choices_copy = choices.clone();
choices.retain(|birthday| !(&birthday.month_unique_in(&choices_copy)));
 
// Albert also knows that Bernard doesn't know the answer.
// So the month can't have a unique day.
let choices_copy = choices.clone();
choices.retain(|birthday| !(birthday.month_with_unique_day_in(&choices_copy)));
 
// Bernard now knows the answer.
// So the day must be unique within the remaining choices.
let choices_copy = choices.clone();
choices.retain(|birthday| birthday.day_unique_in(&choices_copy));
 
// Albert now knows the answer too.
// So the month must be unique within the remaining choices.
let choices_copy = choices.clone();
choices.retain(|birthday| birthday.month_unique_in(&choices_copy));
 
if choices.len() == 1 {
Some(choices[0])
} else {
None
}
}
 
fn main() {
match solution() {
Some(solution) => println!("Cheryl's birthday is {:?}", solution),
None => panic!("Didn't work!"),
}
}
 
</syntaxhighlight>
{{out}}
<pre>
Cheryl's birthday is Birthday { month: July, day: 16 }
</pre>
=={{header|Scala}}==
==={{trans|D}}===
<langsyntaxhighlight lang="scala">import java.time.format.DateTimeFormatter
import java.time.{LocalDate, Month}
 
Line 2,377 ⟶ 3,352:
printf(birthDay.format(DateTimeFormatter.ofPattern("MMMM dd")))
}
}</langsyntaxhighlight>
{{out}}
<pre>July 16</pre>
Line 2,389 ⟶ 3,364:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<langsyntaxhighlight Scalalang="scala">object Cheryl_sBirthday extends App {
 
private val possiblerDates = Set(
Line 2,421 ⟶ 3,396:
 
println(clou3)
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">structfunc Datef(day, month) {
Date.parse("#{day} #{month}", "%d %B")
}
 
var dates = [
Datef(15, "May"),
Datef(16, "May"),
Datef(19, "May"),
Datef(17, "June"),
Datef(18, "June"),
Datef(14, "July"),
Datef(16, "July"),
Datef(14, "August"),
Datef(15, "August"),
Datef(17, "August")
]
 
 
var filtered = dates.grep {
dates.grep {
dates.map{ .day }.count(.day) == 1
}.map{ .month }.count(.month)  != 1
}
 
 
var birthday = filtered.grep {
filtered.map{ .day }.count(.day) == 1
}.group_by{ .month }.values.first_by { .len == 1 }[0]
 
 
say "Cheryl's birthday is #{birthday.monthfullmonth} #{birthday.day}."</langsyntaxhighlight>
{{out}}
<pre>
Cheryl's birthday is July 16.
</pre>
 
=={{header|Swift}}==
 
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="swift">struct MonthDay: CustomStringConvertible {
static let months = [
"January", "February", "March", "April", "May", "June",
Line 2,515 ⟶ 3,490:
}
 
print("Cheryl's birthday is \(birthday)")</langsyntaxhighlight>
 
{{out}}
 
<pre>Cheryl's birthday is July 16</pre>
=={{header|uBasic/4tH}}==
{{trans|C}}
<syntaxhighlight lang="ubasic/4th">Dim @d(30)
Dim @m(13)
 
Push 5,15,1, 5,16,1, 5,19,1, 6,17,1 ,6,18,1, 7,14,1, 7,16,1, 8,14,1, 8,15,1, 8,17,1
For x = 29 To 0 Step -1 : @d(x) = Pop() : Next
 
Push "ERR", "Jan", "Feb", "Mar", "Apr", "May"
Push "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
For x = 12 To 0 Step -1 : @m(x) = Pop() : Next
 
Proc _printRemaining ' the month cannot have a unique day
Proc _firstPass
 
Proc _printRemaining ' the day must now be unique
Proc _secondPass
 
Proc _printRemaining ' the month must now be unique
Proc _thirdPass
 
Proc _printAnswer
End
 
_printRemaining
Local (2)
b@ = 0
For a@ = 0 To 29 Step 3
If @d(a@+2) Then b@ = b@ + 1
Next
 
Print b@; " remaining."
Return
 
_printAnswer
Local (1)
 
For a@ = 0 To 29 Step 3
If @d(a@+2) Then Print Show (@m(@d(a@))); ", "; @d(a@+1)
Next
Return
 
_firstPass ' the month cannot have a unique day
Local (3)
For a@ = 0 To 29 Step 3
c@ = 0
For b@ = 0 To 29 Step 3
If @d(b@+1) = @d(a@+1) Then c@ = c@ + 1
Next
If c@ = 1 Then
For b@ = 0 To 29 Step 3
If @d(b@+2) = 0 Then
Continue
EndIf
If @d(b@) = @d(a@) Then
@d(b@+2) = 0
EndIf
Next
EndIf
Next
Return
 
_secondPass ' the day must now be unique
Local (3)
For a@ = 0 To 29 Step 3
If @d(a@+2) = 0 Then Continue
c@ = 0
For b@ = 0 To 29 Step 3
If @d(b@+2) = 0 Then Continue
If @d(b@+1) = @d(a@+1) Then c@ = c@ + 1
Next
If c@ > 1 Then
For b@ = 0 To 29 Step 3
If @d(b@+2) = 0 Then
Continue
EndIf
If @d(b@+1) = @d(a@+1) Then
@d(b@+2) = 0
EndIf
Next
EndIf
Next
Return
 
_thirdPass ' the month must now be unique
Local (3)
For a@ = 0 To 29 Step 3
If @d(a@+2) = 0 Then Continue
c@ = 0
For b@ = 0 To 29 Step 3
If @d(b@+2) = 0 Then Continue
If @d(b@) = @d(a@) Then c@ = c@ + 1
Next
If c@ > 1 Then
For b@ = 0 To 29 Step 3
If @d(b@+2) = 0 Then
Continue
EndIf
If @d(b@) = @d(a@) Then
@d(b@+2) = 0
EndIf
Next
EndIf
Next
Return</syntaxhighlight>
{{Out}}
<pre>10 remaining.
5 remaining.
3 remaining.
Jul, 16
 
0 OK, 0:657</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Sub exclude_unique_days(w As Collection)
Dim number_of_dates(31) As Integer
Dim months_to_exclude As New Collection
Line 2,581 ⟶ 3,681:
exclude_non_unique_months v
Debug.Print v(1)(0); " "; v(1)(1)
End Sub</langsyntaxhighlight>{{out}}
<pre>July 16</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Structure MonDay
Line 2,631 ⟶ 3,731:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>10 remaining.
Line 2,637 ⟶ 3,737:
3 remaining.
(July, 16)</pre>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import time
 
struct Birthday {
month int
day int
}
fn (b Birthday) str() string {
return "${time.long_months[b.month-1]} $b.day"
}
fn (b Birthday) month_uniquie_in(bds []Birthday) bool {
mut count := 0
for bd in bds {
if bd.month == b.month {
count++
}
}
if count == 1 {
return true
}
return false
}
fn (b Birthday) day_unique_in(bds []Birthday) bool {
mut count := 0
for bd in bds {
if bd.day == b.day {
count++
}
}
if count == 1 {
return true
}
return false
}
fn (b Birthday) month_with_unique_day_in(bds []Birthday) bool {
for bd in bds {
if bd.month == b.month && bd.day_unique_in(bds) {
return true
}
}
return false
}
fn main() {
choices := [
Birthday{5, 15}, Birthday{5, 16}, Birthday{5, 19}, Birthday{6, 17}, Birthday{6, 18},
Birthday{7, 14}, Birthday{7, 16}, Birthday{8, 14}, Birthday{8, 15}, Birthday{8, 17},
]
// Albert knows the month but doesn't know the day.
// So the month can't be unique within the choices.
mut filtered := []Birthday{}
for bd in choices {
if !bd.month_uniquie_in(choices) {
filtered << bd
}
}
// Albert also knows that Bernard doesn't know the answer.
// So the month can't have a unique day.
mut filtered2 := []Birthday{}
for bd in filtered {
if !bd.month_with_unique_day_in(filtered) {
filtered2 << bd
}
}
// Bernard now knows the answer.
// So the day must be unique within the remaining choices.
mut filtered3 := []Birthday{}
for bd in filtered2 {
if bd.day_unique_in(filtered2) {
filtered3 << bd
}
}
// Albert now knows the answer too.
// So the month must be unique within the remaining choices.
mut filtered4 := []Birthday{}
for bd in filtered3 {
if bd.month_uniquie_in(filtered3) {
filtered4 << bd
}
}
if filtered4.len == 1 {
println("Cheryl's Birthday is ${filtered4[0]}")
} else {
println("Something went wrong!")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Cheryl's birthday is July 16
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">var Months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
Line 2,689 ⟶ 3,890:
} else {
System.print("Something went wrong!")
}</langsyntaxhighlight>
 
{{out}}
Line 2,697 ⟶ 3,898:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">dates:=T(T("May", 15), T("May", 16), T("May", 19),
T("June", 17), T("June", 18),
T("July", 14), T("July", 16),
Line 2,715 ⟶ 3,916:
 
// print birthday such that muliples are shown, if any
println("Cheryl's birthday is ",theDay.flatten().flatten().concat(" "));</langsyntaxhighlight>
{{out}}
<pre>
2,123

edits