Skip to content

Instantly share code, notes, and snippets.

@luizrobertofreitas
Created June 28, 2025 13:20
Show Gist options
  • Select an option

  • Save luizrobertofreitas/202b55daafc974c858e31d993154f84a to your computer and use it in GitHub Desktop.

Select an option

Save luizrobertofreitas/202b55daafc974c858e31d993154f84a to your computer and use it in GitHub Desktop.

Revisions

  1. luizrobertofreitas revised this gist Jun 28, 2025. 1 changed file with 26 additions and 0 deletions.
    26 changes: 26 additions & 0 deletions Ex1Test.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    package org.javatests;

    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.params.ParameterizedTest;
    import org.junit.jupiter.params.provider.CsvSource;

    class Ex1Test {

    @ParameterizedTest
    @CsvSource({
    "OP_1 OP_2 OP_ADD,true",
    "OP_1 OP_1 OP_ADD OP_3 OP_EQUAL,false",
    "OP_3 OP_2 OP_SUB OP_1 OP_EQUAL,true",
    "OP_3 OP_2 OP_SUB OP_5 OP_ADD OP_5 OP_EQUAL,false",
    "OP_ADD,false",
    "OP_1 OP_2,true",
    "OP_0 OP_VERIFY OP_1,false",
    "OP_1 OP_VERIFY OP_2,true"

    })
    void test(String input, Boolean expected) {
    Ex1 ex = new Ex1();
    Assertions.assertEquals(expected, ex.transactions(input));
    }

    }
  2. luizrobertofreitas created this gist Jun 28, 2025.
    36 changes: 36 additions & 0 deletions Ex1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    package org.javatests;

    import java.util.Stack;

    public class Ex1 {
    public Boolean transactions(String input) {
    String[] arr = input.split(" ");

    final var stack = new Stack<Integer>();

    for (String s : arr) {
    String op = s.replace("OP_", "");
    if (op.chars().allMatch(Character::isDigit)) {
    Integer number = Integer.parseInt(op);
    stack.push(number);
    } else if (!stack.isEmpty()) {
    if (op.equals("EQUAL")) {
    if (stack.pop().equals(stack.pop())) stack.push(1);
    else stack.push(0);
    } else if (op.equals("ADD")) {
    Integer res = stack.pop() + stack.pop();
    stack.push(res);
    } else if (op.equals("SUB")) {
    Integer top = stack.pop();
    Integer second = stack.pop();
    stack.push(second - top);
    } else if (op.equals("VERIFY")) {
    if (stack.peek().equals(0)) return false;
    else stack.pop();
    }
    }
    }

    return !stack.isEmpty() && stack.pop() != 0;
    }
    }