The way to Make the Deadfish Swim in Java


The problem

Write a easy parser that can parse and run Deadfish.

Deadfish has 4 instructions, every 1 character lengthy:

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

Invalid characters ought to be ignored.

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

The answer in Java code

Choice 1:

import java.util.ArrayList;
import java.util.Record;

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

Choice 2:

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

Choice 3:

import java.util.ArrayList;

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

Take a look at circumstances to validate our resolution

import static org.junit.Assert.*;

public class ExampleTests {
    @org.junit.Take a look at
    public void exampleTests() {
        assertArrayEquals(new int[] {8, 64}, DeadFish.parse("iiisdoso"));
        assertArrayEquals(new int[] {8, 64, 3600}, DeadFish.parse("iiisdosodddddiso"));
    }
}
See also  Tips on how to Sum Consecutives in Java

Leave a Reply