In: Computer Science
Code with Java and no imports, Method sandwiched returns true if num is in the element before and after an element that is not equal to num
sandwiched([4,5,4,6,7,3], 4) returns true
sandwiched([2,1,2], 2) returns true
sandwiched([3,3,3], 3) returns false
sandwiched([4,5,6,4], 4) returns false
sandwiched([1,1,2,3,1,4,1], 1) returns true
@param nums Integer ArrayList
@param num integer
@return true if a single number is between elements equal to num
*/ public static boolean sandwiched(ArrayList nums, int num) {
return false;
}//end sandwiched
/** * sandwiched([4,5,4,6,7,3], 4) returns true * sandwiched([2,1,2], 2) returns true * sandwiched([3,3,3], 3) returns false * sandwiched([4,5,6,4], 4) returns false * sandwiched([1,1,2,3,1,4,1], 1) returns true * * @param nums Integer ArrayList * @param num integer * @return true if a single number is between elements equal to num */ public static boolean sandwiched(ArrayList<Integer> nums, int num) { for (int i = 0; i < nums.size() - 2; i++) { if (nums.get(i) == num && nums.get(i + 1) != num && nums.get(i + 2) == num) { return true; } } return false; }
import java.util.ArrayList; import java.util.Arrays; public class SandswitchedTest { /** * sandwiched([4,5,4,6,7,3], 4) returns true * sandwiched([2,1,2], 2) returns true * sandwiched([3,3,3], 3) returns false * sandwiched([4,5,6,4], 4) returns false * sandwiched([1,1,2,3,1,4,1], 1) returns true * * @param nums Integer ArrayList * @param num integer * @return true if a single number is between elements equal to num */ public static boolean sandwiched(ArrayList<Integer> nums, int num) { for (int i = 0; i < nums.size() - 2; i++) { if (nums.get(i) == num && nums.get(i + 1) != num && nums.get(i + 2) == num) { return true; } } return false; } public static void main(String[] args) { System.out.println(sandwiched(new ArrayList<>(Arrays.asList(4, 5, 4, 6, 7, 3)), 4)); System.out.println(sandwiched(new ArrayList<>(Arrays.asList(2, 1, 2)), 2)); System.out.println(sandwiched(new ArrayList<>(Arrays.asList(3, 3, 3)), 3)); System.out.println(sandwiched(new ArrayList<>(Arrays.asList(4, 5, 6, 4)), 4)); System.out.println(sandwiched(new ArrayList<>(Arrays.asList(1, 1, 2, 3, 1, 4, 1)), 1)); } }