Java Array: Finding how many numbers are less then the Mean - java

Okay so im trying to find the amount of numbers that are less then
the mean of the first array. Everything but the last part is working and i
cant figure it out. The code at the bottom is what im having problems with.
for example. if i enter 1 2 3 4 5. the mean is 3 and, 1 and 2 are less then 3. so the answer would be 2 numbers.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("How many integers should we analyze?" );
int num;
num=in.nextInt();
while ( num <= 2)
{
System.out.println( "Please reenter, integer must be greater than 1" );
num=in.nextInt();
}
int[] arr = new int[num];
System.out.println( "Please enter the "+ num +" integers:" );
for (int i = 0; i < arr.length; i++)
{
arr[i] = in.nextInt();
}
System.out.print("Number of integers input: " + num);
System.out.println();
double total = 0;
for( int element : arr) {
total += element;
}
System.out.print("Total: " + (int) total);
System.out.println();
double mean = 0;
if ( arr.length > 0) {
mean = total / arr.length;
}
System.out.print("Mean: " + mean );
int big = arr[0];
for (int i = 0 ; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
}
}
System.out.println();
System.out.print("Largest: " + big);
System.out.println();
///////////////////////////////////////////////////////////////////////////////////////////////
int less;
for(int i=0;i<mean;i++) {
int num2 = i;
int[] arr2 = new int[num2];
int count = 0;
while ( num2 != 0 )
{
num2/=10;
++count;
System.out.print("Numbers less than the mean: " + count);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
}
}

you could use this code below
int count = 0;
for(int i =0;i< arr.length;i++) {
if(arr[i] < mean)
count++;
}
System.out.println("numbers less than mean " + count);
what this does is it loops through all of the original integers and if one is less than the mean, the count variable goes up by 1.

You should iterate over the array and check each element if they are under the mean. If yes, then increment an integer.
int less = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < mean) {
less++;
}
}
System.out.print("Numbers less than the mean: " + less);

Related

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

java.util.NoSuchElementException reading user input

I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}
Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

ArrayIndexOutOfBoundsException when assigning new arrays

I am trying to sort one array to two other arrays that have to be exact length. Why am I getting the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Tal.main(Tal.java:39) when running this? I know there is better way to solve this task but I am not allowed to. I have to do it this way.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many random numbers from 0 to 999? ");
int amount = in.nextInt();
int lowerCounter = 0;
int higherCounter = 0;
int[] numbers = new int[amount];
System.out.print("Here is the random numbers: ");
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = (int) Math.floor(Math.random()*1000);
System.out.print(numbers[i] + " ");
if (numbers[i] <= 499) {
lowerCounter++;
}
else {
higherCounter++;
}
}
System.out.println("");
int[] numbersLow = new int[lowerCounter];
int[] numbersHigh = new int[higherCounter];
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] <= 499)
{
numbersLow[i] = numbers[i];
} else {
numbersHigh[i] = numbers[i];
}
}
System.out.print("These "+ lowerCounter +" numbers are from 0 to 499: ");
for(int i = 0; i < numbersLow.length; i++)
{
System.out.print(numbersLow[i] + " ");
}
System.out.println("");
System.out.print("These "+ higherCounter +" numbers are from 500 to 999: ");
for(int i = 0; i < numbersHigh.length; i++)
{
System.out.print(numbersHigh[i] + " ");
}
}
Your looping variables are not correct. You should fix your code in order to have 2 different counters for both arrays and one counter to loop through the main one.
lowerCounter=higherCounter=0;
for(int i = 0; i < numbers.length; i++) {
if (numbers[i] <= 499) {
numbersLow[lowerCounter++] = numbers[i];
} else {
numbersHigh[higherCounter++] = numbers[i];
}
}
The best way is to use Java 8 :
int[] lowerThan500 = Arrays.stream(numbers).filter(i -> i < 500).toArray();
Less code, less errors.
Or :
long nbLessThan500 = Arrays.stream(numbers).filter(i -> i < 500).count();

Counting occurrences of integers in an array in Java

Note: no mapping, no sorting
Here's my code:
public static void countArray(int[] n){
int[] m = new int[n.length]; //50 elements of integers between values of 10 & 20
int count = 0;
int sum = 0;
for ( int i = 0; i < n.length ; i++){
m[i] = n[i]; //make a copy of array 'n'
System.out.print(m[i]+" ");
}System.out.println();
for ( int j =0; j < n.length ; j++){
count =0;
for(int i = 0; i < n.length ; i++){
if (n[j]%m[i]==0 && n[j] == m[i])
count++;
}if ( n[j]%m[j] == 0)
System.out.println(m[j] + " occurs = " + count);
}
}
So the problem is: I get repeating results like : "25 occurs = 5", on different lines.
What I think: the problem occurs because of if ( n[j]%m[j] == 0)
so I tried if ( n[j]%m[j+1] == 0). Another problem occurs since m[j] will be m[50] so it crashes but sort of give me the results that I want.
Result that I want: something like this: no repetitions and covers all the random integers on a set
17 occurs = 3
23 occurs = 2
19 occurs = 3
15 occurs = 2
12 occurs = 2
With some adaptation your code should work :
public static void countArray(int[] n){
boolean [] alreadyCounted = new boolean[n.length];
for (int i = 0; i < n.length ; i++){
int count = 0;
if (alreadyCounted[i]) {
// skip this one, already counted
continue;
}
for(int j = 0; j < n.length ; j++){
if (n[i] == n[j]) {
// mark as already counted
alreadyCounted[j] = true;
count++;
}
}
System.out.println(n[i] + " occurs = " + count);
}
}
You could definitely use the same logic with better code, I just tried to follow the original "coding style";
This is O(n^2) solution (read "very slow").
If you could use sorting, you could do it in O(n log(n)) - that is fast.
With mapping you could do it in O(n) - that is blazingly fast;
If you exploit the input limit you can lose the nested loop:
public static void main(String[] args)
{
//6 elements of integers between values of 10 & 20
int[] countMe = { 10, 10, 20, 10, 20, 15 };
countArray(countMe);
}
/** Count integers between values of 10 & 20 (inclusive) */
public static void countArray(int[] input)
{
final int LOWEST = 10;
final int HIGHEST = 20;
//Will allow indexes from 0 to 20 but only using 10 to 20
int[] count = new int[HIGHEST + 1];
for(int i = 0; i < input.length; i++)
{
//Complain properly if given bad input
if (input[i] < LOWEST || HIGHEST < input[i])
{
throw new IllegalArgumentException("All integers must be between " +
LOWEST + " and " + HIGHEST + ", inclusive");
}
//count
int numberFound = input[i];
count[numberFound] += 1;
}
for(int i = LOWEST; i <= HIGHEST; i++)
{
if (count[i] != 0)
{
System.out.println(i + " occurs = " + count[i]);
}
}
}
try this :(sort the array and then count the occurence of element)
public static void countArray(int[] n) {
int count = 0;
int i, j, t;
for (i = 0; i < n.length - 1; i++) // sort the array
{
for (j = i + 1; j < n.length; j++) {
if (n[i] > n[j]) {
t = n[i];
n[i] = n[j];
n[j] = t;
}
}
}
for (i = 0; i < n.length;)
{
for (j = i; j < n.length; j++) {
if (n[i] == n[j])
{
count++;
} else
break;
}
System.out.println(n[i] + " occurs " + count);
count = 0;
i = j;
}
}
Here's a nice, efficient way to do it, rather more efficiently than the other solutions posted here. This one runs in O(n) time, where the array is of length n. It assumes that you have some number MAX_VAL, representing the maximum value that you might find in your array, and that the minimum is 0. In your commenting you suggest that MAX_VAL==20.
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i: arr)
counts[i]++;
//now we print the results
for (int i: arr)
if (counts[i]>0) {
System.out.println(i+" occurs "+counts[i]+" times");
//now set this count to zero so we won't get duplicates
counts[i]=0;
}
}
It first loops through the array increasing the relevant counter each time it finds an element. Then it goes back through, and prints out the count for each one. But, crucially, each time it prints the count for an integer, it resets that one's count to 0, so that it won't get printed again.
If you don't like the for (int i: arr) style, this is exactly equivalent:
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i=0; i<arr.length; i++)
counts[arr[i]]++;
//now we print the results
for (int i=0; i<arr.length; i++)
if (counts[arr[i]]>0) {
System.out.println(arr[i]+" occurs "+counts[arr[i]]+" times");
//now set this count to zero so we won't get duplicates
counts[arr[i]]=0;
}
}

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers

I'm at a loss here.
I have this homework assignment where I have to enable the user to input 10 numbers, place them in an array, and figure out which inputted numbers are unique.
This is my workflow right now: Input number> If number has not been inputted before, store in array; if number has been inputted before, ignore> Display the numbers inputted> Display the unique numbers
ex: Inputting 1 2 3 5 1 2 4 6 would find the unique numbers and show "1 2 3 4 5 6"
So far my code looks like this:
public class HwChapter6 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] count = new int[10];
int number = 0;
int x = 0;
boolean unique = false;
int length = count.length;
System.out.println("Insert 10 single digit numbers in any order your heart desires:");
for (int i = 0; i < count.length; i++) {
count[i] = input.nextInt();
number = count[i];
for (int j = 0; j < count.length; j++) {
Thanks for the help guys.
Instead of an array of input values, put them in a Set of Integers. Sets, by definition, store only unique values. If you add 3 'foos', there will be only one 'foo' in the set.
// Add this to your top-level loop
Set<Integer> uniqueValues = new TreeSet<Integer>;
uniqueValues.add(number);
// Add this after the loop to write all unique values on one line
for (Integer value : uniqueValues) {
System.out.print(value.toString() + " ");
}
// Now end the line.
System.out.println();
Check the numbers at they are entered, then keep track of which ones are unique by marking the same positions in a second (boolean) array with true if they are unique and false otherwise.
Then, when you print out the unique values, only print the value from each position in numbers[] if that position in uniques[] contains true.
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean[] uniques = new boolean[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
uniques[i] = true;
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && i != j) {
uniques[i] = false;
}
}
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("\nThe uniqe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
if(uniques[i]) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Store all numbers in an array.
For each stored number: check if number was inserted before and save that in a boolean array.
Print all numbers that are not marked in the boolean array.
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
The fastest and most concise and efficient way is to destructively parse the array for uniques using its first number as a magic value, after all other operations on it are complete:
Scanner input = new Scanner(System.in);
int magic = 0;
int[] numbers = new int[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("The unique numbers are: ");
magic = numbers[0];
System.out.println(magic + ", ");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && j != i) {
numbers[j] = magic;
}
}
if(numbers[i] != magic) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Yes, I have two answers - this one is significantly different from the other one, and is better, though it is much more difficult for beginners to understand. Both solutions are valid, however.

Categories

Resources