Thursday, September 21, 2023
HomeSoftware EngineeringLearn how to Make the Deadfish Swim in Java

Learn how to Make the Deadfish Swim in Java


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 worth
  • s squares the worth
  • o outputs the worth into the return array

Invalid characters must 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 knowledge) {
    int worth = 0;
    Record<Integer> end result = new ArrayList<>();
    for(char letter : knowledge.toCharArray()) {
      change(letter) {
        case 'i': worth++; break;
        case 'd': value--; break;
        case 's': worth *= worth; break;
        case 'o': end result.add(worth); break;
        default: throw new IllegalArgumentException("Not legitimate code letter");
      }
    }
    return end result.stream().mapToInt(Integer::intValue).toArray();
  }
}

Choice 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()) {
      change (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 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 circumstances to validate our answer

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"));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments