The String Fight Problem in Java


The problem

After an extended battle, the rulers of Nek and Glo have determined {that a} last duel ought to determine the destiny of their nations. Every ruler will choose their finest knights and ship them into battle, one after one other. The final standing crew will win the crown.

However the knights don’t need to die for nothing, in order that they ask you, the clever technomagican, to derive which crew will win. Are you able to assist them?

Activity

You’re given two strings, s1 and s2. Each characterize a crew consisting of the characters a..z (repsenting life factors 1..26) and A..Z (representing life factors 27..52). In every spherical, the primary two contributors of each groups (aka their first characters) will duel.

The character with fewer life factors will die and get eliminated, whereas the life factors of the survivor get diminished by 2/3 (it has only one/3 of its unique worth rounded to the closest integer). The winner will nonetheless take part within the duels. If each combatants have the identical life factors, they get each eliminated.

The duels cease every time one in all each strings is empty or null worth. Except each are empty or null worth, it’s a must to return the profitable string and its remaining content material, e.g. "Winner: s1(abc)". If each are empty string or null worth, return "Draw".

Some simple instance:
  fight("a","c")      == "Winner: s2(a)"    fight("a","a")     == "Draw"
  fight("abc","ab")   == "Winner: s1(c)"    fight("ab","ab")   == "Draw"
  fight("boy","woman") == "Winner: s2(fl)"   fight("canine","cat") == "Draw"

The answer in Java code

Choice 1:

import java.util.*;
import java.util.stream.*;

public class StringCombat { 
  
    public static String fight(String s1, String s2) {
        Record<Integer> list1 = s1 != null ? toRanks(s1) : Collections.emptyList();
        Record<Integer> list2 = s2 != null ? toRanks(s2) : Collections.emptyList();

        whereas (!list1.isEmpty() && !list2.isEmpty()) {
            int i1 = list1.get(0);
            int i2 = list2.get(0);

            if (i1 > i2) {
                list2.take away(0);
                list1.set(0, Math.spherical(i1 * (1 / 3.0f)));
            } else if (i2 > i1) {
                list1.take away(0);
                list2.set(0, Math.spherical(i2 * (1 / 3.0f)));
            } else {
                list1.take away(0);
                list2.take away(0);
            }
        }

        if (list1.isEmpty() && list2.isEmpty()) {
            return "Draw";
        } else {
            String index = list2.isEmpty() ? "1" : "2";
            String relaxation = toString(list2.isEmpty() ? list1 : list2);
            return "Winner: s" + index + "(" + relaxation + ")";
        }
    }

    personal static Record<Integer> toRanks(String s) {
        return s.chars()
                .mapToObj(c -> c >= 'a' && c <= 'z' ? c - 'a' + 1 : c - 'A' + 27)
                .acquire(Collectors.toList());
    }

    personal static String toString(Record<Integer> ranks) {
        StringBuilder builder = new StringBuilder();
        ranks.forEach(i -> builder.append((char) (i >= 1 && i <= 26 ? i - 1 + 'a' : i - 27 + 'A')));

        return builder.toString();
    }
    
}

Choice 2:

public class StringCombat { 
    
 public static String fight(String s1, String s2) {
            if(s1==null)
                s1="";
            if(s2==null)
                s2="";

            if(s1.equals(s2)) return "Draw";
            String ct = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder str1 = new StringBuilder(s1), str2 = new StringBuilder(s2);

            int i = 0, j = 0, idx;
            whereas (str1.size() != 0 && str2.size() != 0) {

                if (ct.indexOf(str1.charAt(i)) > ct.indexOf(str2.charAt(j))) {
                    idx = ct.indexOf(str1.charAt(i));
                    str1.setCharAt(i, ct.charAt(Math.spherical(idx / (float) 3)));
                    str2.deleteCharAt(j);
                } else if (ct.indexOf(str1.charAt(i)) < ct.indexOf(str2.charAt(j))) {
                    idx = ct.indexOf(str2.charAt(j));
                    str2.setCharAt(j, ct.charAt(Math.spherical(idx / (float) 3)));
                    str1.deleteCharAt(i);
                } else {
                    str1.deleteCharAt(i);
                    str2.deleteCharAt(j);
                }

            }

            return str1.size() > str2.size() ? "Winner: s1(" + str1 + ")" : str1.size() == str2.size() ? "Draw" : "Winner: s2(" + str2 + ")";

    }
  
}

Choice 3:

import java.util.Record;
import java.util.stream.Collectors;

public class StringCombat {

  public static String fight(String s1, String s2) {
    if (s1 == null && s2 == null)
      return "Draw";
    if (s1 == null)
      return (s2.isEmpty()) ? "Draw" : "Winner: s2(" + s2 + ")";
    if (s2 == null)
      return (s1.isEmpty()) ? "Draw" : "Winner: s1(" + s1 + ")";
    if (s1.equals(s2))
      return "Draw";

    String life = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    Record<Character> s1c = s1.chars().mapToObj(c -> (char) c).acquire(Collectors.toList());
    Record<Character> s2c = s2.chars().mapToObj(c -> (char) c).acquire(Collectors.toList());
    whereas (s1c.measurement() > 0 && s2c.measurement() > 0) {
      int life1 = life.indexOf(s1c.get(0)) + 1;
      int life2 = life.indexOf(s2c.get(0)) + 1;
      if (life1 == life2) {
        s1c.take away(0);
        s2c.take away(0);
      } else if (life1 > life2) {
        s2c.take away(0);
        s1c.set(0, life.charAt(Math.spherical(life1 / 3f) - 1));
      } else if (life2 > life1) {
        s1c.take away(0);
        s2c.set(0, life.charAt(Math.spherical(life2 / 3f) - 1));
      }
    }

    if (s1c.isEmpty() && s2c.isEmpty())
      return "Draw";
    if (s2c.isEmpty())
      return "Winner: s1(" + s1c.stream().map(Object::toString).acquire(Collectors.becoming a member of()) + ")";
    if (s1c.isEmpty())
      return "Winner: s2(" + s2c.stream().map(Object::toString).acquire(Collectors.becoming a member of()) + ")";
    return "ERROR";
  }

}

Check instances to validate our resolution

import java.util.LinkedList;
import java.util.Record;

import org.junit.Assert;
import org.junit.Earlier than;
import org.junit.Check;

public class StringCombatTest2 {

	personal static Record<String[]> assessments = new LinkedList<>();

	@Earlier than
	public void setUp() {
		assessments.clear();
	}

	@Check
	public void shouldPassBasicTests() {
		assessments.add(new String[] { "a", "a", "Draw", "string equivalence signifies immediate draw" });
		assessments.add(new String[] { "a", "b", "Winner: s2(a)", "anticipated b to outwin a" });
		assessments.add(new String[] { "q", "b", "Winner: s1(f)", "anticipated q to outwin b" });
		assessments.add(new String[] { "canine", "cat", "Draw" });
    assessments.add(new String[] { "boy", "woman", "Winner: s2(fl)" });
		assessments.add(new String[] { "abcde", "fghij", "Winner: s2(cj)" });
		assessments.add(new String[] { "abCde", "fghij", "Winner: s1(b)" });
		assessments.add(new String[] { "iGnfQxJYy", "MlHGtsGF", "Winner: s2(ok)" });
		assessments.add(new String[] { "vyTcJSGRGZcTq", "GFyfgBkDxNvgf", "Winner: s1(f)" });
		assessments.add(new String[] { "vyTcJSGRGZcTq", "GFyfgBkDxNvgeq", "Draw" });
		executeTestBundle("fundamental assessments bundle");
	}

	/** Check execution helper */
	personal void executeTestBundle(String bundleName) {
		System.out.println("------Executing " + bundleName + "------");
		assessments.forEach(take a look at -> {
			String s1 = take a look at[0], s2 = take a look at[1], anticipated = take a look at[2], msg = take a look at.size > 3 ? take a look at[3] : "",
					precise = StringCombat.fight(s1, s2);
			Assert.assertEquals(msg, anticipated, precise);
			System.out.printf("`%s` duels towards `%s` : %spercentn", s1, s2, precise);
		});
		System.out.println("------   finish of bundle   ------");
	}

}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles