Issue
This is an assignment. I have the following code:
#! /bin/bash
y=$1
if [ -z $1 ] # if year is not specified use the current year
then y=(`date +%Y`)
fi
for m in {1..12}; do
if [ $m -eq 12 ] # december exception
then echo $(date -d $m/1/$y +%b) - $(date -d "$(($m%12+1))/1/$y" +%A)
break
fi
echo $(date -d $m/1/$y +%b) - $(date -d "$(($m%12+1))/1/$y - 1 days" +%A) # print the last day of the week for the month
done
It lists the last day of the week for every month:
Jan - Monday
Feb - Monday
Mar - Thursday
Apr - Saturday
May - Tuesday
Jun - Thursday
Jul - Sunday
Aug - Wednesday
Sep - Friday
Oct - Monday
Nov - Wednesday
Dec - Saturday
Now I need to reverse it, so that it lists months ending on every day of the week like so:
Sunday - Jul
Monday - Jan Feb Oct
Tuesday - May
Wednesday - Aug Nov
Thursday - Mar Jun
Friday - Sep
Saturday - Apr Dec
I'm thinking of a nested loop,
for d in {1..7};
And storing months in an array?
Solution
#! /usr/bin/env bash
# if year is not specified use the current year
declare -r year="${1:-$(date +%Y)}"
# associative array (aka hash table)
declare -A months_per_day=()
for m in {01..12}; do
day_month=$(LANG=C date -d "${year}-${m}-01 +1 month -1 day" +"%A %b")
months_per_day[${day_month% *}]+=" ${day_month#* }"
done
for day in Sunday Monday Tuesday Wednesday Thursday Friday Saturday; do
echo "${day} -${months_per_day[${day}]:-}"
done
Output:
Sunday - Jul
Monday - Jan Feb Oct
Tuesday - May
Wednesday - Aug Nov
Thursday - Mar Jun
Friday - Sep
Saturday - Apr Dec
Answered By - Arnaud Valmary Answer Checked By - Katrina (WPSolving Volunteer)