can anybody solve this please? its for java netbeans A sequence of n > 0 integer
ID: 3816106 • Letter: C
Question
can anybody solve this please? its for java netbeans
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n - 1. For instance, 1 4 2 3 is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether or not each of a number of sequences is a jolly jumper. Each line of the input file contains an integer nExplanation / Answer
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class JollyJumper {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//scanner object to read from the users
StringTokenizer tokenizer;
int numItems;
while (scan.hasNext()) {//loops till we have input from the users
String str =scan.nextLine();//read the entire lines
tokenizer = new StringTokenizer(str," ");//tokenizes the string with delimineter as space(" ")
numItems = Integer.parseInt(tokenizer.nextToken());// get the first token from the numbers
int[] numbArr = new int[numItems];//create array of n number
for (int i = 0; i < numItems; i++) {
numbArr[i] = Integer.parseInt(tokenizer.nextToken());//adding to the numbArr array
}
System.out.println(isJollySeries(numbArr)+" ");//invoking the isJollySeries method
}
}
//helper method to find whether the array is jolly or not
private static String isJollySeries(int[] numbers) {
List results = new ArrayList();//creating a list of integers
for (int i = 0; i < numbers.length - 1; i++) {//iterating through the numbers
int result = Math.abs(numbers[i] - numbers[i + 1]);// getting the absolute difference
if (result == 0) {// if the diff is 0 then its not jolly
return "Not jolly";
}
if (result >= numbers.length) {// if the diff is greater than the number of numbers then its not jolly
return "Not jolly";
}
if (results.contains(result)) {// if the list contains already the diff then its not jolly
return "Not jolly";
}
results.add(result);
}
return "Jolly";//if none satisfies then the number is jolly
}
}
--------output---------
4 1 4 2 3
Jolly
5 1 4 2 -1 6
Not jolly
6 11 7 4 2 1 6
Jolly
------------output-------------
Note: Feel free to ask any question in case of any doubt. God bless you!!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.