Game of replacing array elements
Last Updated :
03 Oct, 2022
There are two players A and B who are interested in playing a game of numbers. In each move a player pick two distinct number, let's say a1 and a2 and then replace all a2 by a1 or a1 by a2. They stop playing game if any one of them is unable to pick two number and the player who is unable to pick two distinct number in an array, loses the game. First player always move first and then second. Task is to find which player wins.
Examples:
Input: arr[] = { 1, 3, 3, 2, 2, 1 }
Output: Player 2 wins
Explanation:
First plays always loses irrespective of the numbers chosen by him. For example,
say first player picks ( 1 & 3) replace all 3 by 1
Now array Become { 1, 1, 1, 2, 2, 1 }
Then second player picks ( 1 & 2 )
either he replace 1 by 2 or 2 by 1
Array Become { 1, 1, 1, 1, 1, 1 }
Now first player is not able to choose.
Input: arr[] = { 1, 2, 1, 2 }
Output: Player 1 wins
From above examples, we can observe that if number of count of distinct element is even, first player always wins. Else second player wins.
Lets take an another example :
int arr[] = 1, 2, 3, 4, 5, 6
Here number of distinct element is even(n). If player 1 pick any two number lets say (4, 1), then we left with n-1 distinct element. So player second left with n-1 distinct element. This process go on until distinct element become 1. Here n = 6
Player : P1 p2 P1 p2 P1 P2
distinct : [n, n-1, n-2, n-3, n-4, n-5 ]
"At this point no distinct element left,
so p2 is unable to pick two Dis element."
Below implementation of the above idea :
C++
// CPP program for Game of Replacement
#include <bits/stdc++.h>
using namespace std;
// Function return which player win the game
int playGame(int arr[], int n)
{
// Create hash that will stores
// all distinct element
unordered_set<int> hash;
// Traverse an array element
for (int i = 0; i < n; i++)
hash.insert(arr[i]);
return (hash.size() % 2 == 0 ? 1 : 2);
}
// Driver Function
int main()
{
int arr[] = { 1, 1, 2, 2, 2, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Player " << playGame(arr, n) << " Wins" << endl;
return 0;
}
Java
// Java program for Game of Replacement
import java.util.HashSet;
public class GameOfReplacingArrayElements
{
// Function return which player win the game
public static int playGame(int arr[])
{
// Create hash that will stores
// all distinct element
HashSet<Integer> set=new HashSet<>();
// Traverse an array element
for(int i:arr)
set.add(i);
return (set.size()%2==0)?1:2;
}
public static void main(String args[]) {
int arr[] = { 1, 1, 2, 2, 2, 2 };
System.out.print("Player "+playGame(arr)+" wins");
}
}
//This code is contributed by Gaurav Tiwari
Python3
# Python program for Game of Replacement
# Function return which player win the game
def playGame(arr, n):
# Create hash that will stores
# all distinct element
s = set()
# Traverse an array element
for i in range(n):
s.add(arr[i])
return 1 if len(s) % 2 == 0 else 2
# Driver code
arr = [1, 1, 2, 2, 2, 2]
n = len(arr)
print("Player",playGame(arr, n),"Wins")
# This code is contributed by Shrikant13
C#
// C# program for Game of Replacement
using System;
using System.Collections.Generic;
public class GameOfReplacingArrayElements
{
// Function return which player win the game
public static int playGame(int []arr)
{
// Create hash that will stores
// all distinct element
HashSet<int> set = new HashSet<int>();
// Traverse an array element
foreach(int i in arr)
set.Add(i);
return (set.Count % 2 == 0) ? 1 : 2;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 1, 1, 2, 2, 2, 2 };
Console.Write("Player " + playGame(arr) + " wins");
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for Game of Replacement
// Function return which player win the game
function playGame(arr, n)
{
// Create hash that will stores
// all distinct element
var hash = new Set();
// Traverse an array element
for (var i = 0; i < n; i++)
hash.add(arr[i]);
return (hash.size % 2 == 0 ? 1 : 2);
}
// Driver Function
var arr = [1, 1, 2, 2, 2, 2];
var n = arr.length;
document.write( "Player " + playGame(arr, n) + " Wins" );
// This code is contributed by importantly.
</script>
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Replacing an element makes array elements consecutive
Given an array of positive distinct integers. We need to find the only element whose replacement with any other value makes array elements distinct consecutive. If it is not possible to make array elements consecutive, return -1. Examples : Input : arr[] = {45, 42, 46, 48, 47} Output : 42 Explanatio
8 min read
Find the winner of the Game of removing odd or replacing even array elements
Given an array arr[] consisting of N integers. Two players, Player 1 and Player 2, play turn-by-turn in which one player can may either of the following two moves: Convert even array element to any other integer.Remove odd array element. The player who is not able to make any move loses the game. Th
7 min read
Implement Arrays in different Programming Languages
Arrays are one of the basic data structures that should be learnt by every programmer. Arrays stores a collection of elements, each identified by an index or a key. They provide a way to organize and access a fixed-size sequential collection of elements of the same type. In this article, we will lea
5 min read
Minimize the sum of MEX by removing all elements of array
Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
7 min read
Modify Array by modifying adjacent equal elements
Given an array arr[] of size N of positive integers. The task is to rearrange the array after applying the conditions given below: If arr[i] and arr[i+1] are equal then multiply the ith (current) element with 2 and set the (i +1)th element to 0. After applying all the conditions move all zeros at th
7 min read
Minimize the maximum frequency of Array elements by replacing them only once
Given an array A[] of length N, the task is to minimize the maximum frequency of any array element by performing the following operation only once: Choose any random set (say S) of indices i (0 ? i ? N-1) of the array such that every element of S is the same and Replace every element of that index w
7 min read
Minimum operations to make all Array elements 0 by MEX replacement
Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read
Replace every array element by sum of previous and next
Given an array of integers, update every element with sum of previous and next elements with following exceptions. First element is replaced by sum of first and second. Last element is replaced by sum of last and second last. Examples: Input : arr[] = { 2, 3, 4, 5, 6} Output : 5 6 8 10 11 Explanatio
7 min read
Inserting Elements in an Array - Array Operations
In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as: Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element a
2 min read
Find the winner in game of rotated Array
Given a circular connected binary array X[] of length N. Considered two players A and B are playing the game on the following move: Choose a sub-array and left-rotate it once. The move is said to be valid if and only if the number of adjacent indices in X[] having different values (after rotation) i
8 min read