One-shot Programming ProblemsΒΆ

You only get one shot, do not miss your chance – Eminem, Lose Yourself


Write a boolean function called isPositive(x) that returns true if x is a number greater than 0, and false otherwise. For example:

isPositive(3.21) returns true
isPositive(-12) returns false
isPositive(0.0) returns false

Sample solution:

boolean isPositive(float x) {
  return x > 0;
}

void isPositiveTest() {
  if (isPositive(3.21) == true) {
    println("test case 1 passed");
  } else {
    println("test case 1 FAILED!");
  }

  if (isPositive(-12) == false) {
    println("test case 2 passed");
  } else {
    println("test case 2 FAILED!");
  }

  if (isPositive(0.0) == false) {
    println("test case 3 passed");
  } else {
    println("test case 3 FAILED!");
  }
}

void setup() {
  isPositiveTest();
}

Write a function called sign(x) that returns the int -1 if x is less than 0, the int 0 if x is equal to 0, and the int 1 if x is greater than 1. For example:

sign(3.21)  returns 1
sign(0.0)   returns 0
sign(-1.83) returns -1

Sample solution:

int sign(float x) {
  if (x < 0) return -1;
  if (x > 0) return 1;
  return 0;
}

void signTest() {
  println("\nsign testing ...");
  if (sign(3.21) == 1) {
    println("test case 1 passed");
  } else {
    println("test case 1 FAILED!");
  }

  if (sign(0.0) == 0) {
    println("test case 2 passed");
  } else {
    println("test case 2 FAILED!");
  }

  if (sign(-1.83) == -1) {
    println("test case 3 passed");
  } else {
    println("test case 3 FAILED!");
  }
}

Write a function called average(x, y) that returns the average of x and y. For example:

average(1.0, 2.0)  returns 1.5
average(4.0, 0.0)  returns 2.0
average(5.0, 15.0) returns 10.0

Sample solution:

float average(float x, float y) {
  return (x + y) / 2.0;
}

void averageTest() {
  println("\naverage testing ...");
  if (average(1.0, 2.0) == 1.5) {
    println("test case 1 passed");
  } else {
    println("test case 1 FAILED!");
  }

  if (average(4.0, 0.0) == 2.0) {
    println("test case 2 passed");
  } else {
    println("test case 2 FAILED!");
  }

  if (average(5.0, 15.0) == 10.0) {
    println("test case 3 passed");
  } else {
    println("test case 3 FAILED!");
  }
}