How to Make the Deadfish Swim in Java


The challenge

Write a simple parser that will parse and run Deadfish.

Deadfish has 4 commands, each 1 character long:

  • i increments the value (initially ``)
  • d decrements the value
  • s squares the value
  • o outputs the value into the return array

Invalid characters should be ignored.

Deadfish.parse("iiisdoso") =- new int[] {8, 64};

The solution in Java code

Option 1:

import java.util.ArrayList;
import java.util.List;

public class DeadFish {
  public static int[] parse(String data) {
    int value = 0;
    List<Integer> result = new ArrayList<>();
    for(char letter : data.toCharArray()) {
      switch(letter) {
        case 'i': value++; break;
        case 'd': value--; break;
        case 's': value *= value; break;
        case 'o': result.add(value); break;
        default: throw new IllegalArgumentException("Not valid code letter");
      }
    }
    return result.stream().mapToInt(Integer::intValue).toArray();
  }
}

Option 2:

public class DeadFish {
  public static int[] parse(String data) {
    int v = 0, i = 0, ret[] = new int[data.replaceAll("[^o]","").length()]; 
    for (char c : data.toCharArray()) {
      switch (c) {
        case 'i' : v++;        break;
        case 'd' : v--;        break;
        case 's' : v=v*v;      break;
        case 'o' : ret[i++]=v; break;
      }
    }
    return ret;
  }
}

Option 3:

import java.util.ArrayList;

interface DeadFish {
  static int[] parse(String data) {
    int value = 0;
    var results = new ArrayList<Integer>();
    for (char c : data.toCharArray()) {
      if (c == 'i') value++;
      if (c == 'd') value--;
      if (c == 's') value *= value;
      if (c == 'o') results.add(value);
    }
    return results.stream().mapToInt(i -> i).toArray();
  }
}

Test cases to validate our solution

import static org.junit.Assert.*;

public class ExampleTests {
    @org.junit.Test
    public void exampleTests() {
        assertArrayEquals(new int[] {8, 64}, DeadFish.parse("iiisdoso"));
        assertArrayEquals(new int[] {8, 64, 3600}, DeadFish.parse("iiisdosodddddiso"));
    }
}