Find Lowest, Highest, Median and Average Score using findKth - java

For this program, my goal is to...
Find the Highest, Lowest, Median and Average Score by using findKth
The user must input the numbers (Enter -1 to stop scanner) and they do not know how many there are and if they are sorted
However, I am seeing some issue with trying to do this.
The findKth method I am provided only takes in an int[]arr, and I cannot find a way to initialize an array to the specific size need for this project.
Could someone suggest a way to to do this?
Below are my test methods and my findKth
import java.util.*;
public class Statistics
{
public static void main(String[]args)
{
System.out.print("Enter Scores, -1 to end: ");
Scanner keyboard= new Scanner(System.in);
String numbers = null;
while(keyboard.nextInt()!=-1)
{
numbers= keyboard.next();
}
String[] parts = numbers.split(" ");
int[] n1 = new int[parts.length];
for(int n = 0; n < parts.length; n++)
{
n1[n] = Integer.parseInt(parts[n]);
}
int highest= n1.length-1;
int lowest=0;
int median= n1.length/2;
QuickSort.findKth(n1, highest);
System.out.println("High: "+n1[highest]);
QuickSort.findKth(n1, lowest);
System.out.println("Low: "+n1[lowest]);
QuickSort.findKth(n1, median);
System.out.println("Median: "+n1[median]);
}
}
public static void findKth(int[] arr, int k)
{
findKth(arr, 0, arr.length, k);
}
//Pre: arr[first]..arr[last-1] contain integers
// k must be in [first..last-1]
//Post: The elements in arr has been rearranged in such a way that arr[k] now contains the kth
// largest element
public static void findKth(int[] arr, int first, int last, int k)
{
int pivotLoc = rearrange(arr, first, last);
if (pivotLoc==k) return;
else if (pivotLoc>k) findKth(arr, first, pivotLoc, k);
else findKth (arr, pivotLoc +1, last, k);
}
I've tried different methods such as trying to parse the string for the numbers however I cannot do this as i cannot find a way to properly stop the scanner when the user inputs -1.
Also i have tried using ArrayList, but findKth with ONLY take an int[]arr. So this will not work.
Suggestions? I am stumped.

Use a List to collect the input:
List<Integer> input = new ArrayList<>();
input.add(n); // add each number
Then to convert to an array after all input:
int[] array = input.stream().mapToInt(Integer::intValue).toArray();
Your input loop is buggy. Although out of scope of the question, try a simpler loop, for example:
while (true) {
int n = keyboard.nextInt();
if (n == -1)
break;
input.add(n);
}

Related

Having trouble in printing the largest array number from the 20 randomly generated numbers

Ok so I been working on this assignment all day for the past 3 days but I haven't had any luck. I wasn't going to ask for help but I finally gave up. But there is also one more thing I need to implement to the code. This is what I gotta implement "Find the length of the longest continuous series of positive numbers in the array data. If the contents were: 4 5 0 2 . . . -1 88 78 66 -6. The length would be 3. For this problem, 0 is considered non-negative but not positive". Plus I have an issue where I can't print the largest int in the array of 20.
import java.util.Random;
import java.util.ArrayList;
public class arrayops {
public static int findLargest(ArrayList<Integer> nums) {
int greatestnum = nums.get(0);
for (Integer item : nums) {
if (item > greatestnum) {
greatestnum = item;
}
}
return greatestnum;
}
public static int randomData(ArrayList<Integer> nums) {
int[] array = new int [20];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = -100 + random.nextInt(201);
}
return -100 + random.nextInt(201);
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(4);
nums.add(13);
nums.add(43);
nums.add(-25);
nums.add(17);
nums.add(22);
nums.add(-37);
nums.add(29);
System.out.println("The Greatest Number from the hardcoded numbers " + findLargest(nums));
System.out.println("The Greatest number from the random numbers " + randomData(nums));
}
}
The findLargest method:
public static int findLargest(ArrayList<Integer> nums) {
int greatestnum = 0;
int greatestLen = 0;
for (Integer item : nums) {
if (item > 0) {
greatestLen++ ;
if(greatestLen > greatestnum)
greatestnum = greatestLen;
}
else
greatestLen = 0;
}
return greatestnum;
}
Logic used:
Keep the length of the longest chain encountered, and the length of current chain, in two separate variables (greatestnum and greatestLen respectively)
Increment greatestLen every time a positive number is encountered. If the number if less than or equal to zero, reset this count.
If the length of current chain is greater than the previous longest chain, sent the longest chain size to current chain size.
The problem is you created a list with random numbers but never put that list into the findLargest method. You also never created a method to find the consecutive positive numbers. If you didn't know how to go about coding it, I recommend drawing out an algorithm on paper.
Largest value in ArrayList...
public static int findL(ArrayList<Integer> nums)
{
int top = nums.get(0);
for(int i = 0; i<nums.size(); i++)
{
if(nums.get(i)>top)
{
top = nums.get(i);
}
}
return top;
}
Largest number of consecutive positives...
public static int positiveString(ArrayList<Integer> nums)
{
int longest = 0;
int count = 0;
for(int i = 0; i<nums.size(); i++)
{
if(nums.get(i) > 0)
{
count++;
}
else
{
if(longest<count)
{
longest = count;
}
count = 0;
}
}
return longest;
}
If you want to arrange the numbers into order you can simply use java.util.TreeSet. Then use the method last() to get the largest number.
public static int findLargest(ArrayList<Integer> nums) {
return new TreeSet<Integer>(nums).last();
}

Recursion method in Java providing incorrect output

I am working on a program that will take five numbers from a user then using recursion will provide the user with the sum of those numbers. My program appeared to be working at first however in my testing I am finding that it is just taking the first number entered by the user and basically multiplying it by five rather than taking the different numbers and finding the sum. Where am I going wrong with this? Like I said I am not getting any errors however it is not taking the additional four numbers and calculating the sum of the five numbers. Any help is always appreciated thank you.
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class sumRecusion2 {
static int i;
static int N = 5;
static int[] userNum= new int[N];
public static int sumUser(int newArray[]) {
int n = newArray.length;
if (n == 0)
return 0;
int ans = newArray[0]+sumUser(Arrays.copyOf(newArray, n-1));
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scnr = new Scanner(System.in);
try {
for(i = 0; i<=userNum.length-1; i++) {
System.out.println("Please enter a number: ");
userNum[i]= scnr.nextInt();
}}
catch(InputMismatchException ex) {
System.out.println("Please enter an integer without a decimal point!");
}
System.out.println("The sum of your numbers is: "+ sumUser(userNum));
}
}
Arrays.copyOf(newArray, n - 1) is just trimming of the last element from the array, meaning you are just summing the first element n times.
I would consider using Arrays.copyOfRange(newArray, 1, n) instead, which will make a copy of the array starting from the second element (trimming of the first element)
I, personally, might be tempted to pass in the array AND the index of the element to be summed, which would be more efficient then making n number of copies of the array...
static int i;
static int N = 5;
static int[] userNum = new int[N];
public static int sumUser(int newArray[], int index) {
if (index >= newArray.length) {
return 0;
}
int ans = newArray[index] + sumUser(newArray, index + 1);
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
userNum = new int[] {1, 2, 3, 4, 5};
System.out.println("The sum of your numbers is: " + sumUser(userNum, 0));
}
But, your requirements might differ

How to add 2 For-Each Loops to the below code?

I need to write a program that takes 10 floating-point numbers as inputs.
The program should display the average of the numbers followed by all of the numbers that are greater than the average.
Part of my requirements include writing a method that takes an array of doubles as a parameter and returns the average of the data in the array, and I am required to use at least 2 for-each loops in this program, and am not sure where to place them. The program works perfectly now, it just needs to have two for each loops added.
Here is what I have so far.
public class Floats {
public Floats() {
}
public static void main(String[] args) {
int count = 0, ct = 0, inc = 0, avc = 0, ac = 0, incre = 0, greaterCount = 0;
double sum = 0, average = 0, number = 0;
Scanner reader = new Scanner(System.in);
double[] array = new double[10];
double[] averageArray = new double[1];
double[] greaterArray = new double[10];
//inputs and appends to an array
while (count < array.length) {
System.out.print("Enter a number: ");
number = reader.nextInt();
array[count] = number;
sum = sum + number;
count++;
}
average = sum / count;
//counts
while (inc < array.length) {
if (array[inc] > average) {
greaterArray[inc] = array[inc];
incre++;
}
inc++;
}
//prints all numbers
System.out.println("All of the numbers entered: ");
while (avc < array.length) {
System.out.print(array[avc] + "," + " ");
avc++;
}
//average displayed
averageArray[0] = average;
System.out.println("");
System.out.println("The average of all numbers entered: ");
System.out.println(averageArray[0]);
//larger than average
System.out.println("Numbers greater than the average: ");
while (ac < inc) {
if (greaterArray[ac] != 0) {
System.out.println(greaterArray[ac]);
}
ac++;
}
}
}
Thanks for the help in advance! Let me know if you have any questions!!
I don't want to do your homework for you, but I will try to give a helpful recommendation. The Arrays.asList(array) method returns a list that can easily be used as the source of a for-each loop.
Since it was pointed out that a for-each loop can be used on an array and a collection that implements Iterable, my answer above isn't necessary. With that in mind, I'll provide some example code:
String[] array = new String[] {"Test", "String", "Array"};
for (String string : array) {
}
Print all the numbers in double[] array.
for (double d : array) {
System.out.print(d + ", ");
}
Print all the numbers in array greater than average
for (double d : array) {
if (d > average) {
System.out.println(d);
}
}

Summing two arrays by element, issue with carrying the 1

So I've gotten these two arrays to add properly when there is no need to carry anything. so a[0,1,1] + b[0,1,1] will give me c[0,0,2,2], but if I similarly do a[0,9,9] + b[0,9,9] I only get c[0, 0, 8, 8]. The loop in method addBigInts doesn't seem to work the way I thought it would. Any thoughts are appreciated.
import java.util.*;
public class AddBigInts {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//init firstNum array
int[] firstNum = new int[getDigit()];
System.out.println("First number:");
//gets input to pop array
firstNum = getInt(firstNum);
//second array is same length
int[] secondNum = new int[firstNum.length];
System.out.println("Second number:");
//pop second array
secondNum = getInt(secondNum);
System.out.println(Arrays.toString(firstNum));
System.out.println(Arrays.toString(secondNum));
addBigInts(firstNum, secondNum);
}
//creates array that is one place bigger than entered #
public static int getDigit (){
Scanner console = new Scanner(System.in);
System.out.print("How many digits? ");
int arraySize = console.nextInt();
return arraySize + 1;
}
//populates array
public static int[] getInt (int[] num){
Scanner console = new Scanner(System.in);
for (int i=num.length-1; i>0; i--){
System.out.print("Digit " + i + ": ");
num[i] = console.nextInt();
}
return num;
}
//adds both arrays by index into the sum array
public static int[] addBigInts (int[]numArray1, int[] numArray2){
int count = Math.max(numArray1.length, numArray2.length);
int[] sum = new int[count+1];
//starting at numArray1 & 2 index, sums ints
for (int i=count-1; i>=0; i--){
//sum has to be +1 for numArray1 & 2 indexes
sum[i+1] = numArray1[i] + numArray2[i];
if (sum[i+1]>9){
//this line below doesn't seem to execute
sum[i]++;
sum[i+1] = sum[i+1] - 10;
}
else;
}
System.out.println(Arrays.toString(sum));
return sum;
}
}
You have:
sum[i+1] = numArray1[i] + numArray2[i];
You need:
sum[i+1] += numArray1[i] + numArray2[i];
By assigning instead of adding you are overwriting the carried 1 from the previous digit.
In your add bigints function, try change store the addition into a temp variable and use that in the if statement
int temp = numArray1[i] + numArray2[i]
if( temp > 9)

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories