Arrays, Statistics, and calculating mean, median, mode, average and sqrt - java

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

Related

find the best ratios to minimize the cost of the box ( 100 % ratio or less ) from multiple values

I have array of targets values and list of components need to pick the best ratio of each or some of it that make the final return ratio is 100 % or less and meet the targets array with minimum cost in java
here is the code that i tried to solve the problem with and it work correctly as i need but take so long time and need some optimization
inputs
InputMaxRates[] --the max possible rate that the final solution can have from the ith protect
inputMinRates[] --the min possible rate that the final solution can have from the ith protect if it included
valuesMatrix[][] --array of the values inside 100% in the ith protect
targetsArray[] --the target values that the final box need to cover
costOfTheProdects[] --the cost of 100% if the ith protect
IsRequired[] --boolen array to tell if the ith protect must be in the final box
output
array with size of input protects number with the best ratio of each / some of the protects that meet the targets with minimum cost
output must be array with total of 100 or less and if no possible solution return array with -1
anyone can help please here is my code
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTable;
public class AISolver {
double InputMaxRates[], inputMinRates[] , costOfTheProdects[];
double targetsArray[];
double[] bestRatios = null;
double[] bestValues = null;
boolean IsRequired[];
double minPriceCost = 1000000000;
int minPriceMet = -1;
double[][] valuesMatrix;
int numberOfTargets = 9;//number of vectors
int numberOfRows = 0;
public AISolver(double[] InputMaxRates, double[] inputMinRates, double[][] valuesMatrix,
double[] targetsArray, boolean IsRequired[], double[] costOfTheProdects) {
this.InputMaxRates = InputMaxRates;
this.inputMinRates = inputMinRates;
this.valuesMatrix = valuesMatrix;
this.targetsArray = targetsArray;
this.costOfTheProdects = costOfTheProdects;
this.IsRequired = IsRequired;
numberOfTargets = targetsArray.length;
numberOfRows = inputMinRates.length;
}
int hitflag = 0;
private void checkTheVictor(Vector<Double> v) {
double[] thisRatioValues = getTheNewValues(v);
double thisRatioCost = calcCostFromRates(v);
int checkmet = checkMeetTargets(thisRatioValues);
if (checkmet > 0 && checkmet >= minPriceMet) {
if (checkmet > minPriceMet) {
//JOptionPane.showMessageDialog(dataTable, "Meet -> " + minPriceMet);
minPriceCost = 1000000000;
}
minPriceMet = checkmet;
if (checkmet == numberOfTargets) {
// JOptionPane.showMessageDialog(dataTable, "Meet -> " + minPriceMet + " cost = " + thisRatioCost);
// if (hitflag == 0) {
// minPriceCost = 1000000000;
// }
if (minPriceCost > thisRatioCost) {
minPriceCost = thisRatioCost;
bestRatios = new double[numberOfRows];
for (int i = 0; i < bestRatios.length; i++) {
try {
bestRatios[i] = v.get(i);
} catch (Exception e) {
bestRatios[i] = 0;
}
}
bestValues = new double[numberOfTargets];
for (int i = 0; i < thisRatioValues.length; i++) {
bestValues[i] = thisRatioValues[i];
}
}
}
}
}
public double[] bestRatioFinder(Vector<Double> v) {
if ((v.size() == numberOfRows && getRatesVectorSum(v) <= 100) || getRatesVectorSum(v) >= 100) {
checkTheVictor(v);
} else if (inputMinRates[v.size()] == InputMaxRates[v.size()]) {
v.add(inputMinRates[v.size()]);
bestRatioFinder(v);
} else {
//leave the prodect option
if (IsRequired[v.size()] == false) {
v.add(0.0);
// new Thread(() -> {
// Vector<Double> vt = new Vector<>();
// for (Double tx : v) {
// vt.add(tx);
// }
// bestRatioFinder(v);
// }).start();
bestRatioFinder(v);
v.removeElementAt(v.size() - 1);
}
//contune
Double maxPossibleRate = Math.min(101 - getRatesVectorSum(v), InputMaxRates[v.size()] + 1);
for (Double i = inputMinRates[v.size()]; i < maxPossibleRate; i++) {
v.add(i);
//System.out.println(Arrays.toString(v.toArray()));
// new Thread(() -> {
// Vector<Double> vt = new Vector<>();
// for (Double tx : v) {
// vt.add(tx);
// }
// bestRatioFinder(v);
// }).start();
bestRatioFinder(v);
v.removeElementAt(v.size() - 1);
}
}
return bestRatios;
}
private int getRatesVectorSum(Vector<Double> v) {
int sum = 0;
for (int i = 0; i < v.size(); i++) {
Double el = v.elementAt(i);
sum += el;
}
return sum;
}
private double calcCostFromRates(Vector<Double> v) {
double sum = 0;
for (int i = 0; i < v.size(); i++) {
Double el = v.elementAt(i);
double cost = costOfTheProdects[i];
sum += el * cost;
}
return sum;
}
private double[] getTheNewValues(Vector<Double> v) {
//need to update
double[] gvalus = new double[numberOfTargets];
for (int rowCounter = 0; rowCounter < v.size(); rowCounter++) {
Double el = v.elementAt(rowCounter);
for (int colCounter = 0; colCounter < numberOfTargets; colCounter++) {
Double cItemRatio = el;
double theCourntValueOfTheItem = valuesMatrix[rowCounter][colCounter];
double theValueToAdd = cItemRatio * theCourntValueOfTheItem / 100;
gvalus[colCounter] += theValueToAdd;
}
}
return gvalus;
}
private int checkMeetTargets(double[] ratvals) {
int met = 0;
for (int i = 0; i < ratvals.length; i++) {
if (ratvals[i] >= targetsArray[i]) {
met++;
}
}
return met;
}
}

Use boolean to search for outliers of standard dev and then print the outliers using java

What I'm trying to do is figure out a way to print the outliers of standard deviation here. The outliers are defined as having a variance greater than 2x the standard deviation. I can't figure out how but I've started by creating a boolean flag, however I don't understand the dynamics of this. Could someone please help me figure out how to print out the outliers somehow? Thanks.
public class Main {
public static void main(String[] args)
{
{
Algebra n = new Algebra();
System.out.println(" ");
System.out.println("The maximum number is: " + n.max);
System.out.println("The minimum is: " + n.min);
System.out.println("The mean is: " + n.avg);
System.out.println("The standard deviation is " + n.stdev);
}
}
}
2nd part:
public class Algebra
{
static int[] n = createArray();
int max = displayMaximum(n);
int min = displayMinimum(n);
double avg = displayAverage(n);
double stdev = displayStdDev(n);
public boolean outliers() {
for(int i = 0; i < n.length; i++)
{
boolean flag = (n[i] < stdev*2);
}
return
}
public Algebra()
{
this(n);
System.out.println("The numbers that are outliers are ");
for(int i = 0; i < n.length; i++)
{
System.out.print(" " + (n[i] < stdev*2));
}
}
public Algebra(int[] n)
{
createArray();
}
public static int[] createArray()
{
int[] n = new int[100];
for(int i = 0; i < n.length; i++)
n[i] = (int)(Math.random()*100 + 1);
return n;
}
public int displayMaximum(int[] n)
{
int maxValue = n[0];
for(int i=1; i < n.length; i++){
if(n[i] > maxValue){
maxValue = n[i];
}
}
return maxValue;
}
public int displayMinimum(int[] n)
{
int minValue = n[0];
for(int i=1;i<n.length;i++){
if(n[i] < minValue){
minValue = n[i];
}
}
return minValue;
}
protected double displayAverage(int[] n)
{
int sum = 0;
double mean = 0;
for (int i = 0; i < n.length; i++) {
sum += n[i];
mean = sum / n.length;
}
return mean;
}
protected double displayStdDev(int[] n)
{
int sum = 0;
double mean = 0;
for (int i = 0; i < n.length; i++) {
sum = sum + n[i];
mean = sum/ n.length;
}
double squareSum = 0.0;
for (int i = 0; i < n.length; i++)
{
squareSum += Math.pow(n[i] - mean, 2);
}
return Math.sqrt((squareSum) / (n.length - 1));
}
}
Variance is defined as the squared difference from the mean. This is a fairly straight forward calculation.
public static double variance(double val, double mean) {
return Math.pow(val - mean, 2);
}
You define an outlier as an instance that has a variance greater than x2 the standard deviation.
public static boolean isOutlier(double val, double mean, double std) {
return variance(val, mean) > 2*std;
}
You then just need to iterate through the values and print any values that are evaluated as an outlier.
public void printOutliers() {
for (int i : n) {
if (isOutlier(i, avg, stdev)) {
...
}
}
}
You should note that if one value is defined as an outlier and subsequently removed, values previously classified as an outlier may no longer be. You may also be interested in the extent of an outlier in the current set; One value may be an outlier to a greater extent than another.

two problems with mean med mode method

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 + ",");
}

Program won't quit after 10 integers or 0 have been entered

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 :)

Inheritance problems in Java

I have some problems with getting inheritance to work. In the parent class, the array Coefficients is private. I have some access methods but I still can't get it to work.
import java.util.ArrayList;
public class Poly {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);
}
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Poly multiplyCon (double c){
int n = getDegree();
Poly results = new Poly(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Poly multiplyPoly (Poly p){
int n = getDegree();
int m = p.getDegree();
Poly result = null;
for (int i = 0; i <= n; i++){
Poly tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void leadingZero() {
int degree = getDegree();
if ( degree == 0 ) return;
if ( coefficients[degree] != 0 ) return;
// find the last highest degree with non-zero cofficient
int highestDegree = degree;
for ( int i = degree; i <= 0; i--) {
if ( coefficients[i] == 0 ) {
highestDegree = i -1;
} else {
// if the value is non-zero
break;
}
}
float[] newCoefficients = new float[highestDegree + 1];
for ( int i=0; i<= highestDegree; i++ ) {
newCoefficients[i] = coefficients[i];
}
coefficients = newCoefficients;
}
public Poly differentiate(){
int n = getDegree();
Poly newResult = new Poly(n);
if (n>0){ //checking if it has a degree
for (int i = 1; i<= n; i++){
newResult.coefficients[i-1]= coefficients[i] * (i); // shift degree by 1 and multiplies
}
return newResult;
} else {
return new Poly(); //empty
}
}
public Poly multiByConstantWithDegree(double c, int degree){ //used specifically for multiply poly
int oldPolyDegree = this.getDegree();
int newPolyDegree = oldPolyDegree + degree;
Poly newResult = new Poly(newPolyDegree);
//set all coeff to zero
for (int i = 0; i<= newPolyDegree; i++){
newResult.coefficients[i] = 0;
}
//shift by n degree
for (int j = 0; j <= oldPolyDegree; j++){
newResult.coefficients[j+degree] = coefficients[j] * (float)c;
}
return newResult;
}
}
Can anyone help me fix my Second class that inherits from the one above? I cant seem to get my multiply and add methods for the second class to work properly.
public class QuadPoly extends Poly
{
private float [] quadcoefficients;
public QuadPoly() {
super(2);
}
public QuadPoly(int degree) {
super(2);
}
public QuadPoly(float [] f) {
super(f);
if (getDegree() > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
}
public QuadPoly(Poly p){
super(p.coefficients);
for (int i = 0; i < coefficients.length; i++){
if (coefficients[i] < 0){
throw new Exception("Expecting positive coefficients!");
}
}
}
// public QuadPoly(Poly p){
// super(p.coefficients);
//}
public QuadPoly addQuad (QuadPoly p){
return new QuadPoly(super.add(p));
}
public QuadPoly multiplyQuadPoly (QuadPoly f){
if (quadcoefficients.length > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
return new QuadPoly(super.multiplyPoly(f));
}
I would make the coefficients protected or use an accessor method.
I wouldn't throw a plain checked Exception. An IllegalArgumentException would be a better choice.
What is quadcoefficients? They don't appear to be set anywhere.
You put coefficients private. I wouldn't change this but I would add a getter method into Poly class:
public class Poly {
//somecode here
public float[] getCoefficients(){
return this.coefficients;
}
}
Then I would use it by the getter method in other code;
public QuadPoly(Poly p){
super(p.getCoefficients);
//some more code here
}
Even if you make coefficient protected, you are trying to reach coefficients field of another Object, which is a parameter. So it is not related to inheritance and the problem.

Categories