Cambiar la hora de un reloj a otra hora en un número mínimo de operaciones

Dadas dos horas de reloj (en formato HH:MM:SS), cambie una hora a otra en un número mínimo de operaciones. Aquí, una operación se refiere a cambiar la manecilla de hora, minuto o segundo del reloj en 1 unidad en cualquier dirección. El programa sigue todas las reglas básicas de un reloj, por ejemplo: cambiar la manecilla de segundos de 59 a 0 también hará que 1 unidad cambie para la manecilla de minutos. Pero esto será considerado como una sola operación.

Ejemplos: 

Input : original_time = "10:10:10", 
             new_time = "05:02:58" 
Output : 24
Operations = 5 + 7 + 12 = 24   

Input : original_time = "13:12:21", 
             new_time = "11:10:18"
Output : 7
Operations = 2 + 2 + 3 = 7

El tiempo en el reloj comienza a las 00:00:00 y finaliza a las 23:59:59 en un reloj de 24 horas. En primer lugar, convertimos los tiempos dados en segundos. Luego encontrar la diferencia en segundos. La diferencia se calcula de dos maneras. Uno restando directamente el menor tiempo del mayor tiempo. La otra forma es mover el tiempo mayor a 23:59:59 y luego ir al tiempo menor.
Luego encontrar las operaciones necesarias para dos diferencias.

Explicación del ejemplo 1: 

original_time = "10:10:10", 
      new_time = "05:02:58" .

original time in seconds = 10*3600 + 10*60 + 10 
                         = 36610
new time in seconds      = 5*3600 + 2*60 + 58 
                         = 18178

difference1 = 36610 - 18178 = 18432

since there are total 24 hr i.e.. 86400 seconds
in a day.
difference2 = 86400 - 36610 + 18178 = 67968

Now, to calculate operations first move hour 
hand, than minute hand and than second hand.
operations1 = 5 + 7 + 12 = 24
operations2 = 19 + 7 + 12 = 38
So, minimum of these two is answer. Hence 24 
operations.


Un punto importante a tener en cuenta es que si quedan segundos después de que el movimiento de la manecilla de la hora es mayor que 1830 o después del movimiento de la manecilla de los minutos es mayor que 30, mueva esa manecilla una vez más.

Example : To calculate operations for 118 seconds.
So for 118 seconds, hour hand will not be moved.
Moving minute hand.
118/60 = 1 (integer) (minute hand move)
118%60 = 58 (second hand move)

So, operations will be 1 + 58 = 59
But according to above statement,
1+1=2 (minute hand move)
60 - 58 = 2 (second hand move)
So, operations will be 2 + 2 = 4
Hence 4 will be taken as answer. 

C++

// C++ program to find minimum number of
// operations needed to change one clock
// time to other.Here clock is consider
// as 24 Hour clock. The time given is
// in HH:MM:SS format.
#include<bits/stdc++.h>
using namespace std;
 
// hh is HH, mm is MM and ss is SS
// in HH:MM:SS format respectively.
void readTime(string time, int &hh, int &mm, int ss)
{
    stringstream s;
 
    // c is used to read ":" in given format.
    char c;
 
    s.clear();
    s.str(time);
    s >> hh >> c >> mm >> c >> ss;
}
 
// Returns minimum number of operations required
// to convert original_time to new_time.
int findMinOperations(string original_time,
                      string new_time)
{
    int hh, mm, ss;
 
    // Here ots is the original time in
    // seconds.
    readTime(original_time, hh, mm, ss);
    int ots = 3600*hh + 60*mm + ss;
 
 
    // Here nts is the new time in
    // seconds.
    readTime(new_time, hh, mm, ss);
    int nts = 3600*hh + 60*mm + ss;
 
    // Here gre and sma is to find which
    // time is ahead and which is back
    // respectively.
    int gre = max(ots, nts);
    int sma = min(ots, nts);
 
    // diff is array containing two integers.
    // One is second's difference between gre and sma.
    // The other one is the second's difference when
    // the greater will goes up to 24 hr and than come
    // back to sma.
    int diff[2] = {gre - sma, 86400 - (gre - sma)};
 
    // ope is array containing two integers, the number
    // of operations needed to change the time
    // corresponding to two differences.
    int ope[2];
    for (int i=0; i<2; i++)
    {
        // Firstly move the hour hand as much as
        // possible.
        // This gives the number of operations
        // by hour hand.
        ope[i] = diff[i]/3600;
 
        // The seconds left after moving hour
        // hand.
        diff[i] = diff[i]%3600;
 
        // If number of seconds left are greater
        // than 1830 than move hour hand one more time
        if (diff[i] > 1830)
        {
            ope[i]++;
 
            // Now seconds left will be:
            diff[i]= 3600 - diff[i];
        }
 
        // Now move the minute hand as much as
        // possible.
        ope[i] = ope[i]+diff[i]/60;
 
        // The seconds left after moving minute
        // hand.
        diff[i] = diff[i]%60;
 
        // If number of seconds left are greater
        // than 30 than move minute hand one more time
        if (diff[i] > 30)
        {
            ope[i]++;
 
            // Now seconds left will be:
            diff[i] = 60-diff[i];
        }
        ope[i] = ope[i] + diff[i];
    }
 
    // The answer will be the minimum of operations
    // needed to cover those two differences.
    return min(ope[0], ope[1]);
}
 
// Driver code
int main()
{
    string original_time = "10:05:04" ;
    string new_time = "02:34:12";
    cout << findMinOperations(original_time, new_time);
    return 0;
}

Java

// Java program to find minimum number of
// operations needed to change one clock
// time to other.Here clock is consider
// as 24 Hour clock. The time given is
// in HH:MM:SS format.
 
import java.util.*;
import java.lang.*;
import java.io.*;
import java.lang.StringBuilder;
 
 
// Class to Store time in
// HH:MM:SS format respectively.
class ReadTime
{
    int hh;
    int mm;
    int ss;
}
 
/* Name of the class to con time */
class ChangeTime
{   
    // two object one for each original and
    // New time
     ReadTime res=new ReadTime();    
     ReadTime res1=new ReadTime();   
 
     
    // hh is HH, mm is MM and ss is SS
    // in HH:MM:SS format respectively.
     
    public  void readTime(String time, ReadTime res)
    {
        String s=time;
        String[] values = s.split(":");
         
        res.hh=Integer.parseInt(values[0].toString());
        res.mm=Integer.parseInt(values[1].toString());
        res.ss=Integer.parseInt(values[2].toString());
         
    }
     
         
    // Returns minimum number of operations required
    // to convert original_time to new_time.
    public  int findMinOperations(String original_time, String new_time)
    {
         
     
        // Here ots is the original time in
        // seconds.
        readTime(original_time, res);
        int ots = 3600*res.hh + 60*res.mm + res.ss;
     
     
        // Here nts is the new time in
        // seconds.
        readTime(new_time, res1);
        int nts = 3600*res1.hh + 60*res1.mm + res1.ss;
         
     
        // Here gre and sma is to find which
        // time is ahead and which is back
        // respectively.
        int gre = Math.max(ots, nts);
        int sma = Math.min(ots, nts);
     
        // diff is array containing two integers.
        // One is second's difference between gre and sma.
        // The other one is the second's difference when
        // the greater will goes up to 24 hr and than come
        // back to sma.
        //int diff[]=new int[5];
        gre=gre - sma;
         
        int diff[] = {gre, 86400 - gre};
     
        // ope is array containing two integers, the number
        // of operations needed to change the time
        // corresponding to two differences.
        int ope[]=new int[2];
        for (int i=0; i<2; i++)
        {
            // Firstly move the hour hand as much as
            // possible.
            // This gives the number of operations
            // by hour hand.
            ope[i] = diff[i]/3600;
     
            // The seconds left after moving hour
            // hand.
            diff[i] = diff[i]%3600;
     
            // If number of seconds left are greater
            // than 1830 than move hour hand one more time
            if (diff[i] > 1830)
            {
                ope[i]++;
     
                // Now seconds left will be:
                diff[i]= 3600 - diff[i];
            }
     
            // Now move the minute hand as much as
            // possible.
            ope[i] = ope[i]+diff[i]/60;
     
            // The seconds left after moving minute
            // hand.
            diff[i] = diff[i]%60;
     
            // If number of seconds left are greater
            // than 30 than move minute hand one more time
            if (diff[i] > 30)
            {
                ope[i]++;
     
                // Now seconds left will be:
                diff[i] = 60-diff[i];
            }
            ope[i] = ope[i] + diff[i];
        }
     
        // The answer will be the minimum of operations
        // needed to cover those two differences.
        return Math.min(ope[0], ope[1]);
    }
 
    // Driver code
    public static void main (String[] args)
    {
        String original_time = "10:05:04" ;
        String new_time = "02:34:12";
         
        ChangeTime obj=new ChangeTime();
         
        System.out.println(obj.findMinOperations(original_time, new_time));
    }
}
 
/* This Code is contributed by Mr. Somesh Awasthi */

Python3

# Python3 program to find minimum number of
# operations needed to change one clock
# time to other.Here clock is consider
# as 24 Hour clock. The time given is
# in HH:MM:SS format.
hh, mm, ss = (0, 0, 0)
 
# hh is HH, mm is MM and ss is SS
# in HH:MM:SS format respectively.
def readTime(time):
     
    global hh
    global mm
    global ss
     
    # c is used to read ":"
    # in given format.
    c = time.split(':')
    hh = int(c[0])
    mm = int(c[1])
    ss = int(c[2])
     
# Returns minimum number of operations required
# to convert original_time to new_time.
def findMinOperations(original_time, new_time):
 
    global hh
    global mm
    global ss
     
    # Here ots is the original time in
    # seconds.
    readTime(original_time)
     
    ots = 3600 * hh + 60 * mm + ss
  
    # Here nts is the new time in
    # seconds.
    readTime(new_time)
    nts = 3600 * hh + 60 * mm + ss
  
    # Here gre and sma is to find which
    # time is ahead and which is back
    # respectively.
    gre = max(ots, nts)
    sma = min(ots, nts)
  
    # diff is array containing two integers.
    # One is second's difference between gre and sma.
    # The other one is the second's difference when
    # the greater will goes up to 24 hr and than come
    # back to sma.
    diff = [gre - sma, 86400 - (gre - sma)]
  
    # ope is array containing two integers,
    # the number of operations needed to
    # change the time corresponding to
    # two differences.
    ope = [0, 0]
     
    for i in range(2):
 
        # Firstly move the hour hand as much as
        # possible.
        # This gives the number of operations
        # by hour hand.
        ope[i] = diff[i] // 3600
  
        # The seconds left after moving hour
        # hand.
        diff[i] = diff[i] % 3600
  
        # If number of seconds left are greater
        # than 1830 than move hour hand one more time
        if (diff[i] > 1830):
            ope[i] += 1
  
            # Now seconds left will be:
            diff[i] = 3600 - diff[i]
         
        # Now move the minute hand as much as
        # possible.
        ope[i] = ope[i] + diff[i] // 60
  
        # The seconds left after moving minute
        # hand.
        diff[i] = diff[i] % 60
  
        # If number of seconds left are
        # greater than 30 than move minute
        # hand one more time
        if (diff[i] > 30):
            ope[i] += 1
  
            # Now seconds left will be:
            diff[i] = 60 - diff[i]
         
        ope[i] = ope[i] + diff[i]
     
    # The answer will be the minimum of
    # operations needed to cover those
    # two differences.
    return min(ope[0], ope[1])
 
# Driver code  
if __name__=="__main__":
     
    original_time = "10:05:04"
    new_time = "02:34:12"
     
    print(findMinOperations(original_time,
                                 new_time))
     
# This code is contributed by rutvik_56

Producción: 

45


Este artículo es una contribución de Jatin Goyal . Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo usando contribuya.geeksforgeeks.org o envíe su artículo por correo a contribuya@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 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 *