How to resolve the algorithm Last Friday of each month step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Last Friday of each month step by step in the Swift programming language

Table of Contents

Problem Statement

Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Last Friday of each month step by step in the Swift programming language

Source code in the swift programming language

import Foundation

func lastFridays(of year: Int) -> [Date] {
	
	let calendar = Calendar.current
	var dates = [Date]()
	
	for month in 2...13 {
		
		let lastDayOfMonth = DateComponents(calendar: calendar,
		                                    year: year,
		                                    month: month,
		                                    day: 0,
		                                    hour: 12)
		
		let date = calendar.date(from: lastDayOfMonth)!
		
		let isFriday = calendar.component(.weekday, from: date) == 6
		
		if isFriday {
			
			dates.append(calendar.date(from: lastDayOfMonth)!)
			
		} else {
			
			let lastWeekofMonth = calendar.ordinality(of: .weekOfMonth,
			                                          in: .month,
			                                          for: date)!
			
			let lastWithFriday = lastWeekofMonth - (calendar.component(.weekday, from: date) > 6 ? 0 : 1)
			
			let lastFridayOfMonth = DateComponents(calendar: calendar,
			                                       year: year,
			                                       month: month - 1,
			                                       hour: 12,
			                                       weekday: 6,
			                                       weekOfMonth: lastWithFriday)
			
			dates.append(calendar.date(from: lastFridayOfMonth)!)
		}
	}
	return dates
}

var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short

print(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))


  

You may also check:How to resolve the algorithm Function definition step by step in the Modula-3 programming language
You may also check:How to resolve the algorithm Morse code step by step in the Befunge programming language
You may also check:How to resolve the algorithm Range extraction step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Find the missing permutation step by step in the Quackery programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the Go programming language