Card flipping game in Java
Two 0-indexed integer arrays of length n are given to you, fronts and backs, with the positive integer fronts[i] printed on the front and backs[i] printed on the back of the ith card. Each card is first arranged with one number facing up and the other facing down on a table. You can turn over any number of cards.
An integer is considered valid after the cards are flipped if it is facing down on some card and not facing up on any other card.
After the cards are flipped, return the lowest good integer that can be found. Return 0 if there are no good integers.
Example 1:
Input: fronts = [1, 2, 3, 4, 5], backs = [6, 7, 8, 9, 10]
Output: 1
Example 2:
Input: fronts = [1, 2, 4, 4, 7, 8], backs = [1, 3, 4, 1, 3, 9]
Output: 2
Example 3:
Input: fronts = [1], backs = [1]
Output: 0
Implementation
The fliipgame method takes two arrays of integers, fronts and backs, as input parameters. It aims to find the minimum possible number that can be shown facing up, considering that each card has two sides (front and back). The goal is to flip some cards to minimize the number shown facing up.
- An array count is initialized to store the count of cards with the same number on both sides.
- The length of the input arrays is stored in variable n.
- The first loop iterates through each card to check if its front and back sides have the same number. If they do, increment the count for that number in the count array.
- int result initialize a variable result to the maximum possible integer value. This will be used to track the minimum possible number shown facing up.
- The second loop iterates through each card again. If the count of the number on the front side is zero, update the result to be the minimum of its current value and the front side number. Do the same for the backside.
- Return the result if no suitable number is found (i.e., the result is still the maximum value), and return 0; otherwise, return the minimum possible number.
- The main method creates an instance of the class, initializes two arrays fronts and backs, calls the fliipgame method with these arrays, and prints the result.
- In the given an example, with fronts = {1,2,4,4,7} and backs = {1,3,4,1,3}, the output of the flipgame method would be 2.
Let us try to understand using a java program
Filename: Cardflipping.java
public class Cardflipping { public static int fliipgame(int[] fronts, int[] backs) { int[] count = new int[2000]; int n = fronts.length; for (int i = 0; i < n; i++) { if (fronts[i] == backs[i]) { count[fronts[i]]++; } } int result = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (count[fronts[i]] == 0) { result = Math.min(result, fronts[i]); } if (count[backs[i]] == 0) { result = Math.min(result, backs[i]); } } return result == Integer.MAX_VALUE ? 0 : result; } public static void main(String[] args) { int fronts[] = {1,2,3,4,5}; int backs[] = {6,7,8,9,10}; int result=fliipgame(fronts,backs); System.out.println(result); } }
Output:
1