In: Computer Science
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<Integer> nums, int num)
{
return false;
}//end sandwiched
Hi,
Hope you are doing fine. I have coded the question in java keeping all the requirements in mind. I have tested the output with all the given inputs and the result seems positive. The code has been clearly explained using comments that have been highlighted in bold.
Program:
import java.util.ArrayList;
public class Sandwich {
//method as per the question
public static boolean
sandwiched(ArrayList<Integer> nums, int num)
{
//we traverse through the
list using i
//note that we only traverse up to
size-2 elements as the elements beyond that cannot be
sandwiched
for(int
i=0;i<nums.size()-2;i++)
{
//if the
number in the list is equal to num and if it is not
nums.size()-2
if(nums.get(i)==num && i!=nums.size()-2)
{
//if the next number in list is not equal to
current number and the number next to the next number is same as
current number
if(nums.get(i)!=nums.get(i+1) &&
nums.get(i)==nums.get(i+2))
//return True
return true;
}
}
//if no numbers are
sandwiched
return false;
}//end sandwiched
//Main method is only used for
testing
public static void main(String[] args) {
// Testing the method using
the call sandwiched([1,1,2,3,1,4,1], 1). It must return true as 4
is sandwiched between 1's at the end of the list
ArrayList<Integer> test=new
ArrayList<Integer>();
test.add(1);
test.add(1);
test.add(2);
test.add(3);
test.add(1);
test.add(4);
test.add(1);
boolean result=sandwiched(test,
1);
System.out.println(result);
// Testing the method using
the call sandwiched([3,3,3], 3). It must return false as all
elements are equal
ArrayList<Integer> test1=new
ArrayList<Integer>();
test1.add(3);
test1.add(3);
test1.add(3);
result=sandwiched(test1, 3);
System.out.println(result);
}
}
Executable code snippet:
Output: