The problem
Write a easy parser that may parse and run Deadfish.
Deadfish has 4 instructions, every 1 character lengthy:
i
increments the worth (initially “)d
decrements the worths
squares the wortho
outputs the worth into the return array
Invalid characters must be ignored.
Deadfish.parse("iiisdoso") =- new int[] {8, 64};
The answer in Java code
Possibility 1:
import java.util.ArrayList;
import java.util.Listing;
public class DeadFish {
public static int[] parse(String knowledge) {
int worth = 0;
Listing<Integer> outcome = new ArrayList<>();
for(char letter : knowledge.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();
}
}
Possibility 2:
public class DeadFish {
public static int[] parse(String knowledge) {
int v = 0, i = 0, ret[] = new int[data.replaceAll("[^o]","").size()];
for (char c : knowledge.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;
}
}
Possibility 3:
import java.util.ArrayList;
interface DeadFish {
static int[] parse(String knowledge) {
int worth = 0;
var outcomes = new ArrayList<Integer>();
for (char c : knowledge.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 instances 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"));
}
}