Home > Mobile >  Need a better solution to a hackerrank challenge
Need a better solution to a hackerrank challenge

Time:06-26

So I am new to competitive programming and I have been trying to solve this challenge for the past hour or so. I'm pretty sure my solution is overly complicated so can someone give me a better solution please? My code is pretty bad so if you can pls provide me with some feedback.

The challenge

You are given the day of the week for the first day of a month (M) (e.g. 1-Monday, 2-Tuesday, 3- Wednesday ...) and a date (D). You need to find the day of the week for the date given.

Constraints: 1<=M<=7 1<=D<=31

e.g. Input: 1 30 Output: 2

My (bad) code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int find_answer_for_more_than_7_days(int start,int day){
    cout<<day%7   start - 1;
    return 0;
}
int find_answer_for_less_than_7_days(int start,int day){
    if ((start   day - 1)>7)
        cout<<start day - 8;
    else
        cout<< start   day  - 1;
    return 0;
}
int find_answer(int start, int day){
    if (day>7)
        find_answer_for_more_than_7_days(start, day);
    else if (day<7)
         find_answer_for_less_than_7_days(start,day);   
    return 0;
}


int main() {
    int m,d;
    cin>>m>>d;
    if (d!=1){
        if (d%7 == 0){
            if (m != 1)
                cout<<m-1;
            else
                cout<<7;
        }
        else{
            if (m == 1){
                    if (d>7)
                        cout<<d%7;
                    else if (d<7)
                        cout<< d;
                }
            else if (m == 7){
                if (d > 7)
                    cout<<d - 7*(d/7) - 1;
                else if (d< 7)
                    cout<< d - 1;
            }
            else{
                find_answer(m,d);
            }
            }
        }
    else
        cout<< m;
    return 0;
  }

CodePudding user response:

For a start it would help if the code would actually be correct:

int find_answer_for_more_than_7_days(int start,int day){
    cout<<day%7   start - 1;
    return 0;
}

start = 7 and day = 6 produces 12.

All those special cases in main are unlikely and costing you far more time then simply doing the general math. Just do

cout << ((m   d - 2) % 7)   1

CodePudding user response:

Maths does the work.

#include <iostream>

using namespace std;

int day_of_the_week(int M, int D){

    return (D % 7   M - 1) % 7;
}

int main(){
    cout << day_of_the_week(1, 30);
    return 0;
}
  •  Tags:  
  • c
  • Related