Encuentre la fecha posterior al próximo medio año a partir de una fecha dada

Dado un entero positivo D y una string M que representa el día y el mes de un año bisiesto, la tarea es encontrar la fecha posterior al próximo medio año.

Ejemplos:

Entrada: D = 15, M = “Enero”
Salida: 16 de julio
Explicación: La fecha del 15 de enero al próximo medio año es el 16 de julio.

Entrada: D = 10, M = “Octubre”
Salida: 10 de abril

Enfoque: dado que un año bisiesto contiene 366 días , el problema dado se puede resolver encontrando los datos después de incrementar la fecha actual en 183 días . Siga los pasos para resolver el problema:

  • Almacene la cantidad de días de cada mes en esa array, digamos days[] .
  • Inicialice una variable, digamos curMonth como M , para almacenar el índice del mes actual.
  • Inicialice una variable, diga curDate como D , para almacenar la fecha actual.
  • Inicialice una variable, digamos contar como 183 , que representa la cuenta de días para incrementar.
  • Iterar hasta que el valor de count sea positivo y realizar los siguientes pasos:
    • Si el valor de count es positivo y curDate es como máximo el número de días en curMonth , disminuya el valor de count en 1 e incremente el valor de curDate en 1 .
    • Si el valor de count es 0 , salga del bucle .
    • Actualice el valor de curMonth por (curMonth + 1)%12 .
  • Después de completar los pasos anteriores, imprima la fecha correspondiente a curDate y curMonth como resultado.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to find the date
// after the next half-year
void getDate(int d, string m) {
 
    // Stores the number of days in the
    // months of a leap year
    int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 
    // List of months
    string month[] = {"January", "February",
             "March", "April",
             "May", "June",
             "July", "August",
             "September", "October",
             "November", "December"};
 
    // Days in half of a year
    int cnt = 183;
 
    // Index of current month
    int cur_month;
      for(int i = 0; i < 12; i++)
      if(m == month[i])
          cur_month = i;
 
    // Starting day
    int cur_date = d;
 
    while(1) {
 
        while(cnt > 0 && cur_date <= days[cur_month]) {
 
            // Decrement the value of
            // cnt by 1
            cnt -= 1;
 
            // Increment cur_date
            cur_date += 1;
        }
 
        // If cnt is equal to 0, then
        // break out of the loop
        if(cnt == 0)
            break;
 
        // Update cur_month
        cur_month = (cur_month + 1) % 12;
 
        // Update cur_date
        cur_date = 1;
    }
 
    // Print the resultant date
    cout << cur_date << " " << month[cur_month] << endl;
}
 
// Driver Code
int main() {
 
    int D = 15;
    string M = "January";
 
    // Function Call
    getDate(D, M);
       
    return 0;
}
 
// This code is contributed by Dharanendra L V.

Java

// Java program for the above approach
class GFG{
     
// Function to find the date
// after the next half-year
public static void getDate(int d, String m)
{
     
    // Stores the number of days in the
    // months of a leap year
    int[] days = { 31, 29, 31, 30, 31, 30,
                   31, 31, 30, 31, 30, 31 };
 
    // List of months
    String[] month = { "January", "February", "March",
                       "April", "May", "June", "July",
                       "August", "September", "October",
                       "November", "December" };
 
    // Days in half of a year
    int cnt = 183;
 
    // Index of current month
    int cur_month = 0;
    for(int i = 0; i < 12; i++)
        if (m == month[i])
            cur_month = i;
 
    // Starting day
    int cur_date = d;
 
    while (true)
    {
        while (cnt > 0 && cur_date <= days[cur_month])
        {
             
            // Decrement the value of
            // cnt by 1
            cnt -= 1;
 
            // Increment cur_date
            cur_date += 1;
        }
 
        // If cnt is equal to 0, then
        // break out of the loop
        if (cnt == 0)
            break;
 
        // Update cur_month
        cur_month = (cur_month + 1) % 12;
 
        // Update cur_date
        cur_date = 1;
    }
 
    // Print the resultant date
    System.out.println(cur_date + " " +
                       month[cur_month]);
}
 
// Driver Code
public static void main(String args[])
{
    int D = 15;
    String M = "January";
 
    // Function Call
    getDate(D, M);
}
}
 
// This code is contributed by SoumikMondal

Python3

# Python program for the above approach
 
# Function to find the date
# after the next half-year
def getDate(d, m):
 
    # Stores the number of days in the
    # months of a leap year
    days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 
    # List of months
    month = ['January', 'February',
             'March', 'April',
             'May', 'June',
             'July', 'August',
             'September', 'October',
             'November', 'December']
 
    # Days in half of a year
    cnt = 183
 
    # Index of current month
    cur_month = month.index(m)
 
    # Starting day
    cur_date = d
 
    while(1):
 
        while(cnt > 0 and cur_date <= days[cur_month]):
 
            # Decrement the value of
            # cnt by 1
            cnt -= 1
 
            # Increment cur_date
            cur_date += 1
 
        # If cnt is equal to 0, then
        # break out of the loop
        if(cnt == 0):
            break
 
        # Update cur_month
        cur_month = (cur_month + 1) % 12
 
        # Update cur_date
        cur_date = 1
 
    # Print the resultant date
    print(cur_date, month[cur_month])
 
 
# Driver Code
D = 15
M = "January"
 
# Function Call
getDate(D, M)

C#

// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the date
// after the next half-year
static void getDate(int d, string m)
{
     
    // Stores the number of days in the
    // months of a leap year
    int[] days = { 31, 29, 31, 30, 31, 30,
                   31, 31, 30, 31, 30, 31 };
 
    // List of months
    string[] month = { "January", "February", "March",
                       "April", "May", "June", "July",
                       "August", "September", "October",
                       "November", "December" };
 
    // Days in half of a year
    int cnt = 183;
 
    // Index of current month
    int cur_month = 0;
    for(int i = 0; i < 12; i++)
        if (m == month[i])
            cur_month = i;
 
    // Starting day
    int cur_date = d;
 
    while (true)
    {
        while (cnt > 0 && cur_date <= days[cur_month])
        {
             
            // Decrement the value of
            // cnt by 1
            cnt -= 1;
 
            // Increment cur_date
            cur_date += 1;
        }
 
        // If cnt is equal to 0, then
        // break out of the loop
        if (cnt == 0)
            break;
 
        // Update cur_month
        cur_month = (cur_month + 1) % 12;
 
        // Update cur_date
        cur_date = 1;
    }
 
    // Print the resultant date
    Console.WriteLine(cur_date + " " +
                      month[cur_month]);
}
 
// Driver Code
public static void Main()
{
    int D = 15;
    string M = "January";
 
    // Function Call
    getDate(D, M);
}
}
 
// This code is contributed by ukasp

Javascript

<script>
 
// Javascript program for the above approach
 
// Function to find the date
// after the next half-year
function getDate(d, m)
{
     
    // Stores the number of days in the
    // months of a leap year
    let days = [ 31, 29, 31, 30, 31, 30,
                 31, 31, 30, 31, 30, 31 ];
  
    // List of months
    let month = [ "January", "February", "March",
                  "April", "May", "June", "July",
                  "August", "September", "October",
                  "November", "December" ];
  
    // Days in half of a year
    let cnt = 183;
  
    // Index of current month
    let cur_month = 0;
    for(let i = 0; i < 12; i++)
        if (m == month[i])
            cur_month = i;
  
    // Starting day
    let cur_date = d;
  
    while (true)
    {
        while (cnt > 0 && cur_date <= days[cur_month])
        {
             
            // Decrement the value of
            // cnt by 1
            cnt -= 1;
  
            // Increment cur_date
            cur_date += 1;
        }
  
        // If cnt is equal to 0, then
        // break out of the loop
        if (cnt == 0)
            break;
  
        // Update cur_month
        cur_month = (cur_month + 1) % 12;
  
        // Update cur_date
        cur_date = 1;
    }
  
    // Print the resultant date
    document.write(cur_date + " " +
                   month[cur_month]);
}
 
// Driver Code
let D = 15;
let M = "January";
 
// Function Call
getDate(D, M);
 
// This code is contributed by susmitakundugoaldanga
 
</script>
Producción: 

16 July

 

Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por poulami21ghosh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *