Saturday, September 30, 2023
HomeSoftware EngineeringExes and Ohs in Java

Exes and Ohs in Java


The problem

Examine to see if a string has the identical quantity of ‘x’s and ‘o’s. The strategy should return a boolean and be case insensitive. The string can include any char.

Examples enter/output:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is current ought to return true
XO("zzoo") => false

The answer in Java code

Choice 1:

import java.util.*;

public class XO {
  
  public static boolean getXO (String str) {
    
    Map<String, Integer> m = new HashMap<>();
    m.put("x", 0);
    m.put("o", 0);
    
    for (int i = 0; i < str.size(); i++){
      char c = str.charAt(i);        
      
      if (Character.toLowerCase(c)=='x')
        m.put("x", m.get("x")+1);
      
      if (Character.toLowerCase(c)=='o')
        m.put("o", m.get("o")+1);
      
    }
    
    return m.get("x")==m.get("o");
    
  }
}

Choice 2:

public class XO {
  
  public static boolean getXO (String str) {
    str = str.toLowerCase();
    return str.exchange("o","").size() == str.exchange("x","").size();
    
  }
}

Choice 3:

public class XO {
  
  public static boolean getXO (String str) {
    String xValues = str.replaceAll("[^xX]", "");
    String oValues = str.replaceAll("[^oO]", "");
    
    return xValues.size() == oValues.size();
  }
  
}

Take a look at circumstances to validate our resolution

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Take a look at
    public void testSomething1() {
      assertEquals(true, XO.getXO("xxxooo"));
    }
    
    @Take a look at
    public void testSomething2() {
      assertEquals(true, XO.getXO("xxxXooOo"));
    }
    
    @Take a look at
    public void testSomething3() {
      assertEquals(false, XO.getXO("xxx23424esdsfvxXXOOooo"));
    }
    
    @Take a look at
    public void testSomething4() {
      assertEquals(false, XO.getXO("xXxxoewrcoOoo"));
    }
    
    @Take a look at
    public void testSomething5() {
      assertEquals(false, XO.getXO("XxxxooO"));
    }
    
    @Take a look at
    public void testSomething6() {
      assertEquals(true, XO.getXO("zssddd"));
    }
    
    @Take a look at
    public void testSomething7() {
      assertEquals(false, XO.getXO("Xxxxertr34"));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments