Open In App

RGYB(color) Slots Game to guess the correct color for the correct slot

Last Updated : 17 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given that you have four slots, and each slot will contain a color red (R), yellow (Y), green (G), blue (B) respectively. For example, if you select YGGR (Slot-1 is yellow, Slots-2 and -3 are green, Slot -4 is red). The colors of slots are not known to you beforehand. You will make a guess about the colors. You might, for example, guess YRGB. 

When you guess the correct color for the correct slot, you get a “hit” If you guess a color that exists but is in the wrong slot, you get a “pseudo-hit:’ Note that a slot that is a hit can never count as a pseudo-hit. 

Given a guess and a solution, your task is to write a program to calculate the number of hits and pseudo-hits. 

Examples: 

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

A simple solution will be to traverse both strings simultaneously and check the characters of both strings. If both strings have same character then it is a hit and thus increment the count of hits. If the characters of strings do not match at a position, then traverse the solution string again to see if the character in guess is occurred anywhere in solution string or not, if yes increment count of pseudo hits. 

Time Complexity: O(N*N) , where N is the length of string.

An efficient solution is to create a frequency array which stores how many times each character occurs in solution, excluding times when the slot is a “hit”. Then, we iterate through guess to count the number of pseudo-hits. 

Below is the implementation of above approach: 

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;
    elif c == 'G':
        return 1;
    elif c == 'R':
        return 2;
    elif 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>


Output

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

Time Complexity: O(N) 
Auxiliary Space: O(N)

This article is contributed by Mr. Somesh Awasthi.  



Similar Reads

Task Allocation to Game Slots
Given an array of n tasks, each represented by two arrays: start_time and duration. The start_time array represents the start time of each task, and the duration array represents the duration of each task. Your goal is to design an allocation strategy for these tasks to maximize their chances of being processed. The tasks need to be assigned to ava
10 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
Minimum time slots to convert time T1 to T2
Given two strings T1 and T2 representing two time instances in 24-hour formats, the task is to convert T1 to T2 using a minimum number of time slots among 1, 5, 15, or 60 minutes. 24-hour times are formatted as "HH: MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Examples
7 min read
Minimum time required to fill given N slots
Given an integer N which denotes the number of slots, and an array arr[] consisting of K integers in the range [1, N] . Each element of the array are in the range [1, N] which represents the indices of the filled slots. At each unit of time, the index with filled slot fills the adjacent empty slots. The task is to find the minimum time taken to fil
13 min read
Number of moves required to guess a permutation.
Given an integer N and there is a hidden permutation (of numbers from 1 to N, each occurring exactly once) that you need to guess. You can do the following: Choose a number at 1st position: If it is correct, you guess the next position.If it is wrong, the whole permutation resets and you go back to guessing the first position. You can perform trial
4 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Article Tags :
Practice Tags :