I don't know what algorithm to use for the number counter

Asked 2 years ago, Updated 2 years ago, 41 views

You want to create a counter that increments the number.

I want to create a counter similar to the current status of election counting.

For example, we're going to count the number 15000.

It's not that 15000 is constantly countering, it's that the number is increasing for 24 hours.

So every seven seconds it's increasing so that it reaches 15,000 by 12:00 p.m.

Every seven seconds, the increasing number is not constant.

And one more thing, multiple people can check it out, so even if you access it from different places at different times,

Make sure that the number counter is the same.

The final number to be reached varies from day to day.

And the counter starts at 00 every day, so if you access at 9 a.m., it doesn't start at 0 but

You have to calculate the counter from 00 to 9 so that it starts.

To summarize,

1) The number increases every 7 seconds, making it take 24 hours to reach the final number.

2) The final number reached varies from day to day.

3) The number increasing every 7 seconds shall also be different.

4) The same counter should be shown even if you check in several places.

5) The counter starts at 00:00 every day.

No matter how hard I think about it, I don't know what algorithm to use.<

algorithm python

2022-09-22 08:33

1 Answers

I don't think we need to update the number every 7 seconds. If it is a web page, it would be better to update the number only whenever there is a page request from the user.

You can save the 3 values in DB like this.

(1) If the request from the user is within 7 seconds of the last request, give the same value as the previous one (2) Otherwise, you can calculate how much you need to increase per second to achieve the final target_count ( increment_per_second), and then change the number you want to display with how many seconds have passed since the last update (elapped_time).

import datetime

def user_count():
    # Please read last_count, last_update_time, and target_count from DB.
    # The values below are random values.    
    last_count = 10
    last_update_time = datetime.datetime.now().replace(hour=1)
    target_count = 10000

    elapsed_time = (datetime.datetime.now()-last_update_time).total_seconds()
    if elapsed_time <7 :
        return last_count
    increment_per_second  =(target_count-last_count)/(datetime.datetime.now().replace(hour=23,minute=59,second=59) - last_update_time).total_seconds()

    #Randomly change increment_per_second here

    #last_count and last_update_time must also be updated on db
    last_count = last_count + elapsed_time * increment_per_second
    last_update_time = datetime.datetime.now()

    return last_count

The logic of changing target_count every day has been omitted.


2022-09-22 08:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.