So here is my completed code that calculates Mean, Median, Mode, Standard deviation, min, max, q1, q2, and 5 number summary which is supposed to be returned as an array. The array is formatted properly to my knowledge, but for some odd reason the return array is spitting out this 5 number Summary:[D#689af4 and I don't for the life of my know why or how to fix it. Also the mode is outputting 22 when I need it to out put -1. Is there any one who can look at this and tell me what is wrong and what I can to do fix these issues?
import java.util.Arrays;
class Statistics {
public static void main(String[] args)
{
int[] a = new int[]{22,44,66,55,33};
bubbleSort(a);
double mean;
double median;
int mode;
int max;
int min;
double sd;
int q1;
int q3;
double[] vals;
mode = calcMoe (a);
median = calcMed (a);
mean = calcMean (a);
max =calcMax (a);
min =calcMin (a);
sd =calcSd (a);
q1=calcQuart1 (a);
q3=calcQuart3 (a);
vals=calcNumsum (a);
System.out.println("Median:"+median);
System.out.println("Mean:"+mean);
System.out.println("Mode:"+mode);
System.out.println("max number is : " + max);
System.out.println("min number is : " + min);
System.out.println("Standard Deviation:"+sd);
System.out.println("1st Quartile:"+q1);
System.out.println("3rd Quartile:"+q3);
System.out.println("5 number Summary:"+vals);
}
public static double calcMean(int[] a)
{
// int[]array = {22,44,66,55,33};
int i;//=0;
int sum=0;
double mean =0;
for ( i=0;i<a.length;i++)
{
//System.out.println(a[i]);
sum=sum+a[i];
}
{ mean = ((double) sum/ ((double) a.length));
//System.out.println(); } {
return mean;}
}
//Calulate median
public static double calcMed(int[] a)
{// Sort array
int[] sorta = bubbleSort(a);
double median = 0;
if (a.length % 2 == 0)
{
int indexA = (sorta.length - 1) / 2;
int indexB = sorta.length / 2;
median = ((double) (sorta[indexA] + sorta[indexB])) / 2;
}
// Else if our array's length is odd
else
{
int index = (sorta.length - 1) / 2;
median = a[ index ];
}
// Print the values of the sorted array
for (int v : sorta)
{
System.out.println(v);
}
return median;
}
public static int[] bubbleSort(int[] a)
{
//outer loop
for(int luck=0; luck<a.length -1; luck++){
for (int juck=1; juck<a.length - luck; juck++){
if (a[juck-1]>a[juck]){
int temp= a[juck];
a[juck]=a[juck-1];
a[juck-1]=temp;
//System.out.printf("unsorted array after %d pass %s: %n", luck+1, Arrays.toString(a));
}
}
}
return a;
}
public static int calcMoe(int[] a)
{
Arrays.sort(a);
int count2 = 0;
int count1 = 1;
int pupular1 =0;
int mode =0;
for (int i = 0; i < a.length; i++)
{
pupular1 = a[i];
count1 = 1;
for (int j = i + 1; j < a.length; j++)
{
if (pupular1 == a[j]) count1++;
}
if (count1 > count2)
{
mode = pupular1;
count2 = count1;
}
if (count1 == count2)
{
mode = Math.min(mode, pupular1);
}
}
return mode;
}
public static int calcMax(int[] a) {
//int min = a[0];
int max = a[0];
for (int i = 1; i <= a.length - 1; i++) {
if (max < a[i]) {
max = a[i];
}
}
return max;
}
public static int calcMin(int[] a) {
int min = a[0];
for (int i = 1; i <= a.length - 1; i++) {
if (min > a[i]) {
min = a[i];
}
}
return min;
}
public static double calcSd(int[] a) {
//int sum = 0;
//int max = 0;
//int min = a[0];
double sd = 0;
int i = 0;
double mean =0;
sd=0;
for ( i=0;i<a.length;i++)
{
sd += ((a[i] - mean)*(a[i] - mean)) / (a.length - 1);
}
double standarddeviation = Math.sqrt(sd);
{
}
return standarddeviation;
}
public static int calcQuart1(int[] a) {
int[] sorta = bubbleSort(a);
int q1 = 0;
{
int index = (sorta.length - 1) / 4;
q1 = a[ index ] ;
}
for (int v : sorta)
{
System.out.println(v);
}
return q1;
}
public static int calcQuart3(int[] a) {
int[] sorta = bubbleSort(a);
int q3 = 0;
{
int index = 3*(sorta.length - 1) / 4;
q3 = a[ index ] ;
}
for (int v : sorta)
{
System.out.println(v);
}
return q3;
}
public static double[] calcNumsum(int[] a) {
double median = calcMed (a);
double max =calcMax (a);
double min =calcMin (a);
double q1=calcQuart1 (a);
double q3=calcQuart3 (a);
double[] vals = new double[5];
vals[0] = min;
vals [1] = q1;
vals [2] = median;
vals [3] = q3;
vals [4] = max;
return vals;
}
}
This line:
System.out.println("5 number Summary:"+vals);
simply takes vals, converts it to a String, and prints it. The default toString implementation for array types in Java produces the output you noted: the overall type ([ for 'array'), the type stored in the array (D for double), an # symbol, and the location of the array in memory (689af4, in this case).
To get perhaps a more useful output for your purposes, you can use Arrays.toString:
System.out.println("5 number summary: " + Arrays.toString(vals));
In regard to that strange out put "5 number Summary:[D#689af4" this is just the reference of the array, and that is the general print of an array. If you want to print all elements in an array you need to implement a toString method and the basic way to do it is print one-by-one item from the array. In your case it will be something like that:
System.out.print( "5 number Summary: ");
for(int i = 0; i < vals.length; i++){
System.out.print(" " + vals[i]);
}
System.out.println();
Your code is printing the memory location of the Object vals not the content, to print the content you have to loop over it like this:
System.out.println("5 number Summary:");
for (double d : vals) {
System.out.print(d + ",");
}
Related
EDIT
try run in the main:
int[] arr = {646 ,94 ,366 ,754 ,948 ,678 ,121 ,320 ,528 ,36};
for(int i=0;i<10;i++){
System.out.println(randomizedSelect(arr,0,arr.length-1,5));
printArr(arr);
}
and see that i got diffrent outpot in each loop..
Got a little problem that I would like some help with, if anyone knows how.
I need to find the kth smallest value in an array by randomized partition.
I've got two problems:
I get array out of bounds with -1 and can't find a way to fix it.
Most of the time it works but sometimes it gives me wrong k place.
For example for array with length of 10, it tells me that 20 is in the 5th place but actually it should be in the 2nd place and it prints the array where not all the values on the left are smaller than 20 and not smaller than the 5th place.
Here is an example array:
{646 ,94 ,366 ,754 ,948 ,678 ,121 ,320 ,528 ,36}
The array input is done by a random number generator.
This is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
int nSize = askSizeN();
int kSize = askSizeK(nSize);
int[] arr = new int[nSize];
chose(arr);
int[] arrCopy = new int[nSize];
for (int i = 0; i < arrCopy.length; i++) {
arrCopy[i] = arr[i];
}
printArr(arrCopy);
System.out.println(randomizedSelect(arrCopy, 0, arr.length - 1, kSize));
printArr(arrCopy);
}
private static int partition(int[] arr, int p, int r) {
int x = arr[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (arr[j] <= x) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[r];
arr[r] = temp;
return i + 1;
}
private static int randomizedPartition(int[] arr, int p, int r) {
int i = rand.nextInt(r - p);
int temp = arr[r];
arr[r] = arr[i];
arr[i] = temp;
return partition(arr, p, r);
}
private static int randomizedSelect(int[] arr, int p, int r, int i) {
if (p == r) {
return arr[p];
}
int q = randomizedPartition(arr, p, r);
int k = q - p + 1;
if (i == k) {
return arr[q];
}
else if (i < k) {
return randomizedSelect(arr, p, q - 1, i);
}
else {
return randomizedSelect(arr, q + 1, r, i - k);
}
}
private static int askSizeN() {
System.out.println("Please chose the size of the heap: \n" + "(the size of n)");
return scan.nextInt();
}
private static int askSizeK(int nSize) {
System.out.println(
"Please chose how much small values you want to see: \n" + "(the size of k)");
int kSize = scan.nextInt();
if (kSize > nSize) {
System.out.println("cant print more number then the size of the Heap..");
System.out.println("Please enter a number less then " + (nSize + 1));
askSizeK(nSize);
}
return kSize;
}
private static int[] chose(int[] a) {
System.out.println("Chose the option you want: \n" + "\t1. enter your own values."
+ "\n\t2. let me generate random values");
int chose = scan.nextInt();
if (chose == 1) {
for (int i = 0; i < a.length; i++) {
System.out.println("Enter value number " + (i + 1));
a[i] = scan.nextInt();
}
}
else if (chose == 2) {
System.out.println("Generate random numbers.");
for (int i = 0; i < a.length; i++) {
a[i] = rand.nextInt(1000);
}
}
else {
chose(a);
}
return a;
}
private static void printArr(int[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
}
I've solved the problem.
Method randmizedPartition() was generating wrong random pivot for partition.
I solved it by changing the random line to:
int i = rand.nextInt((r - p) + 1) + p;
I have an array with several numbers:
int[] tab = {1,2,3,4};
I have to create two methods the first is the sum() method and the second is numberOdd().
It's Ok for this step !
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
public static int sum(int[] tab, int length){
int total = 0;
for(int i=0;i<length;i++){
total += tab[i];
}
return total;
}
public static int numberOdd(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 != 0){
tab[n++] = tab[i];
}
}
return n;
}
Now, I have to add the even numbers with the numberEven() method and I get the value "0".
I don't understand why I retrieve the value => 0 ???????
Here is my code:
int[] tab = {1,2,3,4};
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
length = numberEven(tab,length);
int sum_even = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers : => " + sum_even);
}
public static int numberEven(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 == 0){
tab[n++] = tab[i];
}
}
return n;
}
For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte
Thank you for your help.
You need to add tab[i] to n
Having length as a parameter to numberEven does not cause any harm but you don't need it.
Given below is the working example:
public class Main {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4 };
System.out.println(numberEven(tab));
}
public static int numberEven(int[] tab) {
int n = 0;
for (int i = 0; i < tab.length; i++) {
if (tab[i] % 2 == 0) {
n += tab[i];
}
}
return n;
}
}
Output:
6
you have changed the array in your numberOdd() method.
try replacing tab[n++] = tab[i]; with n++;
public static int sumEven(int[] tab){
int sumEven = 0;
for(int i=0;i<tab.length;i++){
if(tab[i] % 2 == 0){
sumEven = sumEven + tab[i];
}
}
return sumEven;
}
This should work.
I am currently in a class for Java Programming and am completely new to Java. I am trying to create a program that will use binary search for the value 45.3
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
};
};
};
System.out.println("45.3 found" + binarySearch(a, 45.3));
};
public static void binarySearch(Integer[] a, int x) {
int low = 0;
int high = a.length - 1;
int mid; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (a[mid].compareTo(x) < 0) {
low = mid + 1;
}
else if (a[mid].compareTo(x) > 0) {
high = mid - 1;
};
};
};
This is the compiler error I got:
Line: 25
method binarySearch in class findValue cannot be applied to given types;
required: java.lang.Integer[],int
found: double[],double
reason: actual argument double[] cannot be converted to java.lang.Integer[] by method invocation conversion
(I know there is a lot of room for improvement, but I'm just suggesting the minimum number of changes for the program to work)
The method
public static void binarySearch(Integer[] a, int x) {...}
is expecting integers, but we want it to use doubles insted. This means that the arguments should be an array of doubles, and the double to find:
public static void binarySearch(double[] a, double x) {...}
This said, we know that this function will return an int, so we set the return type:
public static double binarySearch(double[] a, double x) {...}
Now, finally, we must return the number we were looking for by adding the following at the end of the method (after the while):
return mid;
The final result should be:
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
}
}
}
System.out.println("45.3 found: " + binarySearch(a, 45.3));
}
public static int binarySearch(double[] a, double x) {
int low = 0;
int high = a.length - 1;
int mid = (low + high) / 2; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (Double.compare(a[mid], (double)x) < 0) {
low = mid + 1;
}
else if (Double.compare(a[mid], (double)x) > 0) {
high = mid - 1;
}
}
return mid;
}
}
Output:
45.3 found: 5
From your declaration of the method public static void binarySearch(Integer[] a, int x) {
the binarySearch is expecting an array of Integer and an int as parameters,
While your call in line 25 is calling binary search with a double array and a double as parameter, hence the exception.
You can't convert a double to int because the double has more "information" than the int. double 43.5 converted to int would lose the .5
I need to implement four static methods in a class named ArrayStatistics. Each of the four methods will calculate the mean, median, mode, and population standard deviation, respectively, of the values in the array.
This is my first time working with Java, and cannot figure out what should I do next. I was given some test values for, you guessed it, test out my program.
public class ArrayStatistics {
public static void main(String[] args) {
final int[] arr;
int[] testValues = new int[] { 10, 20, 30, 40 };
meanValue = a;
meadianValue = b;
modeValue = c;
sqrtDevValue = d;
average = (sum / count);
System.out.println("Average is " );
}
static double[] mean(int[] data) {
for(int x = 1; x <=counter; x++) {
input = NumScanner.nextInt();
sum = sum + inputNum;
System.out.println();
}
return a;
}
static double[] median(int[] data) {
// ...
}
public double getMedian(double[] numberList) {
int factor = numberList.length - 1;
double[] first = new double[(double) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numbersList[i];
}
for (int i = numberList.length; i > last.length; i--) {
last[i] = numbersList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i]) middleNumbers[i] = numberList[i];
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return b;
}
}
static double[] mode(int[] data) {
public double getMode(double[] numberList) {
HashMap<Double,Double> freqs = new HashMap<Double,Double>();
for (double d: numberList) {
Double freq = freqs.get(d);
freqs.put(d, (freq == null ? 1 : freq + 1));
}
double mode = 0;
double maxFreq = 0;
for (Map.Entry<Double,Doubler> entry : freqs.entrySet()) {
double freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return c;
}
static double[] sqrt(int[] sqrtDev) {
return d;
}
}
This is pretty easy.
public double mean(ArrayList list) {
double ans=0;
for(int i=0; i<list.size(); i++) {
ans+=list.get(i); }
return ans/list.size()
}
`
Median:
public void median(ArrayList list) {
if(list.size()%==2) return (list.get(list.size()/2)+list.get(list.size()+1))/2;
else return list.get((list.size()/2)+1)
}
For Mode, just a keep a tally on the frequency of each number occurrence, extremely easy.
For standard deviation find the mean and just use the formula given here: https://www.mathsisfun.com/data/standard-deviation-formulas.html
Can someone help explain to me why my program won't terminate after either "0" or 10 integers have been entered? It's supposed to after, but it won't and keeps going even after either condition to quit have been met. It compiles correctly and doesn't give me any errors, so I think it has to do with my loops but I don't know what's wrong...
import java.util.Scanner;
public class Lab11
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int intArray[] = new int[10];
int size = 0;
int userInt;
do
{
do
{
System.out.print("Enter an integer in the array, or enter '0' to quit:" + " ");
userInt = scan.nextInt();
if (userInt != 0)
{
intArray[size] = userInt;
size++;
}
}
while (size <= intArray.length);
System.out.println(sum(intArray, size));
System.out.println(max(intArray, size));
System.out.println(min(intArray, size));
System.out.println(average(intArray, size));
System.out.println(stringToArray(intArray, size));
}
while (userInt !=0);
}
public static int sum(int intArray[], int size)
{
int sum = 0;
for (int a = 0; a <= size; a++)
{
sum = sum + intArray[size];
}
return sum;
}
public static int max(int intArray[], int size)
{
int max = intArray[0];
for (int b = 1; b <= size; b++)
{
if (intArray[size] > max)
{
max = intArray[size];
}
}
return max;
}
public static int min(int intArray[], int size)
{
int min = intArray[0];
for (int c = 1; c <= size; c++)
{
if (intArray[size] < min)
{
min = intArray[size];
}
}
return min;
}
public static double average(int intArray[], int size)
{
double total = 0;
double average = 0;
for (double element : intArray)
{
total = total + element;
}
if (intArray.length > 0)
{
average = total / intArray.length;
}
return average;
}
public static String stringToArray(int intArray[], int size)
{
String stringArray = "";
for (int d = 1; d <= size; d++)
{
stringArray = intArray.toString();
}
return stringArray;
}
}
The first if statement that tests for 0 is sandwiched in a do/while, and the do/while will loop your checker until your if statement is true. Place it outside your loop.
Edit: Heh the main method bit was for C, not java :)