Cheryl's birthday: Difference between revisions

m
→‎{{header|11l}}: named tuples
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
m (→‎{{header|11l}}: named tuples)
 
(20 intermediate revisions by 14 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)
<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),
Line 91 ⟶ 85:
 
print()
print(‘So birthday date is ’month‘ ’day‘.’)</langsyntaxhighlight>
 
{{out}}
Line 101 ⟶ 95:
 
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 725 ⟶ 942:
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}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">oDates:= {"May" : [ 15, 16, 19]
,"Jun" : [ 17, 18]
,"Jul" : [14, 16]
Line 782 ⟶ 1,051:
else
return m " " obj.1
}</langsyntaxhighlight>
{{out}}
<pre>Jul 16</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CHERYLS_BIRTHDAY.AWK [-v debug={0|1}]
#
Line 872 ⟶ 1,141:
printf("\n\n")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 892 ⟶ 1,161:
07/16
</pre>
 
=={{header|C}}==
{{trans|C#}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
 
Line 1,020 ⟶ 1,288:
printAnswer();
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>10 remaining.
Line 1,026 ⟶ 1,294:
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 1,057 ⟶ 1,324:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,065 ⟶ 1,332:
(July, 16)
</pre>
 
=={{header|C++}}==
{{trans|Go}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 1,178 ⟶ 1,444:
 
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 1,213 ⟶ 1,478:
 
(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,255 ⟶ 1,519:
// 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,270 ⟶ 1,533:
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,302 ⟶ 1,564:
 
! 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,404 ⟶ 1,752:
fmt.Println("Something went wrong!")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,410 ⟶ 1,758:
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,486 ⟶ 1,989:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>There are 10 candidates remaining.
Line 1,493 ⟶ 1,996:
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,566 ⟶ 2,068:
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,585 ⟶ 2,086:
)
 
getDayMonth=: |:@:(' '&splitstringcut&>) NB. retrieve lists of days and months from dates
keep=: adverb def '] #~ u' NB. apply mask to filter dates
 
Line 1,595 ⟶ 2,096:
 
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,606 ⟶ 2,107:
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,623 ⟶ 2,124:
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,632 ⟶ 2,133:
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">import java.time.Month;
import java.util.Collection;
import java.util.List;
Line 1,717 ⟶ 2,218:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>There are 10 candidates remaining.
Line 1,724 ⟶ 2,225:
There are 1 candidates remaining.
Cheryl's birthday is JULY 16</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,902 ⟶ 2,402:
// 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,922 ⟶ 2,495:
 
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,979 ⟶ 2,551:
else
println("Something went wrong!")
}</langsyntaxhighlight>
 
{{output}}
Line 1,985 ⟶ 2,557:
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 2,057 ⟶ 2,628:
if count(subset) > 1 then apply(subset, invalidate) end
end)
listValidChoices()</langsyntaxhighlight>
{{out}}
<pre>Cheryl offers these ten choices:
Line 2,070 ⟶ 2,641:
3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:
July 16</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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]]</langsyntaxhighlight>
{{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 2,160 ⟶ 2,729:
 
echo ""
echo fmt"So birthday date is {month} {day}."</langsyntaxhighlight>
 
{{out}}
Line 2,169 ⟶ 2,738:
 
So birthday date is July 16</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub filter {
my($test,@dates) = @_;
my(%M,%D,@filtered);
Line 2,210 ⟶ 2,778:
 
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}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Cheryls_Birthday.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,240 ⟶ 2,807:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">choices</span>
<!--</langsyntaxhighlight>-->
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.
Line 2,250 ⟶ 2,817:
=== functional/filter ===
(this can also be found in demo\rosetta\Cheryls_Birthday.exw)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 2,296 ⟶ 2,863:
<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>
<!--</langsyntaxhighlight>-->
{{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,432 ⟶ 2,998:
 
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,467 ⟶ 3,059:
;; Albert now knows the answer too.
;; So the month must be unique within the remaining choices
[filter (unique albert)])</langsyntaxhighlight>
 
{{out}}
Line 2,473 ⟶ 3,065:
'((July 16))
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>my @dates =
{ :15day, :5month },
{ :16day, :5month },
Line 2,500 ⟶ 3,091:
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,539 ⟶ 3,129:
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,581 ⟶ 3,170:
.map { |k,v| v }
.flatten
print dates</langsyntaxhighlight>
{{out}}
<pre>10 remaining
Line 2,588 ⟶ 3,177:
["July", 16]</pre>
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
// This version is based on the Go version on Rosettacode
 
Line 2,707 ⟶ 3,296:
}
 
</syntaxhighlight>
</lang>
{{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,759 ⟶ 3,347:
printf(birthDay.format(DateTimeFormatter.ofPattern("MMMM dd")))
}
}</langsyntaxhighlight>
{{out}}
<pre>July 16</pre>
Line 2,771 ⟶ 3,359:
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<langsyntaxhighlight Scalalang="scala">object Cheryl_sBirthday extends App {
 
private val possiblerDates = Set(
Line 2,803 ⟶ 3,391:
 
println(clou3)
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func f(day, month) {
Date.parse("#{day} #{month}", "%d %B")
}
Line 2,834 ⟶ 3,421:
}.group_by{ .month }.values.first_by { .len == 1 }[0]
 
say "Cheryl's birthday is #{birthday.fullmonth} #{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,899 ⟶ 3,485:
}
 
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,965 ⟶ 3,676:
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 3,015 ⟶ 3,726:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>10 remaining.
Line 3,021 ⟶ 3,732:
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 3,073 ⟶ 3,885:
} else {
System.print("Something went wrong!")
}</langsyntaxhighlight>
 
{{out}}
Line 3,081 ⟶ 3,893:
 
=={{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 3,099 ⟶ 3,911:
 
// print birthday such that muliples are shown, if any
println("Cheryl's birthday is ",theDay.flatten().flatten().concat(" "));</langsyntaxhighlight>
{{out}}
<pre>
1,480

edits