Skip to content

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};
Code language: Java (java)

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 = ; 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(); } }
Code language: Java (java)

Option 2:

public class DeadFish { public static int[] parse(String data) { int v = , i = , 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; } }
Code language: Java (java)

Option 3:

import java.util.ArrayList; interface DeadFish { static int[] parse(String data) { int value = ; 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(); } }
Code language: Java (java)

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")); } }
Code language: Java (java)

See also  Reverse the bits in an integer in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x