Challenge of purchases with 4 and 7

1

You have a list of computer brands and their price. You need to determine if the price of each brand has the same number of "4" s and "7" s. If this happens, then the name of the brand is returned. Otherwise, "-1" is returned. If there are two or more brands that meet the same condition, you must select the one with the lowest price.

Example:

LENOVO
4747
MAC
48657

Both comply with the condition, but LENOVO is returned because it is of lower price.

Entry: An integer n representing the number of brands to be evaluated, and n brands with their respective prices

Solution attempt:

#include <iostream>
#include <string>
#include <cstring> 
#include <conio.h>
#include <stdio.h>

using namespace std;
int n,i;
int main(){
  cin>>n;
   for(i=0;i<n;i++){
    int contador1=0;
    int contador2=0;
    string m;
    string a;
    cin>>m;
    cin>>a;
    int b = a.length();
    char _a[b]; 
    strcpy(_a, a.c_str());


    for (int k=0; k<b;k++){
        if (_a[k]=='4'){
            contador1++;
        }
        else if (_a[k]=='7'){
            contador2++;
        }
    }

    if (contador1!=0 && contador2!=0 && contador1==contador2){
        cout<<m<<endl;
    }
    else{
        cout<<-1<<endl;
    }
}

return 0;
}

The code works well if it's just a brand, but if it's more than one I do not know what to do to compare them in case more than one complies with the condition. How do I assign individuality to each brand to use this code and finally compare them?

    
asked by Jsanabria 24.10.2018 в 05:33
source

1 answer

1

For each computer you need to store 2 values:

  • name,
  • price

Well, when you read a new pair of values you compare it with what you currently consider optimal and then you stay with only one pair of values, discarding the other. So you only need to store 2 pairs of values.

On the other hand, I almost prefer to store the number as an integer. This simplifies comparisons and has a more natural use, although it slightly complicates the process of calculating the number of 4s and 7s.

#include <limits>

struct Computador
{
  std::string marca;
  int precio;
};

int main()
{
  Computador elegido = { "", std::numeric_limits<int>::max() };
  int n;
  std::cin >> n;
  while( n-- )
  {
    // Paso 1: leemos un item
    Computador propuesta;
    std::cin >> propuesta.marca >> propuesta.precio;

    // Paso 2: Comprobamos si cumple N(4) == N(7)
    int n4 = 0, n7 = 0;
    int precio = propuesta.precio;
    while( precio != 0 )
    {
      int digito = precio % 10;
      precio /= 10;

      n4 += (digito == 4);
      n7 += (digito == 7);
    }

    if( n4 == n7 )
    {
      // Paso 3: nos quedamos con el precio más bajo
      if( elegido.precio > propuesta.precio )
        elegido = propuesta;
    }
  }

  if( elegido.marca.empty() ) // Si no hay propuesta
    std::cout << -1;
  else
    std::cout << elegido.marca;
}
    
answered by 24.10.2018 в 07:08