The times are UNIX timestamps from midnight (so 0-23:59:59) for the day. Notice that the closing time can be on the next day, so Sunday would wrap to monday.
What's the best way to find intersections for these times? (in golang)
Assistant
User
Give me a working code example
Assistant
You're basically dealing with intervals in the daily timeline (seconds since midnight), but with the twist that some closing times can wrap past midnight into the next day.
Problem Breakdown
Data Representation: Each day (e.g. "monday") has an array of {open, close} pairs (but possibly split, as your data shows sometimes open and close appear as separate objects, so you'll need to pair them up properly).
Wrap Around: Closing time may be less than opening time (meaning it goes past midnight), or even close time might appear on the following day (e.g. Sunday closes at 1AM Monday).
Goal: Find intersection intervals — time intervals in which both X and Y are open.
Recommended Approach
Parse & Normalize Intervals
First, parse your data into [start, end] intervals per day:
Iterate the entries day-by-day; pair open and close to generate intervals.
For intervals where close < open, it means the interval wraps over midnight, so you should break it into two parts:
You must figure out matching open/close pairs where a close can appear before open (like the first close at 3600).
Typically, data is a sequence of events, alternating open and close (your example is a bit unordered). You want to order and pair events properly. Usually, an open marks interval start, and the next close marks interval end.
In your snippet, the objects are unsorted or not paired alone. You'll probably want first to parse these into a sorted event list of {time, type} per day, then walk through counting open intervals.
Represent weekly time as linear timeline
Because intervals might wrap across days, it's best to represent the entire week as a linear timeline from second 0 of Monday to second 604,799 (7 * 86400 - 1).
For example:
Monday 0–86400 seconds
Tuesday 86400–172800 seconds
...
That simplifies wrap-around logic.
Convert all intervals of X and Y to this timeline
For each (open, close) in day D:
start = D * 86400 + open
if close < open, i.e. wrap-around:
add interval [start, (D+1) * 86400 + close]
else:
add interval [start, D * 86400 + close]
For wrap-around on Sunday (day 6), (D+1) becomes Monday (day 0 of next week), so map Sunday close time accordingly (next week wrap).
Find intersection intervals on the weekly timeline
Now you have interval lists for X and for Y on the same timeline.
Use the classic interval intersection algorithm:
Iterate through both sorted lists of intervals and find overlaps:
go
i, j := 0, 0
var intersections []Interval
for i < len(XIntervals) && j < len(YIntervals) {
a, b := XIntervals[i], YIntervals[j]
start := max(a.Start, b.Start)
end := min(a.End, b.End)
if start < end {
intersections = append(intersections, Interval{start, end})
}
if a.End < b.End {
i++
} else {
j++
}
}
The result is the list of intersections in the weekly timeline.
Map intersections back to days
Since the entire week timeline is linear seconds, map back to day + seconds in day:
go
day := intersection.Start / 86400
startInDay := intersection.Start % 86400
// same for interval.End
Sample Outline in Go
go
type Interval struct {
Start, End int // in seconds from start of week
}
// Convert day string to int (Monday=0,... Sunday=6)
var dayOrder = map[string]int{
"monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3,
"friday": 4, "saturday": 5, "sunday": 6,
}
func openClosePairs(events []map[string]int) []Interval {
/*
Parses the alternating open/close events in order to intervals.
You likely need to:
- Sort events by time (because your example is unordered)
- Pair each open with the next close
*/
}
func intervalsToWeekTimeline(day int, intervals []Interval) []Interval {
var result []Interval
for _, interval := range intervals {
start := day*86400 + interval.Start
end := day*86400 + interval.End
if interval.End < interval.Start {
// wrap around case
result = append(result, Interval{start, (day+1)*86400 + interval.End})
} else {
result = append(result, Interval{start, end})
}
}
return result
}
func intersectIntervals(a, b []Interval) []Interval {
var i, j int
var out []Interval
for i < len(a) && j < len(b) {
start := max(a[i].Start, b[j].Start)
end := min(a[i].End, b[j].End)
if start < end {
out = append(out, Interval{start, end})
}
if a[i].End < b[j].End {
i++
} else {
j++
}
}
return out
}
Important Notes:
Input normalization/pairing: The biggest challenge is pairing open and close events in your input. If possible, fix your data format so each interval is an object {open: x, close: y} instead of separate objects.
Sort events: If open/close events are in mixed order, sort by time first per day (as Unix-time seconds in day).
Wrap-around Sunday to Monday: When wrapping, Sunday intervals that close after midnight become times beyond Sunday 86400 seconds.
Edge cases: Zero-length intervals, multiple intervals per day, overlapping intervals in the same entity (should consolidate or handle correctly).
If you want a fully working code example or help with parsing your specific input, just ask!
Sure! Here's a complete self-contained Go example that:
Parses your input data structure for one entity (map[string][]map[string]int),
Pairs open and close events per day,
Converts intervals to a linear 7-day timeline (seconds from start of Monday),
Then does the same for two entities,
Computes intersections of their open hours,
And prints the intersection intervals mapped back per day with times.
Assumptions about input format
Input for each day is a slice of unordered objects containing either "open" or "close" time.
We will:
Sort the day events by time,
Pair the events in order: open followed by close, or close before open means wrap-around,
Handle wrap-around intervals properly.
go
package main
import (
"fmt"
"sort"
)
type Interval struct {
Start int // Seconds since start of week
End int
}
// For printing times nicely
func formatTime(sec int) string {
h := sec / 3600
m := (sec % 3600) / 60
s := sec % 60
return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
}
// Days mapping
var dayOrder = map[string]int{
"monday": 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6,
}
var dayNames = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
// Event struct for pairing opens and closes
type Event struct {
Time int
Type string // "open" or "close"
}
// Parse single day events into intervals for that day (0-86400)
func parseDayEvents(events []map[string]int) ([]Interval, error) {
// Extract events
parsedEvents := []Event{}
for _, e := range events {
if t, ok := e["open"]; ok {
parsedEvents = append(parsedEvents, Event{Time: t, Type: "open"})
} else if t, ok := e["close"]; ok {
parsedEvents = append(parsedEvents, Event{Time: t, Type: "close"})
} else {
return nil, fmt.Errorf("invalid event %v", e)
}
}
// Sort by time ascending
sort.Slice(parsedEvents, func(i, j int) bool {
return parsedEvents[i].Time < parsedEvents[j].Time
})
// Pair events to intervals
intervals := []Interval{}
openStack := []int{}
for _, ev := range parsedEvents {
if ev.Type == "open" {
openStack = append(openStack, ev.Time)
} else { // close
if len(openStack) == 0 {
// This close before open means wrap-around from previous day
// We treat it as an interval from 0 to ev.Time (close)
intervals = append(intervals, Interval{Start: 0, End: ev.Time})
} else {
// Pair top open
lastOpen := openStack[len(openStack)-1]
openStack = openStack[:len(openStack)-1]
if ev.Time < lastOpen {
// wrap-around interval, split into two intervals:
intervals = append(intervals, Interval{Start: lastOpen, End: 86400}) // until midnight
intervals = append(intervals, Interval{Start: 0, End: ev.Time}) // from midnight to close
} else {
intervals = append(intervals, Interval{Start: lastOpen, End: ev.Time})
}
}
}
}
// If any remaining opens (no close), assume open till midnight
for _, o := range openStack {
intervals = append(intervals, Interval{Start: o, End: 86400})
}
// Sort intervals by Start time
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})
return intervals, nil
}
// Convert per day intervals to week timeline intervals
func intervalsToWeekTimeline(day int, intervals []Interval) []Interval {
var result []Interval
for _, iv := range intervals {
start := day*86400 + iv.Start
end := day*86400 + iv.End
result = append(result, Interval{Start: start, End: end})
}
return result
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Intersect two slices of intervals (both sorted)
func intersectIntervals(a, b []Interval) []Interval {
i, j := 0, 0
var out []Interval
for i < len(a) && j < len(b) {
start := max(a[i].Start, b[j].Start)
end := min(a[i].End, b[j].End)
if start < end {
out = append(out, Interval{Start: start, End: end})
}
if a[i].End < b[j].End {
i++
} else {
j++
}
}
return out
}
// Parse full weekly schedule map (map[string][]map[string]int) into timeline intervals for the week
func parseWeeklySchedule(schedule map[string][]map[string]int) ([]Interval, error) {
var intervals []Interval
for dayName, events := range schedule {
dayIdx, ok := dayOrder[dayName]
if !ok {
return nil, fmt.Errorf("unknown day name: %s", dayName)
}
dayIntervals, err := parseDayEvents(events)
if err != nil {
return nil, fmt.Errorf("day %s: %v", dayName, err)
}
weekIntervals := intervalsToWeekTimeline(dayIdx, dayIntervals)
intervals = append(intervals, weekIntervals...)
}
// Sort all intervals by start time
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})
return intervals, nil
}
func main() {
// Your example input for two entities X and Y
X := map[string][]map[string]int{
"monday": {
{"open": 28800},
{"close": 72000},
},
"wednesday": {
{"open": 72000},
},
"thursday": {
{"close": 3600},
{"open": 28800},
{"close": 52200},
{"open": 57600},
{"close": 72000},
},
}
Y := map[string][]map[string]int{
"monday": {
{"open": 32400}, // 9:00 AM
{"close": 57600}, // 4:00 PM
},
"tuesday": {
{"open": 0},
{"close": 86400},
},
"thursday": {
{"open": 28800},
{"close": 68400},
},
}
xIntervals, err := parseWeeklySchedule(X)
if err != nil {
panic(err)
}
yIntervals, err := parseWeeklySchedule(Y)
if err != nil {
panic(err)
}
intersections := intersectIntervals(xIntervals, yIntervals)
// Output intersections in readable form
fmt.Println("Intersected open intervals for X and Y:")
for _, iv := range intersections {
day := iv.Start / 86400
startInDay := iv.Start % 86400
endInDay := iv.End % 86400
// Correct Sunday wrapping for end times past week boundary if needed
dayName := "unknown"
if day >= 0 && day < 7 {
dayName = dayNames[day]
} else if day >= 7 {
// wrap weekly
dayName = dayNames[day%7]
}
fmt.Printf("%s: %s - %s\n", dayName, formatTime(startInDay), formatTime(endInDay))
}
}
Explanation
We first parse each day into pairs of intervals, handling wrap-around on midnight by splitting intervals.
We represent each interval as seconds offset from start of Monday.
We intersect intervals from both entities on the single timeline.
Finally, we map intersected intervals back to week days and print in HH:MM:SS format.
Run it:
You can just run this as go run main.go, and it will print intersection open intervals between X and Y.
If you want me to help adapting this to your exact input format or another feature, just let me know!