I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a program that uses two methods to print all the odd numbers in an array and then get the sum of the odd numbers. However, I'm getting an output that makes no sense. This is the code that I'm using:
public class ArrayMethods1 {
public static int[] printOdds(int[]arrayExample) {
int i;
String oddNum = "";
int [] newArray = new int [3];
int x = 0;
for (i = 0; i < arrayExample.length; i++) {
if (arrayExample[i] % 2 != 0) {
System.out.print(arrayExample[i] + " ");
}
}
int[] sumOfOdds = new int [1];
sumOfOdds = sumOdds(newArray);
return sumOfOdds;
}
public static int[] sumOdds(int[]arrayExample1) {
int i;
int[] oddsTotal = new int[1];
int total = 0;
for (i = 0; i < arrayExample1.length; i++) {
if (arrayExample1[i] % 2 != 0) {
total = total + arrayExample1[i];
}
}
oddsTotal[0] = total;
return oddsTotal;
}
public static void main(String[] args) {
int [] mainArray = new int [5];
mainArray[0] = 17;
mainArray[1] = 92;
mainArray[2] = 21;
mainArray[3] = 984;
mainArray[4] = 75;
printOdds(mainArray);
int [] oddSum = new int[1];
oddSum = sumOdds(mainArray);
System.out.println(oddSum);
}
}
And I'm getting this as output:
17 21 75 [I#51016012
I have absolutely no idea where that second part is coming from, so any help would be awesome. Thanks!
well you are storing the result of the sum in an array and then you print the reference of type int[], that's why you get [I#51016012. so you need to print oddSum[0].
It is not quite clear why you return int[] from the methods that just print and calculate the sum of the odd numbers.
So the code could be enhanced:
public static void printOdds(int[] arr) {
for (int n : arr) {
if (n % 2 == 1) {
System.out.print(n + " ");
}
}
System.out.println();
}
public static int sumOdds(int[] arr) {
int total = 0;
for (int n : arr) {
if (n % 2 == 1) {
total += n;
}
}
return total;
}
Also, it may be worth to use Java 8+ stream to implement both tasks in one run:
import java.util.Arrays;
public class PrintAndSumOdds {
public static void main(String [] args){
int[] arr = {17, 92, 21, 984, 75};
int sumOdds = Arrays.stream(arr) // get IntStream from the array
.filter(n -> n % 2 == 1) // filter out the odds
.peek(n -> System.out.print(n + " ")) // print them in one line
.sum(); // and count the sum (terminal operation)
System.out.println("\nTotal odds: " + sumOdds);
}
}
Output:
17 21 75
Total odds: 113
Have some loops homework to do, and need some help! Here are the 3 questions:
Us the method below to take two integers and only output numbers divisible by ten. Make the list start with the largest of the numbers.
public static void divisibleByTen( int start, int end )
The above method is the example on the HW sheet. I have no idea how to implement it. I also don't know how to start with the largest number. Right now, I don't know how to take user input into the loop, so I made an example with 10 and 100:
public class QuestionOne {
public static void main(String [] args) {
for (int i = 10; i <= 100; i += 10){
System.out.println(i + "");
}
}
}
Use the method below to output the triangle below. Assume the positive number is between 3 and 9.
public static void printLeftUpper( int num)
Desired output is this number triangle:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Here's my code so far:
public class QuestionTwo {
public static void main(String [] args) {
for(int i = 5; i >= 1; i--) {
for(int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
The third question I have ZERO idea how to start.
3. public static void sumEvens( int begin, int end )
Use the method above to take in two numbers, called begin and end, inclusive, checks if the numbers between them are even. Include the numbers in the sum if they are even as well, and print out the sum of all such numbers.
Example: sumEven(16, 11) uses 16+14+12 = 42, and outputs "For numbers between 16 and 11, the sum of all even numbers is 42."
The help is GREATLY appreciated. Thanks so much!!
Who likes homework? I've taken the liberty of doing Question 3, hope that helps!
import java.util.List;
import java.util.ArrayList;
public class OddEven {
public static void main(String[] args) {
sumEvens(0,1000);
}
// Gets sum of odd and even numbers between a given range:
public static void sumEvens(int begin, int end)
{
List<Integer> evenNumbers = new ArrayList<Integer>();
List<Integer> oddNumbers = new ArrayList<Integer>();
if (begin < end)
{
for (int i = begin; i <= end; i++)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
else
{
for (int i = begin; i >= end; i--)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
// Calculate even values:
int evenSum = 0;
for (int i: evenNumbers) {
evenSum += i;
}
System.out.println("The sum of all even numbers is: " + evenSum);
// Calculate odd values:
int oddSum = 0;
for (int i: oddNumbers) {
oddSum += i;
}
System.out.println("The sum of all odd numbers is: " + oddSum);
}
}
public class QuestionOne {
public static void main(String [] args) {
divisibleByTen( 1, 100 );
}
public static void divisibleByTen( int start, int end ){
// reversal big to small (100 to 1)
for(int i = end; i >= start; i--){
// use mod (%) to check if i is divisible by 10
if( i%10 == 0 ){
// it is then output
System.out.println(i);
}
}
}
}
Question 2 is correct.
Question 3
public static void main(String [] args) {
sumEvens( 16, 10);
}
public static void sumEvens( int begin, int end ){
int start = 0;
int last = end;
int sum = 0;
if(begin > end){
start = end;
end = begin;
}else{
start = begin;
}
for(int i = start; i <= end; i++){
// get even integers
if(i%2 == 0){
sum += i;
}
}
System.out.println("For numbers between " +begin+ " and " +last+ ", the sum of all even numbers is " +sum);
}
I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).
I was given an assignment that made me create 3 methods that created an array, print an array, and count all the numbers divisible by 10 in a array. The part that is giving me the most trouble is counting the numbers divisible by 10. the is the code I have so far:
public int[] createArray(int size) {
Random rnd = new Random();
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = rnd.nextInt(101);
}
return array;
}
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10");
}
public int divideByTen(int num) {
int count = 0;
if (num % 10 == 0) {
count++;
}
return count;
}
public static void main(String[] args) {
Journal5a call = new Journal5a();
Random rnd = new Random();
call.printArray();
}
Pass an array to the method, and use that for determining the count. Your algorithm looks reasonable. Something like,
public int divideByTen(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 10 == 0) {
count++;
}
}
return count;
}
or, in Java 8+, use an IntStream and filter like
return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();
Then you can call it like
System.out.println("There are " + call.divideByTen(myArray)
+ " numbers that are divisible by 10");
or with printf and inline like
System.out.printf("There are %d numbers that are divisible by 10.%n",
IntStream.of(nums).filter(x -> x % 10 == 0).count());
You can do it this way. Pass full array and then check for division by 10. Skipped other part for simplicity.
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
divideByTen(myArray);
}
public int divideByTen(int[] num) {
int count = 0;
for(i=0;i<num.length;i++)
{
if (num[i] % 10 == 0) {
count++;
}
}
return count;
}
I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62