Rock Paper Scissors CodeChef Solution

Problem -Rock Paper Scissors CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Rock Paper Scissors CodeChef Solution in C++17

#include <bits/stdc++.h>
#include <bits/extc++.h>

using namespace std;
using namespace __gnu_pbds;

#ifdef LOCAL
void dbg() { cerr << '\n'; }
template<class T, class ...U> void dbg(T a, U ...b) { cerr << a << ' ', dbg(b...); }
template<class T> void org(T l, T r) { while (l != r) cerr << *l++ << ' '; cerr << '\n'; }
#define debug(args...) (dbg("#> (" + string(#args) + ") = (", args, ")"))
#define orange(args...) ( cerr << "#> [" + string(#args) + ") = ", org(args))
#else
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#define debug(...) ((void)0)
#define orange(...) ((void)0)
#endif
template<class T> bool chmin(T &a, T b) { return b < a and (a = b, true); }
template<class T> bool chmax(T &a, T b) { return b > a and (a = b, true); }
#define all(v) (v).begin(), (v).end()
#define eb emplace_back
#define pb push_back
#define ff first
#define ss second
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef pair<long double, long double> pdd;

template<class T>
using BST = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

void solve() {
	int n;
	string str;
	cin >> n;
	cin >> str;

	vector<array<char, 3>> dp(n);
	auto go = [&](char a, char b) -> char {
		if (a == b) return a;
		if (a == 'R') return (b == 'P' ? b : a);
		if (a == 'P') return (b == 'S' ? b : a);
		if (a == 'S') return (b == 'R' ? b : a);
	};
	
	const string rps = "RPS";
	auto getid = [&](char c) -> int {
		return find(all(rps), c) - rps.begin();
	};
	string ans(n, 'R');
	for (int i = 0; i < 3; i++)
		dp[n-1][i] = go(rps[i], str[n-1]);


	ans[n-1] = str[n-1];
	for (int i = n-2; ~i; i--) {
		for (int j = 0; j < 3; j++)
			dp[i][j] = dp[i+1][getid(go(rps[j], str[i]))];
		ans[i] = dp[i+1][getid(str[i])];
	}

	cout << ans << '\n';
}

// R < P < S < R

signed main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	int T = 1;
	cin >> T;
	while (T--) solve();
	return 0;
}

/*


*/

Rock Paper Scissors CodeChef Solution in C++14

#include<bits/stdc++.h>
using namespace std;
#define N 500000
char dp[N];

int best(string s,int i,int j)
{
  if(s[i]==s[j])
  {
      return i;
  }
  else
  {
      if(s[i]=='R')
      {
          if(s[j]=='S')
          {
              return i; 
          }
      }
      if(s[i]=='S')
      {
          if(s[j]=='P')
          {
              return i; 
          }
      }
      if(s[i]=='P')
      {
          if(s[j]=='R')
          {
              return i; 
          }
      }
      return j;
  }
}


void code(string s,int i,char*win,map<char,int> &m)
{
    if(i==(s.length()-1))
    {
        win[i]=s[i];
        m[s[i]]=i;
        return;
    }
    code(s,i+1,win,m);
    int n=s.length();
    if(s[i]=='R')
    {
      if(m.find('P')!=m.end())
      {
         win[i]=win[m['P']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
     if(s[i]=='S')
    {
      if(m.find('R')!=m.end())
      {
         win[i]=win[m['R']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
     if(s[i]=='P')
    {
      if(m.find('S')!=m.end())
      {
         win[i]=win[m['S']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
    
    m[s[i]]=i;
}
int main() 
{
    int i;
    /*for(i=0;i<n;i++)
    {
        dp[i]='x';
    }*/
	int t;
	cin>>t;
	while(t--)
	{
	    int n;
	    unordered_map<char,int> m;
	    cin>>n;
	    char win[n];
	    string s;
	    cin>>s;
	    //code(s,0,win,m);
	    for(i=n-1;i>=0;i--)
	    {
	        
	  if(i==(n-1))
     {
        win[i]=s[i];
        m[s[i]]=i;
        continue;
     } 
    //code(s,i+1,win,m);
    if(s[i]=='R')
    {
      if(m.find('P')!=m.end())
      {
         win[i]=win[m['P']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
     if(s[i]=='S')
    {
      if(m.find('R')!=m.end())
      {
         win[i]=win[m['R']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
     if(s[i]=='P')
    {
      if(m.find('S')!=m.end())
      {
         win[i]=win[m['S']]; 
      }
      else
      {
      win[i]=s[i];
      }
    }
    
    m[s[i]]=i;
	        
	    }
	    for(i=0;i<n;i++)
	    {
	        cout<<win[i];
	    }
	    cout<<endl;
	}
	return 0;
}

Rock Paper Scissors CodeChef Solution in PYTH 3

# your code goes here

import sys

T = int(sys.stdin.readline())


def winningMove(a, b):
    if a == b:
        return a
    if a == 'R' and b == 'S':
        return 'R'
    if a == 'R' and b == 'P':
        return 'P'

    if a == 'P' and b == 'S':
        return 'S'
    if a == 'P' and b == 'R':
        return 'P'

    if a == 'S' and b == 'P':
        return 'S'
    if a == 'S' and b == 'R':
        return 'R'


for _ in range(T):
    N = int(sys.stdin.readline())
    Move = sys.stdin.readline()
    Moves = [i for i in Move]
    Moves = Moves[:-1]
    myList = []
    for _ in range(N + 1):
        myList.append({})
    if N == 1:
        print(Moves[0])
        continue

    result = ""

    for i in range(len(Moves)):
        temp = Moves[i]
        cat = len(Moves)
        for j in range(i + 1, len(Moves)):
            if temp in myList[j]:
                temp = myList[j][Moves[j - 1]]
                cat = j
                break
            myList[j][temp] = "HERE"
            myList[j]["HERE"] = temp
            temp = winningMove(temp, Moves[j])
        result += temp
        for j in range(i+1,cat):
            if "HERE" in myList[j]:
                myList[j][myList[j]["HERE"]] = temp
                del myList[j]["HERE"]

    print(result)

Rock Paper Scissors CodeChef Solution in C

#include <stdio.h>
#include <string.h>

char check(char a, char b){
    if ((a == 'S' && b == 'P') || (a == 'P' && b == 'S')){
        return 'S';
    }
    else if ((a == 'S' && b == 'R') || (a == 'R' && b == 'S')){
        return 'R';
    }
    else if ((a == 'R' && b == 'P') || (a == 'P' && b == 'R')){
        return 'P';
    }
    else {
        return a;
    }
}

int main(){
    int test;
    scanf("%d",&test);
    
    while (test--){
        int n;
        scanf("%d",&n);

        char a[n],b[n];
        char r[n], p[n], s[n], w;
        int i,j;

        scanf("%s",a);
        
        if (n==1){
            printf("%c\n", a[0]);
        }

        else {
            b[n-1] = a[n-1];
            for (i=n-2;i>=0;i--){
                w = check('R',a[i+1]);
                r[i] = w;
                if (i+1 < n-1){
                    if ( w == 'R'){
                        r[i] = r[i+1];
                    }
                    else if(w == 'P'){
                        r[i] = p[i+1];
                    }
                }

                w = check('S',a[i+1]);
                s[i] = w;
                if (i+1 < n-1){
                    if ( w == 'S'){
                        s[i] = s[i+1];
                    }
                    else if(w == 'R'){
                        s[i] = r[i+1];
                    }
                }

                w = check('P',a[i+1]);
                p[i] = w;
                if (i+1 < n-1){
                    if ( w == 'P'){
                        p[i] = p[i+1];
                    }
                    else if(w == 'S'){
                        p[i] = s[i+1];
                    }
                }

                if (a[i] == 'P'){
                    b[i] = p[i];
                }
                else if (a[i] == 'R'){
                    b[i] = r[i];
                }
                else if (a[i] == 'S'){
                    b[i] = s[i];
                }
            }
            for (i=0; i<n; i++){
                printf("%c",b[i]);
            }
            printf("\n");
        }
    }
    return 0;
}

Rock Paper Scissors CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner sc= new Scanner(System.in);
		String str= sc.nextLine(); 
		int num_test = Integer.valueOf(str);
		for (int i = 0; i < num_test; i++) {
		    String str1= sc.nextLine(); 
		    String str2= sc.nextLine(); 
		    String s = str2;
		    System.out.println(playGame(str2));
		}
	}
	
	
	public static String playGame (String input) {
	    Map<Integer, Character> map =new HashMap();
	    map.put(0, 'P');
	    map.put(1, 'S');
	    map.put(2, 'R');
		int n = input.length();
		if (n <= 1) {
			return input;
        }
        char[] result = new char[n];
        int k = n-1;
        int[] next = new int[3];
        next[0] = 0; //p
        next[1] = 1; //s
        next[2] = 2; //r
       // StringBuilder sb = new StringBuilder();
        result[k--] = input.charAt(n-1);
        //sb.append(input.charAt(n-1));
        for (int i = n-2; i >= 0 ; i--) {
	        int answer = 0;
	        char cur = input.charAt(i);
	        char next_char = input.charAt(i+1);
	        if ( (cur == 'P' && next_char == 'R') || (cur == 'R' && next_char == 'P')) {
		        answer = 0;
            } else if ((cur == 'S' && next_char == 'R') || (cur == 'R' && next_char == 'S')){	
                answer = 2;
            } else if ((cur == 'S' && next_char == 'P') || (cur == 'P' && next_char == 'S')) {
	            answer = 1;
            } else if((cur == 'P' && next_char == 'P') ) {
                answer = 0;
            } else if((cur == 'S' && next_char == 'S') ) {
                answer = 1;
            } else if((cur == 'R' && next_char == 'R') ) {
                answer = 2;
            }
            
            result[k--] = map.get(next[answer]);
	        //sb.append(map.get(next[answer]));
	        //P
	        if(next_char == 'P' || next_char == 'R') {
	        	next[0] = next[0];
            }
            if(next_char == 'S') {
	            next[0] = next[1];
            }

            //S 
            if(next_char == 'P' || next_char == 'S') {
		        next[1] = next[1];
            }
            if(next_char == 'R') {
		        next[1] = next[2];
            }


            //R
            if(next_char == 'P') {
		        next[2] = next[0];
            }
            if(next_char == 'S' || next_char == 'R') {
	            next[2] = next[2];
            }

        }
        /*StringBuilder result = new StringBuilder();
        for (int i=sb.length()-1; i>=0;i--) {
	        result.append(sb.charAt(i));
        }
        return result.toString();*/
        
        return new String(result);
    }

}

Rock Paper Scissors CodeChef Solution in PYPY 3

def A(a,b):
    if a==b:
        return a
    elif (a=="R" and b=="P") or (a=="P" and b=="R"):
        return "P"
    elif (a=="P" and b=="S") or (a=="S" and b=="P"):
        return "S"
    else:
        return "R"
t=int(input())
for i in range(t):
    n=int(input())
    ans=[0]*n
    a=input()
    if n==1:
        print(a[0])
    else:
        r=[0]*n
        p=[0]*n
        s=[0]*n
        ch=""
        ans[n-1]=a[n-1]
        r[n-2]=A("R",a[n-1])
        p[n-2]=A("P", a[n - 1])
        s[n-2]=A("S", a[n - 1])
        if a[n-2]=="R":
            ans[n-2]=r[n-2]
        elif a[n-2]=="P":
            ans[n-2]=p[n-2]
        elif a[n-2]=="S":
            ans[n-2]=s[n-2]
        for i in range(n-3,-1,-1):
            temp=A("R",a[i+1])
            if temp=="R":
                r[i]=r[i+1]
            elif temp=="P":
                r[i]=p[i+1]
            else:
                r[i]=s[i+1]
            temp = A("P", a[i + 1])
            if temp == "R":
                p[i] = r[i + 1]
            elif temp == "P":
                p[i] = p[i + 1]
            else:
                p[i] = s[i + 1]
            temp = A("S", a[i + 1])
            if temp == "R":
                s[i] = r[i + 1]
            elif temp == "P":
                s[i] = p[i + 1]
            else:
                s[i] = s[i + 1]
            if a[i]=="R":
                ans[i]=r[i]
            elif a[i]=="P":
                ans[i]=p[i]
            else:
                ans[i]=s[i]
        print("".join(ans))

Rock Paper Scissors CodeChef Solution in PYTH

# cook your code here

enemy = {'R':'P','P':'S','S':'R'}

for _ in range(input()):
    n = input()
    s = raw_input()
    
    last_found = {'R':-1,'S':-1,'P':-1}    
    ans = [-1]*n
    
    for i in range(n-1,-1,-1):
        if last_found[enemy[s[i]]] == -1:
            ans[i] = s[i]
        else:
            ans[i] = ans[last_found[enemy[s[i]]]]
        
        last_found[s[i]] = i
    
    print ''.join(ans)

Rock Paper Scissors CodeChef Solution in C#

using System;
using System.Linq;

public class Test
{
	public static void Main()
	{
		// your code goes here
		  string line = Console.ReadLine();
	    int t= Convert.ToInt32(line);
	    
	    while(t>0)
	    {
            line = Console.ReadLine();
            
            int n= Convert.ToInt32(line);
            line = Console.ReadLine();
            
            char[] dp=new char[line.Length];
            
            for(int i=line.Length-1;i>=0;i--)
            {
                if(i==n-1)
                {
                    dp[i]=line[i];
                }
                else
                {
                    char newch=decide(line[i],line[i+1]);
                    if(newch==line[i+1])
                    {
                        dp[i]=dp[i+1];
                    }
                    else
                    {
                        int j=i+1;
                        while(j<n-1)
                        {
                            newch=decide(newch,line[j+1]);
                            if(newch==line[j+1])
                            {
                                dp[i]=dp[j+1];
                                break;
                            }
                            
                            j++;
                        }
                        
                        if(j>=(n-1))
                        {
                            dp[i]=newch;
                        }
                        
                    }
                }
            }
            
            Console.WriteLine(new string(dp));
            
            t--;
            
	    }
	}
	
	static char decide(char ch1,char ch2)
	{
	    
	    if(ch1==ch2)
	     return ch1;
	     
	    if((ch1=='R'||ch1=='P')&&(ch2=='R'||ch2=='P'))
	    {
	        return 'P';
	    }
	    
	    if((ch1=='R'||ch1=='S')&&(ch2=='R'||ch2=='S'))
	    {
	        return 'R';
	    }
	    
	    if((ch1=='P'||ch1=='S')&&(ch2=='S'||ch2=='P'))
	    {
	        return 'S';
	    }
	    
	    
	    return ' ';
	}
}

Rock Paper Scissors CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		n := readNum(reader)
		S, _ := reader.ReadString('\n')
		res := solve(n, S)
		buf.WriteString(res)
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, S string) string {
	W := make([]byte, n)
	next := make([]int, 3)
	for i := 0; i < 3; i++ {
		next[i] = n
	}

	// 0 for R, 1 for P, 2 for S
	for i := n - 1; i >= 0; i-- {
		var x, y int
		if S[i] == 'R' {
			x = 0
			y = 1
		} else if S[i] == 'P' {
			x = 1
			y = 2
		} else {
			x = 2
			y = 0
		}
		if next[y] == n {
			// no components can beat i
			W[i] = S[i]
		} else {
			// i lose to next[y]
			W[i] = W[next[y]]
		}
		next[x] = i
	}

	return string(W)
}
Rock Paper Scissors CodeChef Solution Review:

In our experience, we suggest you solve this Rock Paper Scissors CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Rock Paper Scissors CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Rock Paper Scissors CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *