Alter Simplex Algorithm to Minimize on objective function NOT maximize [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have created the following Simplex Algorithm that maximises on the objective function. I want the opposite to happen. In this example there are two variables and the algorithm must figure out what to multiply these two variables here (13.0 and 23.0) by in order to get the maximum possible result within the constraints set. I want the algorithm to figure out the lowest possible result instead.
My Code:
import java.util.*;
public class Simplex
{
private static final double EPSILON = 1.0E-10;
private double[][] tableaux;
private int numOfConstraints;
private int numOfVariables;
private int[] basis;
/**
* Constructor for objects of class Simplex
*/
public Simplex()
{
double[][] thisTableaux = {
{ 5.0, 15.0 },
{ 4.0, 4.0 },
{ 35.0, 20.0 },
};
double[] constraints = { 480.0, 160.0, 1190.0 };
double[] variables = { 13.0, 23.0 };
numOfConstraints = constraints.length;
numOfVariables = variables.length;
tableaux = new double[numOfConstraints+1][numOfVariables+numOfConstraints+1];
//adds all elements from thisTableaux to tableaux
for(int i=0; i < numOfConstraints; i++)
{
for(int j=0; j < numOfVariables; j++)
{
tableaux[i][j] = thisTableaux[i][j];
}
}
//adds a slack variable for each variable there is and sets it to 1.0
for(int i=0; i < numOfConstraints; i++)
{
tableaux[i][numOfVariables+i] = 1.0;
}
//adds variables into the second [] of tableux
for(int j=0; j < numOfVariables; j++)
{
tableaux[numOfConstraints][j] = variables[j];
}
//adds constraints to first [] of tableaux
for(int k=0; k < numOfConstraints; k++)
{
tableaux[k][numOfConstraints+numOfVariables] = constraints[k];
}
basis = new int[numOfConstraints];
for(int i=0; i < numOfConstraints; i++)
{
basis[i] = numOfVariables + i;
}
//show();
//optimise();
//assert check(thisTableaux, constraints, variables);
}
public void optimise() {
while(true) {
int q = findLowestNonBasicCol();
if(q == -1) {
break;
}
int p = getPivotRow(q);
if(p == -1) throw new ArithmeticException("Linear Program Unbounded");
pivot(p, q);
basis[p] = q;
}
}
public int findLowestNonBasicCol() {
for(int i=0; i < numOfConstraints + numOfVariables; i++)
{
if(tableaux[numOfConstraints][i] > 0) {
return i;
}
}
return -1;
}
public int findIndexOfLowestNonBasicCol() {
int q = 0;
for(int i=1; i < numOfConstraints + numOfVariables; i++)
{
if(tableaux[numOfConstraints][i] > tableaux[numOfConstraints][q]) {
q = i;
}
}
if(tableaux[numOfConstraints][q] <= 0) {
return -1;
}
else {
return q;
}
}
/**
* Finds row p which will be the pivot row using the minimum ratio rule.
* -1 if there is no pivot row
*/
public int getPivotRow(int q) {
int p = -1;
for(int i=0; i < numOfConstraints; i++) {
if (tableaux[i][q] <=0) {
continue;
}
else if (p == -1) {
p = i;
}
else if((tableaux[i][numOfConstraints+numOfVariables] / tableaux[i][q] < tableaux[p][numOfConstraints+numOfVariables] / tableaux[p][q])) {
p = i;
}
}
return p;
}
public void pivot(int p, int q) {
for(int i=0; i <= numOfConstraints; i++) {
for (int j=0; j <= numOfConstraints + numOfVariables; j++) {
if(i != p && j != q) {
tableaux[i][j] -= tableaux[p][j] * tableaux[i][q] / tableaux[p][q];
}
}
}
for(int i=0; i <= numOfConstraints; i++) {
if(i != p) {
tableaux[i][q] = 0.0;
}
}
for(int j=0; j <= numOfConstraints + numOfVariables; j++) {
if(j != q) {
tableaux[p][j] /= tableaux[p][q];
}
}
tableaux[p][q] = 1.0;
show();
}
public double result() {
return -tableaux[numOfConstraints][numOfConstraints+numOfVariables];
}
public double[] primal() {
double[] x = new double[numOfVariables];
for(int i=0; i < numOfConstraints; i++) {
if(basis[i] < numOfVariables) {
x[basis[i]] = tableaux[i][numOfConstraints+numOfVariables];
}
}
return x;
}
public double[] dual() {
double[] y = new double[numOfConstraints];
for(int i=0; i < numOfConstraints; i++) {
y[i] = -tableaux[numOfConstraints][numOfVariables];
}
return y;
}
public boolean isPrimalFeasible(double[][] thisTableaux, double[] constraints) {
double[] x = primal();
for(int j=0; j < x.length; j++) {
if(x[j] < 0.0) {
StdOut.println("x[" + j + "] = " + x[j] + " is negative");
return false;
}
}
for(int i=0; i < numOfConstraints; i++) {
double sum = 0.0;
for(int j=0; j < numOfVariables; j++) {
sum += thisTableaux[i][j] * x[j];
}
if(sum > constraints[i] + EPSILON) {
StdOut.println("not primal feasible");
StdOut.println("constraints[" + i + "] = " + constraints[i] + ", sum = " + sum);
return false;
}
}
return true;
}
private boolean isDualFeasible(double[][] thisTableaux, double[] variables) {
double[] y = dual();
for(int i=0; i < y.length; i++) {
if(y[i] < 0.0) {
StdOut.println("y[" + i + "] = " + y[i] + " is negative");
return false;
}
}
for(int j=0; j < numOfVariables; j++) {
double sum = 0.0;
for(int i=0; i < numOfConstraints; i++) {
sum += thisTableaux[i][j] * y[i];
}
if(sum < variables[j] - EPSILON) {
StdOut.println("not dual feasible");
StdOut.println("variables[" + j + "] = " + variables[j] + ", sum = " + sum);
return false;
}
}
return true;
}
private boolean isOptimal(double[] constraints, double[] variables) {
double[] x = primal();
double[] y = dual();
double value = result();
double value1 = 0.0;
for(int j=0; j < x.length; j++) {
value1 += variables[j] * x[j];
}
double value2 = 0.0;
for(int i=0; i < y.length; i++) {
value2 += y[i] * constraints[i];
}
if(Math.abs(value - value1) > EPSILON || Math.abs(value - value2) > EPSILON) {
StdOut.println("value = " + value + ", cx = " + value1 + ", yb = " + value2);
return true;
}
return true;
}
private boolean check(double[][] thisTableaux, double[] constraints, double [] variables) {
return isPrimalFeasible(thisTableaux, constraints) && isDualFeasible(thisTableaux, variables) && isOptimal(constraints, variables);
}
}
If you need any more info just ask. Any help appreciated thanks.

If you want to minimize f(x), this is equivalent to maximizing -f(x), so if your posted code solves maximization problems correctly, you can use it to minimize any objective function f(x) simply by maximizing its additive inverse -f(x).
Note that you do not change the constraints, only the objective function.
For example, minimizing f(x) = 3x + 5, x >= 1 is equivalent to maximizing -f(x) = -3x -5, x >= 1.
min[f(x), x>=1] = f(1) = 8 = -(-8) = -[-f(1)] = -max[-f(x), x>=1].
In general, min[f(x)] = f(Xmin) = -[-f(Xmax)] = -max[-f(x)] and Xmin = Xmax.
In the above example, min[f(x)] = -max[-f(x)] = 8 and Xmin = Xmax = 1.
In the particular example you give, you would simply need to change the line
double[] variables = { 13.0, 23.0 };
to
double[] variables = { -13.0, -23.0 };
The values of the variables returned should then be the same as for the minimum of the case where
double[] variables = { 13.0, 23.0 };
and multiplying the value of the objective function by -1 will give the minimum of the objective for the case where
double[] variables = { 13.0, 23.0 };

Related

Java, Class' s property is not updated when it is changed with method

App Link: Replit
I have a Neuron_ class
public class Neuron_ {
private double[] weights;
double learningRate;
public Neuron_ (int inputNeurons, double learningRate) {
this.weights = new double[inputNeurons];
this.learningRate = learningRate;
for (int i = 0; i < inputNeurons; i++) {
this.weights[i] = Math.random();
}
}
public double calculate(double[] inputs) {
double output = 0;
for(int i = 0; i < inputs.length; i++) {
output += inputs[i] * this.weights[i];
}
return output;
}
public void decreaseWeight(double[] inputs) {
for (int i = 0; i < this.weights.length; i++) {
this.weights[i] -= learningRate * inputs[i] ;
}
}
public void increaseWeight(double[] inputs) {
for (int i = 0; i < this.weights.length; i++) {
this.weights[i] += learningRate * inputs[i] ;
}
}
}
and I call increaseWeight and decreaseWeight methods from NeuralNetwork class
if(biggestIndex != correctIndex) {
System.out.println("Wrong output, changing weights");
for (int i = 0; i < this.neurons.length; i++) {
for (int j = 0; j < outputNeurons.length; j++) {
System.out.println("Changing weights for neuron " + i + " for output " + outputNeurons[j]);
if (j == correctIndex) {
this.neurons[i].increaseWeight(inputs);
} else if (j == biggestIndex) {
this.neurons[i].decreaseWeight(inputs);
}
}
}
}
neurons array is created like this
public NeuralNetwork_ (int inputNeurons, String[] outputNeurons, double learningRate) {
this.outputNeurons = outputNeurons;
this.neurons = new Neuron_[outputNeurons.length];
for(int i = 0; i<outputNeurons.length; i++) {
this.neurons[i] = new Neuron_(inputNeurons, learningRate);
}
}
When I call decreaseWeight and increaseWeight methods from another class, Logs show like they were changed but when I log weights at the beginning and at the end of the training, they were same every time.
weights array is not updating.
weights change, but finally the result is the same for maths ops.
Try modify you method with more log:
public void decreaseWeight(double[] inputs) {
double[] newWeights = new double[inputs.length];
for (int i = 0; i < this.weights.length; i++) {
newWeights[i] = this.weights[i] - learningRate;
}
this.weights = newWeights;
System.out.println("intermedial weights: " + Arrays.toString(this.weights));
}
public void increaseWeight(double[] inputs) {
double[] newWeights = new double[inputs.length];
for (int i = 0; i < this.weights.length; i++) {
newWeights[i] = this.weights[i] + learningRate;
}
this.weights = newWeights;
System.out.println("intermedial weights: " + Arrays.toString(this.weights));
}
and study the result.
For each neurons iterator you are increasing and then decreasing weights whith the same value, so finally neuron weights are the same

Find triangles in a list of random numbers

I'm taking each element as "sum", "first" and "sec". If (first + sec < sum) I'll make a hashset(tmp) of these 3 and put this hashset into a larger hashset(triangle) containing all tmp hashsets. This removes duplicate combinations of 3 numbers. Here's my code. It works but is there any better solution?
public void findTriangle(int[] a){
HashSet<HashSet<Integer>> triangle = new HashSet<HashSet<Integer>>();
HashSet<Integer> tmp;
for(int i=0;i<a.length;i++){
int sum=a[i];
for(int j=0;j<a.length;j++){
int first = a[j];
if(first!=sum){
for(int k=0;k<a.length;k++){
int sec = a[k];
if(sec!=first && sec!=sum && (first + sec < sum)){
tmp = new HashSet<Integer>();
tmp.add(first);
tmp.add(sec);
tmp.add(sum);
triangle.add(tmp);
}
}
}
}
}
for(HashSet<Integer> hs : triangle)
System.out.println(hs);
}
Sort the array and add the triplets to a list -
public static ArrayList<ArrayList<Integer>> get(int[] input) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (input.length < 3) {
return result;
}
Arrays.sort(input);
for (int i = 0; i < input.length - 2; i++) {
int k = i + 2;
for (int j = i + 1; j < input.length; j++) {
while (k < input.length && input[i] + input[j] > input[k]) {
ArrayList<Integer> inner = new ArrayList<Integer>();
inner.add(input[i]);
inner.add(input[j]);
inner.add(input[k]);
result.add(inner);
k++;
}
}
}
return result;
}
Not so optimal works yet. I tried testing the above two solutions and they seemed to not work. May be i was missing something. Hence decided to post my tested solution here. It does not check for duplicates.
Condition to find a triangle: http://www.wikihow.com/Determine-if-Three-Side-Lengths-Are-a-Triangle
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Arrays;
class Triangle {
int a;
int b;
int c;
public Triangle(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
#Override
public String toString() {
return this.a + " " + this.b + " " + this.c;
}
}
public class FindTriangle {
public List<Triangle> findTriangle(List<Integer> points) {
List<Triangle> result = new ArrayList<Triangle>();
System.out.println("Entered");
for (int i = 0; i < points.size(); i++) {
int pt0 = points.get(i);
System.out.println("Entered i:" + i);
for (int j = i + 1; j < points.size() - 2; j++) {
int pt1 = points.get(j);
int pt2 = points.get(j + 1);
Boolean isTri = isTriangle(pt0, pt1, pt2);
if (isTri.equals(Boolean.TRUE)) {
Triangle t = new Triangle(pt0, pt1, pt2);
result.add(t);
}
}
for (int j = 0; j < (i - 1) && j > 0; j++) {
int pt1 = points.get(j);
int pt2 = points.get(j + 1);
Boolean isTri = isTriangle(pt0, pt1, pt2);
if (isTri.equals(Boolean.TRUE)) {
Triangle t = new Triangle(pt0, pt1, pt2);
result.add(t);
}
}
// final
int pt1, pt2;
if (i == 0) {
pt1 = points.get(i + 1);
pt2 = points.get(points.size() - 1);
} else if (i == points.size() - 1) {
pt1 = points.get(0);
pt2 = points.get(i - 1);
} else {
pt1 = points.get(i + 1);
pt2 = points.get(i - 1);
}
Boolean isTri = isTriangle(pt0, pt1, pt2);
if (isTri.equals(Boolean.TRUE)) {
Triangle t = new Triangle(pt0, pt1, pt2);
result.add(t);
}
}
return result;
}
public Boolean isTriangle(Integer pt1, Integer pt2, Integer pt3) {
System.out.println("Pt1, Pt2, Pt3: " + pt1 + ":" + pt2 + ":" + pt3);
if ((pt1 + pt2) > pt3 && (pt1 + pt3) > pt2 && (pt2 + pt3) > pt1) {
System.out.println("This is triangle");
return Boolean.TRUE;
}
return Boolean.FALSE;
}
public ArrayList<ArrayList<Integer>> getTri(int[] input) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (input.length < 3) {
return result;
}
Arrays.sort(input);
for (int i = 0; i < input.length - 2; i++) {
int k = i + 2;
for (int j = i + 1; j < input.length; j++) {
while (k < input.length && input[i] + input[j] > input[k]) {
ArrayList<Integer> inner = new ArrayList<Integer>();
inner.add(input[i]);
inner.add(input[j]);
inner.add(input[k]);
result.add(inner);
k++;
}
}
}
return result;
}
public void findTriangleW(int[] a) {
HashSet<HashSet<Integer>> triangle = new HashSet<HashSet<Integer>>();
HashSet<Integer> tmp;
for (int i = 0; i < a.length; i++) {
int sum = a[i];
for (int j = 0; j < a.length; j++) {
int first = a[j];
if (first != sum) {
for (int k = 0; k < a.length; k++) {
int sec = a[k];
if (sec != first && sec != sum && (first + sec < sum)) {
tmp = new HashSet<Integer>();
tmp.add(first);
tmp.add(sec);
tmp.add(sum);
triangle.add(tmp);
}
}
}
}
}
for (HashSet<Integer> hs : triangle)
System.out.println(hs);
}
public static void main(String[] args) {
FindTriangle f = new FindTriangle();
List<Integer> points = new ArrayList<Integer>();
points.add(1);
points.add(5);
points.add(10);
points.add(7);
System.out.println("Printing final results");
List<Triangle> result = f.findTriangle(points);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).toString());
}
}
}

Bellman Ford detecting negative cycle of shortest length

Solving this Arbitage problem of UVA http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=40 but I am stuck with finding the negative cycle of shortest length(length here is number of vertices).Here is my code that successfully detects the negative cycle
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class _104 {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String input;
while ((input = reader.readLine()) != null) {
int n = Integer.parseInt(input);
double[][] cost = new double[n + 1][n + 1];
double[] spEstimate = new double[n + 1];
int parent[] = new int[n + 1];
for (int i = 0; i < n + 1; i++) {
spEstimate[i] = Double.MAX_VALUE;
cost[0][i] = 0;
cost[i][0] = Double.MAX_VALUE;
parent[i] = Integer.MAX_VALUE;
}
spEstimate[0] = 0.0;
parent[0] = 0;
for (int i = 1; i < n + 1; i++) {
String[] line = reader.readLine().split("\\s+");
for (int j = 1; j < n + 1; j++) {
if (i == j) {
cost[i][j] = 0;
} else if (i < j) {
cost[i][j] = -(Math
.log(Double.parseDouble(line[j - 2])) / Math
.log(2));
} else {
cost[i][j] = -(Math
.log(Double.parseDouble(line[j - 1])) / Math
.log(2));
}
}
}
int save = 1, s = 1;
boolean flag = BellmanFord(n, cost, spEstimate, parent);
display(cost);
// Relax all edges once more
boolean brk = true;
for (int i = 0; i < cost.length && brk; i++) {
for (int j = 0; j < cost.length && brk; j++) {
//relax(i, j, spEstimate, cost[i][j], parent);
}
}
ArrayList<Integer> path = new ArrayList<Integer>();
while (parent[save] != s) {
path.add(save);
save = parent[save];
}
if (flag) {
System.out.println("no arbitrage sequence exists");
} else {
path.add(0, path.get(path.size() - 1));
for (int i = path.size() - 1; i >= 0; --i) {
System.out.println(path.get(i));
}
}
}
reader.close();
}
public static boolean BellmanFord(int n, double[][] cost, double[] sp,
int[] parent) {
for (int k = 0; k < n - 1; k++) {
for (int i = 0; i < cost.length; i++) {
for (int j = 0; j < cost.length; j++) {
relax(i, j, sp, cost[i][j], parent);
}
}
}
// Relax all edges once more to detect cycle
for (int i = 0; i < cost.length; i++) {
for (int j = 0; j < cost.length; j++) {
if (sp[j] > (sp[i] + cost[i][j])) {
return false;
}
}
}
return true;
}
static void relax(int i, int j, double[] sp, double cij, int[] parent) {
if (sp[j] > (sp[i] + cij)) {
sp[j] = sp[i] + cij;
System.out.println("relaxed " + i + " " + j + " " + cij + " "
+ sp[i] + " " + sp[j]);
parent[j] = i;
}
}
static void display(double[][] cost) {
System.out.println("Display Cost");
for (int i = 0; i < cost.length; i++) {
for (int j = 0; j < cost.length; j++) {
System.out.print(cost[i][j] + "\t");
}
System.out.println();
}
}
static void display(double[] sp) {
for (int i = 0; i < sp.length; i++) {
System.out.println(sp[i]);
}
}
}
You can do it like that:
Fix the start vertex of the cycle(let's call it v).
Run Ford-Bellman algorithm assuming that dist[i] = 0 if i = v and INF otherwise.
If there is a negative cycle that contains v, after k iterations of the outer loop in Ford-Bellman algorithm dist[v] will become negative. So you can easily find such smallest k by simply checking if dist[v] is still non-negative or not after each iteration.
The smallest k among all v is the answer.
It is possible to solve this problem by considering cycles of increasing length as opposed to finding negative cycles as described by kraskevich. The worst case complexity for both approaches is O(n^4). This approach resembles Floyd-Warshall where you consider increasing lengths instead of intermediate vertices.
You can find a detailed explanation that includes diagrams and code here.

Minimize Simplex method

I find topic about Simplex method here Alter Simplex Algorithm to Minimize on objective function NOT maximize
But answer didn`t help. When I change from
double[] variables = { 13.0, 23.0 };
to
double[] variables = { -13.0, -23.0 };
The program dont calculate(no Exception), it print first step and that`s all.
Could somebody help me with alter simplex method from maximize to minimize?
code:
import java.util.*;
public class Simplex
{
private static final double EPSILON = 1.0E-10;
private double[][] tableaux;
private int numOfConstraints;
private int numOfVariables;
private int[] basis;
/**
* Constructor for objects of class Simplex
*/
public Simplex()
{
double[][] thisTableaux = {
{ 5.0, 15.0 },
{ 4.0, 4.0 },
{ 35.0, 20.0 },
};
double[] constraints = { 480.0, 160.0, 1190.0 };
double[] variables = { -13.0, -23.0 };
numOfConstraints = constraints.length;
numOfVariables = variables.length;
tableaux = new double[numOfConstraints+1][numOfVariables+numOfConstraints+1];
//adds all elements from thisTableaux to tableaux
for(int i=0; i < numOfConstraints; i++)
{
for(int j=0; j < numOfVariables; j++)
{
tableaux[i][j] = thisTableaux[i][j];
}
}
//adds a slack variable for each variable there is and sets it to 1.0
for(int i=0; i < numOfConstraints; i++)
{
tableaux[i][numOfVariables+i] = 1.0;
}
//adds variables into the second [] of tableux
for(int j=0; j < numOfVariables; j++)
{
tableaux[numOfConstraints][j] = variables[j];
}
//adds constraints to first [] of tableaux
for(int k=0; k < numOfConstraints; k++)
{
tableaux[k][numOfConstraints+numOfVariables] = constraints[k];
}
basis = new int[numOfConstraints];
for(int i=0; i < numOfConstraints; i++)
{
basis[i] = numOfVariables + i;
}
show();
optimise();
assert check(thisTableaux, constraints, variables);
}
public void optimise() {
while(true) {
int q = findLowestNonBasicCol();
if(q == -1) {
break;
}
int p = getPivotRow(q);
if(p == -1) throw new ArithmeticException("Linear Program Unbounded");
pivot(p, q);
basis[p] = q;
}
}
public int findLowestNonBasicCol() {
for(int i=0; i < numOfConstraints + numOfVariables; i++)
{
if(tableaux[numOfConstraints][i] > 0) {
return i;
}
}
return -1;
}
public int findIndexOfLowestNonBasicCol() {
int q = 0;
for(int i=1; i < numOfConstraints + numOfVariables; i++)
{
if(tableaux[numOfConstraints][i] > tableaux[numOfConstraints][q]) {
q = i;
}
}
if(tableaux[numOfConstraints][q] <= 0) {
return -1;
}
else {
return q;
}
}
/**
* Finds row p which will be the pivot row using the minimum ratio rule.
* -1 if there is no pivot row
*/
public int getPivotRow(int q) {
int p = -1;
for(int i=0; i < numOfConstraints; i++) {
if (tableaux[i][q] <=0) {
continue;
}
else if (p == -1) {
p = i;
}
else if((tableaux[i][numOfConstraints+numOfVariables] / tableaux[i][q] < tableaux[p][numOfConstraints+numOfVariables] / tableaux[p][q])) {
p = i;
}
}
You might want to look into the Dual Simplex Method (or Duality Theory). If the standard form of the primal problem is:
Maximize = 13*X1 + 23*X2;
with constraints:
5*X1 + 15*X2 <= 480;
4*X1 + 4*X2 <= 160;
35*X1 + 20*X2 <= 1190;
X1 >= 0;
X2 >= 0;
Then the dual problem is:
Minimize = 480*Y1 + 160*Y2 + 1190*Y3;
with constraints:
5*Y1 + 4*Y2 + 35*Y3 >= 13;
15*Y1 + 4*Y2 + 20*Y3 >= 23;
Y1 >= 0;
Y2 >= 0;
Y3 >= 0;
I tested both of these problems in LINGO and get the same answer for both (Z = 800, X1 = 12, X2 = 28 -- Y1 = 1, Y2 = 2, Y3 = 0).
I guess the program did nothing because the initial solution is the optimal solution.

How can I discard the largest and smallest numbers when I calculate the arithmetic mean?

My question is about discarding the largest and smallest number when my program calculates an arithmetic mean.
This is my code sample:
public static void main(String[] args) {
int k;
int r;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (r = 0; r < numbers.length; r++) {
result[r] = Integer.parseInt(numbers[r]);
}
for (k = 0; k < result.length; k++) {
System.out.print("");
System.out.println(result[k]);
}
System.out.println(" LargestNumber : " + TheLargestNumber(result));
System.out.println(" SmallestNumber : " + TheSmallestNumber(result));
thelargest = TheLargestNumber(result);
thesmallest = TheSmallestNumber(result);
System.out.println("The Arithmetic Mean : " + AirthmeticMean(result));
}
public static int TheSmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int TheLargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result) {
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
return (float) sum / result.length;
}
I tried to find the way and I wrote this sample but I don't know how to embed this code sample:
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
Will this code sample be helpful to me?
Just before your
System.out.println("The Arithmetic Mean : " + AirthmeticMean(result));
write
thenewmean = (AirthmeticMean(result)*result.length - thesmallest - thelargest)/(result.length-2)
and then print thenewmean
System.out.println("The Arithmetic Mean : " + thenewmean);
You don't need to write your
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
code anywhere. Even then if you wish to use your own code,
then use it in your AirthmeticMean() function
Need to keep track of count as well as sum if removing highest and smallest
public static float AirthmeticMean(int[] result, int theSmallest, int theLargest) {
int sum = 0;
int cnt = 0;
for (int i = 0; i < result.length; i++) {
if (result[i] != theSmallest && result[i] != theLargest) {
sum += result[i];
cnt++;
}
}
return (float) sum / cnt;
}
The code sample you've got:
for (int i = 0; i < result.length; i++) {
if (series[i] != thesmallest && series[i] != thelargest) {
total = total + seriess[i];
}
}
is almost OK. Almost, because you retrieve the length of the array named result in the for-loop and access elements of array series.
You can use this code in the following way. Extend AirthmeticMean with two parameters theSmallest and theLargest and keep track of the number of summed elements:
public static float AirthmeticMean(int[] result, int theSmallest, int theLargest) {
int sum = 0;
int numElements = 0;
for (int i = 0; i < result.length; i++) {
if (result[i] != theSmallest && result[i] != theLargest) {
sum += result[i];
numElements++;
}
}
return (float) sum / numElements;
}
EDIT: added numElements.

Categories

Resources