Skip to content
Advertisement

Given array of string contain X number of words return the same word for a given day [closed]

Background

My Objective is I am basically trying to create an end point where a user calls the get_word() function and they get back a word. The requirement is every single user that calls the get_word() function should get back the same word on a given day. No words should repeat until we have cycled through all the words.

So for example let’s assume we have a array of words.

words = ["lebron","kobe","jordan","durant","pipen"]

day 1 and users call the function get_word() they get back lebron

day 2 and users call the function get_word() they get back kobe

day 3 and users call the function get_word() they get back jordan

day 4 and users call the function get_word() they get back durant

day 5 and users call the function get_word() they get back pipen

day 6 and users call the function get_word() they get back lebron

day 7 and users call the function get_word() they get back kobe

The goal is to have list of 500 unique words and on a given day every user should get the same word back. I would also want the ability to add more words in the future.

Solution

One very naive solution i am able to think of is i can generate a dictionary with everyday of the year as a key and words as the value. The issue with this is we only have 365 days in a year so i can only store 365 words but not 500.

I appreciate any thoughts or feedback on how i can come up with a better solution here.

This problem is language agnostic hence the java and python tag.

Advertisement

Answer

You can use a combination of modulo and a static date to calculate a growing interval as an index that iterates through the list and loops back to start after it’s exhausted.

startingDate = "2022-08-25"

words = ["lebron","kobe","jordan","durant","pipen"]

// get the number of days that have passed since the starting date
currentWordIndex = getDaysSince(startingDate) % count(words)

echo words[currentWordIndex] // "lebron" on day 0, "kobe" on day 1, etc.

In this example, the words should loop every 5 days.

As you rightly pointed out, using the day of the year limits you to 365 words. Calculating the number of days since the static date helps track an ever-growing interval.

This should work in perpetuity and even allows for the word list to grow, so long as you only ever add words to the end. If a word is added somewhere in the middle, “before” the current day’s word, it will cause it to change. If you add words to the end, the current word will not change, but the loop back to the start will obviously take longer.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement