Juego de tragamonedas RGYB (color) para adivinar el color correcto para la tragamonedas correcta

Dado que tiene cuatro ranuras, y cada ranura contendrá un color rojo (R), amarillo (Y), verde (G), azul (B) respectivamente. Por ejemplo, si selecciona YGGR (la ranura 1 es amarilla, las ranuras 2 y 3 son verdes, la ranura 4 es roja). Los colores de las tragamonedas no los conoce de antemano. Va a hacer una conjetura sobre los colores. Podría, por ejemplo, adivinar YRGB. 

Cuando adivina el color correcto para el espacio correcto, obtiene un «acierto». Si adivina un color que existe pero está en el espacio equivocado, obtiene un «pseudo-acierto». cuenta como un pseudo-golpe. 

Dada una conjetura y una solución, su tarea es escribir un programa para calcular el número de aciertos y pseudo-aciertos. 

Ejemplos: 

Input: solution -> RGBY, Guess -> GGRR
Output: hit -> 1, pseudohit -> 1

Input: solution -> RGYB, Guess -> YGRR
Output: hit -> 1, pseudohit -> 2

Input: solution -> RGYB, Guess -> GGYR
Output: hit -> 2, pseudohit -> 1

Una solución simple será recorrer ambas strings simultáneamente y verificar los caracteres de ambas strings. Si ambas strings tienen el mismo carácter, entonces es un acierto y, por lo tanto, incrementa el recuento de aciertos. Si los caracteres de las strings no coinciden en una posición, entonces recorra la string de la solución nuevamente para ver si el carácter en cuestión se encuentra en alguna parte de la string de la solución o no, en caso afirmativo, incremente el conteo de pseudo-accesos. 

Complejidad de tiempo: O(N*N) , donde N es la longitud de la string.

Una solución eficiente es crear una array de frecuencias que almacene cuántas veces aparece cada carácter en la solución, excluyendo las veces en que la ranura es un «golpe». Luego, iteramos a través de adivinar para contar el número de pseudo-aciertos. 

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

C++

// CPP code to solve RGYB game
#include<iostream>
#include<string>
using namespace std;
int hits = 0;
int pseudoHits = 0;
 
// maximum no of colors are 4 RGYB
int MAX_COLORS = 4;
 
// Function to assign code to a slot
// based on the color they have
int codeOfColor(char c)
{
    switch (c)
        {
        case 'B': return 0;
            case 'G': return 1;
            case 'R': return 2;
            case 'Y': return 3;
            default:
            return -1;
        }
}
 
// Function to calculate number of hits
// and pseudo hits
void calcResult(string guess, string solution)
{
    hits = 0;
    pseudoHits = 0;
     
    if(guess.length() != solution.length())
        cout<<"Incorrect Input"<<endl;
     
    // frequency array to store how many times
    // each character occurs in solution string   
    int frequencies[MAX_COLORS] ={ 0 };
     
    // Compute hits and build frequency table
    for(int i = 0; i < guess.length() ;i++)
    {
        if(guess[i] == solution[i])
        hits++;
         
        else
        {
            // Only increment the frequency table (which
            // will be  used for pseudo-hits) if it's not
            // a hit. If it's a hit, the slot has already
            // been "used."
            int codecolor = codeOfColor(solution[i]);
            frequencies[codecolor]++;
        }
    }
    
   // Compute pseudo-hits
    for (int i = 0; i < guess.length(); i++)
        {
            int codecolor = codeOfColor(guess[i]);
             
            if (codecolor >= 0 && frequencies[codecolor] > 0
                               && guess[i] != solution[i])
            {
                pseudoHits++;
                frequencies[codecolor]--;
            }
        }
         
    cout << "hits -> " << hits << " Pseudo hits -> "
                       << pseudoHits << endl;
}
 
// Driver code to test above function
int main()
{
    string solution = "GGRR";
    string guess = "RGBY";
          
    calcResult(solution, guess);
          
    solution = "YGRR";
    guess = "RGYB";
          
    calcResult(solution, guess);
}
// This code is contributed by Sumit Ghosh

Java

// Java code to solve RGYB game
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class CalcRes
{
    static int hits = 0;
    static int pseudoHits = 0;
     
    // Function to assign code to a slot
    // based on the color they have
    static int codeOfColor(char c)
    {
        switch (c)
        {
        case 'B': return 0;
            case 'G': return 1;
            case 'R': return 2;
            case 'Y': return 3;
            default:
            return -1;
        }
    }
     
    // maximum no of colors are 4 RGYB
    static int MAX_COLORS = 4;
     
    // Function to calculate number of hits
    // and pseudo hits
    static void calcResult(String guess, String solution)
    {  
        hits = 0;
        pseudoHits = 0;
         
        if (guess.length() != solution.length())
            System.out.println("Incorrect Input");
         
        // frequency array to store how many times
        // each character occurs in solution string
        int[] frequencies = new int[MAX_COLORS];
 
        // Compute hits and build frequency table
        for (int i = 0; i < guess.length(); i++)
        {
            if (guess.charAt(i) == solution.charAt(i))
            {
                hits++;
            }
            else
            {
                /*
                   Only increment the frequency table (which will be
                   used for pseudo-hits) if it's not a hit. If it's a
                   hit, the slot has already been "used."
                */
                int codeofcolor = codeOfColor(solution.charAt(i));
                frequencies[codeofcolor]++;
            }
        }
 
        // Compute pseudo-hits
        for (int i = 0; i < guess.length(); i++)
        {
            int codeofcolor = codeOfColor(guess.charAt(i));
            if (codeofcolor >= 0 && frequencies[codeofcolor] > 0 &&
                              guess.charAt(i) != solution.charAt(i))
            {
                pseudoHits++;
                frequencies[codeofcolor]--;
            }
        }
         
        System.out.println("hits -> " + hits +
                           " Pseudo hits -> " + pseudoHits);
    }
 
 
    // Driver Code
    public static void main(String[] args)
    {  
        String solution = "GGRR";
        String guess = "RGBY";
         
        calcResult(solution, guess);
         
        solution = "YGRR";
        guess = "RGYB";
         
        calcResult(solution, guess);
    }
}

Python3

# Python code to solve RGYB game
 
hits = 0
pseudoHits = 0
  
# maximum no of colors are 4 RGYB
MAX_COLORS = 4
  
# Function to assign code to a slot
# based on the color they have
def codeOfColor(c):
    if c == 'B':
        return 0;
    else if c == 'G':
        return 1;
    else if c == 'R':
        return 2;
    else if c == 'Y':
        return 3;
    else:
        return -1;
 
# Function to calculate number of hits
# and pseudo hits
def calcResult(guess, solution):
    hits = 0
    pseudoHits = 0
    if (len(guess) != len(solution)):
        print ("Incorrect Input")
      
    # frequency array to store how many times
    # each character occurs in solution string   
    frequencies = [0 for i in range(MAX_COLORS)]
     
    # Compute hits and build frequency table
    for i in range(len(guess)):
        if (guess[i] == solution[i]):
            hits += 1
        else:
 
            # Only increment the frequency table (which
            # will be  used for pseudo-hits) if it's not
            # a hit. If it's a hit, the slot has already
            # been "used."
            codecolor = codeOfColor(solution[i])
            frequencies[codecolor] += 1
 
    # Compute pseudo-hits
    for i in range(len(guess)):
        codecolor = codeOfColor(guess[i])
        if codecolor >= 0 and frequencies[codecolor] > 0 and guess[i] != solution[i]:
                pseudoHits += 1
                frequencies[codecolor] -= 1
    print("hits -> ", hits, " Pseudo hits -> ", pseudoHits)
  
# Driver code to test above function
solution = "GGRR"
guess = "RGBY"
calcResult(solution, guess)
 
solution = "YGRR"
guess = "RGYB"
calcResult(solution, guess)
 
#This code is contributed by Sachin Bisht

C#

// C# code to solve RGYB game
using System;
 
class GFG {
     
    static int hits = 0;
    static int pseudoHits = 0;
     
    // Function to assign code to a slot
    // based on the color they have
    static int codeOfColor(char c)
    {
        switch (c)
        {
            case 'B': return 0;
            case 'G': return 1;
            case 'R': return 2;
            case 'Y': return 3;
            default: return -1;
        }
    }
     
    // maximum no of colors are 4 RGYB
    static int MAX_COLORS = 4;
     
    // Function to calculate number of hits
    // and pseudo hits
    static void calcResult(string guess, string solution)
    {
        hits = 0;
        pseudoHits = 0;
         
        if (guess.Length != solution.Length)
            Console.Write("Incorrect Input");
         
        // frequency array to store how many
        // times each character occurs in
        // solution string
        int []frequencies = new int[MAX_COLORS];
 
        // Compute hits and build frequency table
        for (int i = 0; i < guess.Length; i++)
        {
            if (guess[i] == solution[i])
            {
                hits++;
            }
            else
            {
                 
                /* Only increment the frequency table
                (which will be used for pseudo-hits)
                if it's not a hit. If it's a hit, the
                slot has already been "used." */
                int codeofcolor = codeOfColor(solution[i]);
                frequencies[codeofcolor]++;
            }
        }
 
        // Compute pseudo-hits
        for (int i = 0; i < guess.Length; i++)
        {
            int codeofcolor = codeOfColor(guess[i]);
            if (codeofcolor >= 0 &&
                        frequencies[codeofcolor] > 0 &&
                                guess[i] != solution[i])
            {
                pseudoHits++;
                frequencies[codeofcolor]--;
            }
        }
         
        Console.WriteLine("hits -> " + hits +
                     " Pseudo hits -> " + pseudoHits);
    }
 
    // Driver Code
    public static void Main()
    {
        string solution = "GGRR";
        string guess = "RGBY";
         
        calcResult(solution, guess);
         
        solution = "YGRR";
        guess = "RGYB";
         
        calcResult(solution, guess);
    }
}
 
// This code is contributed by nitin mittal.

Javascript

<script>
 
// JavaScript code to solve RGYB game
 
let hits = 0;
let pseudoHits = 0;
 
// maximum no of colors are 4 RGYB
let MAX_COLORS = 4;
 
// Function to assign code to a slot
// based on the color they have
function codeOfColor(c) {
    switch (c) {
        case 'B': return 0;
        case 'G': return 1;
        case 'R': return 2;
        case 'Y': return 3;
        default:
            return -1;
    }
}
 
// Function to calculate number of hits
// and pseudo hits
function calcResult(guess, solution) {
    hits = 0;
    pseudoHits = 0;
 
    if (guess.length != solution.length)
        document.write("Incorrect Input<br>");
 
    // frequency array to store how many times
    // each character occurs in solution string   
    let frequencies = new Array(MAX_COLORS).fill(0);
 
    // Compute hits and build frequency table
    for (let i = 0; i < guess.length; i++) {
        if (guess[i] == solution[i])
            hits++;
 
        else {
            // Only increment the frequency table (which
            // will be used for pseudo-hits) if it's not
            // a hit. If it's a hit, the slot has already
            // been "used."
            let codecolor = codeOfColor(solution[i]);
            frequencies[codecolor]++;
        }
    }
 
    // Compute pseudo-hits
    for (let i = 0; i < guess.length; i++) {
        let codecolor = codeOfColor(guess[i]);
 
        if (codecolor >= 0 && frequencies[codecolor] > 0
            && guess[i] != solution[i]) {
            pseudoHits++;
            frequencies[codecolor]--;
        }
    }
 
    document.write("hits -> " + hits + " Pseudo hits -> "
        + pseudoHits + "<br>");
}
 
// Driver code to test above function
 
let solution = "GGRR";
let guess = "RGBY";
 
calcResult(solution, guess);
 
solution = "YGRR";
guess = "RGYB";
 
calcResult(solution, guess);
 
// This code is contributed by _saurabh_jaiswal
 
</script>
Producción

hits -> 1 Pseudo hits -> 1
hits -> 1 Pseudo hits -> 2

Complejidad temporal: O(N) 
Espacio auxiliar: O(N)

Este artículo es una contribución del Sr. Somesh Awasthi . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

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 *