Finding out the exact weekday

Okay the problem is to find out the exact weekday after adding n days to the current day. E.g if today is Monday, after adding 1000 days it will be Friday (for example).

Here is my attempt, which obviously doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string weekDay :: add(const int _days) const{
	string weekday[7]={"Sat","Sun","Mon","Tue","Wed","Thu","Fri"};

	for (int i=0; i<7; i++){
		int j=i;

		if (weekday[i]==day){
			for(int k=0; k<(_days-i); k++){
				if (j==7)
					j=0;
				j++;
			}

		}
		return weekday[j];
		break;
	}
}


Note: weekDay is a class with one private member "day" of type "string".

Here is my algorithm:
1. Compare the string day with the array of strings weekday until a match is found.

2. When a match is found after "i" number of tries, we then add 1 to an int "j" which starts at 0. This is done "n" number of times, where n = number of days to be added - i.

3. If int "j" reaches a value above 6 (since there are 7 days in a week), reset it to 0.

4. Once the addition is finished, return weekday[j] and exit out of all loops.

I think my algorithm is correct, but am having trouble applying it. Any help would be appreciated, thanks.
1. I don't see the point of the loop on line 4.
2. It can be done without any loops at all, in two lines, if you use one of the basic arithmetic operators.
Any hint of what that operator might be ? :P
1
2
3
4
5
6
7
8
9
string weekDay :: add(const int today, const int DaysFromToday)
{
    string weekday[7]={"Sat","Sun","Mon","Tue","Wed","Thu","Fri"};

    int FutureDay = DaysFromToday%7 + today;
    if (FutureDay >= 7) FutureDay -= 7;

    return weekday[FutureDay];
}


The basic operator is the "mod" operator or '%'. This returns the remainder of a division.

So 3%7 would be 3. 10%7 would also be 3.
Last edited on
Sure.
You're looking for some binary operator such that
0 ? 7 = 0
1 ? 7 = 1
2 ? 7 = 2
3 ? 7 = 3
4 ? 7 = 4
5 ? 7 = 5
6 ? 7 = 6
7 ? 7 = 0
8 ? 7 = 1
et cetera
Thanks helios and Stewbond, I think I get it now...

One thing though, how come it doesn't work with negative numbers? It doesn't work if I try to add a negative number of days, don't understand why...Thanks.

EDIT: Here is the final one, almost exactly the same as Stewbonds' code with some variation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string weekDay :: add(const int _days) const{
	string weekday[7]={"Sat","Sun","Mon","Tue","Wed","Thu","Fri"};

	int today;
	for(int i=0; i<6; i++){
	if (weekday[i]==day)
		today=i;
	}

	int FutureDay = _days%7 + today;
	if (FutureDay >= 7)
		FutureDay -= 7;

	return weekday[FutureDay];
}


Would it work if I turned the negative value into a positive one, performed % then subtracted the answer from 'today' ?
Last edited on
Nevermind, got it working :))
Topic archived. No new replies allowed.