Code test - Maximize cost for a given weight of a Package - java

You want to send your friend a package with different things. Each thing you put inside the package has such parameters as index number, weight and cost. The package has a weight limit. Your goal is to determine which things to put into the package so that the total weight is less than or equal to the package limit and the total cost is as large as possible.
You would prefer to send a package which weights less in case there is more than one package with the same price.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. The input file contains several lines. Each line is one test case.
Each line contains the weight that the package can take (before the colon) and the list of things you need to choose. Each thing is enclosed in parentheses where the 1st number is a thing's index number, the 2nd is its weight and the 3rd is its cost. Eg:
81 : (1,53.38,45)(2,88.62,98) (3,78.48,3)(4,72.30,76) (5,30.18,9)(6,46.34,48)
8 : (1,15.3,34)
75:(1,85.31,29) (2,14.55,74)(3,3.98,16) (4,26.24,55)(5,63.69,52) (6,76.25,75)(7,60.02,74) (8,93.18,35)(9,89.95,78)
56 : (1,90.72,13)(2,33.80,40) (3,43.15,10)(4,37.97,16) (5,46.81,36)(6,48.77,79) (7,81.80,45)(8,19.36,79) (9,6.76,$64)
OUTPUT SAMPLE:
For each set of things that you put into the package provide a list (items’ index numbers are separated by comma).
E.g.
4 //for package1
- //for package2
2,7 //for package3
8,9 //for package4
CONSTRAINTS:
Max weight that a package can take is ≤ 100 There might be up to 15 items you need to choose from Max weight and cost of an item is ≤ 100
Is there a more elegant and easy to understand solution than https://discuss.codechef.com/questions/104934/package-problemin-java

Here is the code (KnapSack):
public class FriendPackageKnapsack {
public static void parserThings(String[] sub2, List<Package> things,
double maxWeight) {
for (int i = 0; i < sub2.length; i++) {
String[] sub3 = (sub2[i].substring(1, sub2[i].length() - 1)).split(",");
int id = Integer.parseInt(sub3[0]);
double weight = Double.parseDouble(sub3[1]);
double cost = Double.parseDouble(sub3[2].substring(1, sub3[2].length()));
if (weight <= maxWeight) {
Package condidat = new Package(id, weight, cost);
things.add(condidat);
}
}
}
public static String getOptimumFor(List<Package> things, int r, int maxWt) {
int indexSolution = 0;
String returnData = "";
double maxWeight = 0;
double maxCost = 0;
int[] data = new int[r];
List<Integer> res = new ArrayList<Integer>();
int[] arr = new int[things.size()];
for (int i = 0; i < things.size(); i++) {
arr[i] = i;
}
getCombination(arr, data, res, 0, 0);
for (int i = 0; i <= res.size() - r; i += r) {
double someWeight = 0;
double someCost = 0;
for (int j = 0; j < r; j++) {
someWeight += things.get(res.get(i + j)).getWeight();
someCost += things.get(res.get(i + j)).getCost();
}
if (someWeight <= maxWt) {
if ((someCost > maxCost)
|| ((someCost == maxCost) && (someWeight <= maxWeight))) {
indexSolution = i;
maxWeight = someWeight;
maxCost = someCost;
}
}
}
for (int k = indexSolution; k < r + indexSolution; k++) {
returnData += res.get(k) + ",";
}
return returnData + maxCost + "," + maxWeight;
}
public static void getCombination(int[] arr, int[] data, List<Integer> res, int start,
int index) {
if (index == data.length) {
for (int j = 0; j < data.length; j++) { res.add(data[j]); }
return;
}
for (int i = start; i < arr.length && arr.length - i >= data.length - index; i++) {
data[index] = arr[i];
getCombination(arr, data, res, i + 1, index + 1);
}
}
public static void main(String[] args) {
File file = new File("packageproblem.txt");
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) { e.printStackTrace(); }
String line = "";
List<Package> things = new ArrayList<>();
try {
while ((line = in.readLine()) != null) {
String s = "";
// Parsing line
String[] sub1 = line.split(" : ");
int N = Integer.parseInt(sub1[0]);
String[] sub2 = sub1[1].split(" ");
if (sub2.length > 1) {
things.clear();
parserThings(sub2, things, N);
double maxCost = 0;
double maxWeight = 0;
for (int i = 1; i <= things.size(); i++) {
String resultat = getOptimumFor(things, i, N);
// System.out.println(resultat);
String[] sub4 = resultat.split(",");
double cost = Double.parseDouble(sub4[sub4.length - 2]);
double weight = Double.parseDouble(sub4[sub4.length - 1]);
if (cost == maxCost) {
if (weight < maxWeight) {
maxCost = cost;
maxWeight = weight;
s = resultat;
}
}
if (cost > maxCost) {
maxCost = cost;
maxWeight = weight;
s = resultat;
}
}
// System.out.println(s);
String[] sub5 = s.split(",");
String ss = "";
for (int i = 0; i < sub5.length - 2; i++) {
ss += things.get(Integer.parseInt(sub5[i])).getId() + ",";
}
if (ss.equals("")) { System.out.println("-"); }
else { System.out.println(ss.substring(0, ss.length() - 1)); }
}
else { System.out.println("-"); }
}
}
catch (IOException e) { e.printStackTrace(); }
}
}
class Package {
private int id;
private double weight;
private double cost;
public Package(int id, double weight, double cost) {
this.id = id;
this.weight = weight;
this.cost = cost;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weight; }
public double getCost() { return cost; }
public void setCost(double cost) { this.cost = cost; }
}
The code is taken from here.

You can find a full solution of this problem in java here
https://github.com/rantibi/package-challenge

Related

How to stop Java code from repeating last value of object array?

I'm working on a project with a friend; we're trying to create an airplane project using a Passenger class for passengers, Airplane class to add in passengers and create the airplane, and a driver class. We've run into an issue where when we add in all the passengers to the airplane and print all details of the airplane, printed values are capturing only the last passenger's information. We're trying to get this for every passenger. Here is the code:
Passenger
public class Passenger {
private String name;
private int birthYear;
private double weight;
private char gender;
private int numCarryOn;
//Default constructor
public Passenger(){
name = "";
birthYear = 1900;
weight = 0.0;
gender = 'u';
numCarryOn = 0;
}
//Alt default constructor
public Passenger(String newName, int newBirthYear, double newWeight, char newGend, int newNumCarryOn){
this.setName(newName);
this.setBirthYear(newBirthYear);
this.setWeight(newWeight);
this.setGender(newGend);
this.setNumCarryOn(newNumCarryOn);
}
//Calculate age
public int calculateAge(int currentYear){
int age = 0;
if (currentYear < birthYear){
return -1;
}
else {
age = currentYear - birthYear;
}
return age;
}
//Gain weight
public void gainWeight(){
weight += 1;
}
//Gain weight based on input
public void gainWeight(double pounds){
if (weight > 0){
weight = weight + pounds;
}
}
//Get birthYear
public int getBirthYear(){
return birthYear;
}
//Get gender
public char getGender(){
return gender;
}
//Get name
public String getName(){
return name;
}
//Get weight
public double getWeight(){
return weight;
}
//Get numCarryOn
public int getNumCarryOn(){
return numCarryOn;
}
//isFemale
public boolean isFemale(){
if (gender == 'f'){
return true;
}
else {
return false;
}
}
//isMale
public boolean isMale(){
if (gender == 'm'){
return true;
}
else {
return false;
}
}
//loseWeight
public void loseWeight(){
if (weight > 0){
weight -= 1;
}
}
//lose weight by value
public void loseWeight(double weight2lose){
if (weight - weight2lose >= 0){
weight -= weight2lose;
}
}
//print
public void printDetails(){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c | NumCarryOn: %2d\n", name, birthYear, weight, gender, numCarryOn);
}
//setGender
public void setGender(char newGender){
if (newGender == 'f' || newGender == 'm') {
this.gender = newGender;
} else {
this.gender = 'u';
}
}
//setName
public void setName(String newName){
name = newName;
}
//setBirthYear
public void setBirthYear(int newBY){
birthYear = newBY;
}
//setWeight
public void setWeight(double newWeight){
if (newWeight < 0){
weight = -1;
}
else {
weight = newWeight;
}
}
//setNumCarryOn
public void setNumCarryOn(int newNumCarryOn){
if (newNumCarryOn < 0){
numCarryOn = 0;
}
else if (newNumCarryOn > 2){
numCarryOn = 2;
}
else {
numCarryOn = newNumCarryOn;
}
}
}
Airplane
public class Airplane {
private Passenger[] passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with int input
public Airplane(int otherArraySize){
airplaneName = "";
if (otherArraySize < 0){
otherArraySize = 0;
}
passengers = new Passenger[otherArraySize];
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize < 0){
otherArraySize = 0;
}
passengers = new Passenger[otherArraySize];
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
//resize array for new passengers
private void resizePassengerArray(){
passengers = new Passenger[passengers.length * 2];
}
//get a passenger
public Passenger getPassenger(int passengerIndex){
return passengers[passengerIndex];
}
//getNumPassengers
public int getNumPassengers() {
return count;
}
//getFirstPassenger
public Passenger getFirstPassenger(){
return passengers[0];
}
//getLastPassenger
public Passenger getLastPassenger(){
return passengers[passengers.length - 1];
}
//getPassengers**
public Passenger[] getPassengers(){
return passengers;
}
//setAirplaneName
public void setAirplaneName(String newAirplaneName){
airplaneName = newAirplaneName;
}
//printAllDetails
public void printAllDetails(){
System.out.printf("AirplaneName: %20s | Number of Passengers: %4d | Airplane Size: %4d\n", airplaneName, count, passengers.length);
for (int i = 0; i < count; i++){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c\n", passengers[i].getName(), passengers[i].getBirthYear(), passengers[i].getWeight(), passengers[i].getGender());
}
}
//removePassenger
public Passenger removePassenger(int passengerIndex){
if (passengerIndex != passengers.length - 1){
for (int i = passengerIndex; i < passengers.length - 1; i++){
passengers[i] = passengers[i+1];
}
}
return passengers[passengerIndex];
}
//remove all passengers
public void removeAllPassengers(){
passengers = new Passenger[100];
}
//total weight passengers
public double getTotalWeightOfAllPassengers(){
double weight = 0.0;
for (int i = 0; i < passengers.length; i++){
weight += passengers[i].getWeight();
}
return weight;
}
//avg weight passengers
public double getAverageWeightOfAllPassengers(){
double avg = this.getTotalWeightOfAllPassengers() / numPassengers;
return avg;
}
//num elements above weight
public int getNumberOfPassengersAboveWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.length; i++){
if (passengers[i].getWeight() > weight){
sum += 1;
}
}
return sum;
}
//num elements below weight
public int getNumberOfPassengersBelowWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.length; i++){
if (passengers[i].getWeight() < weight){
sum += 1;
}
}
return sum;
}
//increase weight of passengers
public void increaseWeightOfAllPassengers(){
for (int i = 0; i < passengers.length; i++){
passengers[i].gainWeight();
}
}
//increase weight of passengers with weight input
public void increaseWeightOfAllPassengers(double increaseAmount){
for (int i = 0; i < passengers.length; i++){
passengers[i].gainWeight(increaseAmount);
}
}
}
Driver
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.count += 1;
a1.addPassenger(p2);
a1.count += 1;
a1.addPassenger(p3);
a1.count += 1;
a1.addPassenger(p4);
a1.count += 1;
a1.addPassenger(p5);
a1.count += 1;
a1.printAllDetails();
//How it should work starting with name
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Here's a screenshot of the incorrect code:
https://imgur.com/TGc0FQa
The addPassenger() method is overwriting every element in the array:
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
It should just set the one at the next available index, which happens to be count:
public void addPassenger(Passenger a){
passengers[count++] = a;
}
This also gives you better encapsulation, as you don't have to expose and increment count externally.
this
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
Produce every time a Passenger Array full with the same Passenger.
Perhaps this might solve the problem.
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
if((passengers[i-1] !=null)&&((passengers[i] ==null))
{ passengers[i] = a; }
}
}
A better implementation could be with ArrayList
Airplane
public class Airplane {
private ArrayList<Passenger> passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new ArrayList();
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new ArrayList();
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName){
airplaneName = otherAirplaneName;
passengers = new ArrayList();
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
passengers.add(a);
}
//get a passenger
public Passenger getPassenger(int passengerIndex){
return passengers[passengerIndex];
}
//getNumPassengers
public int getNumPassengers() {
return count;
}
//getFirstPassenger
public Passenger getFirstPassenger(){
return passengers.get(0);
}
//getLastPassenger
public Passenger getLastPassenger(){
return passengers.get(passengers.size() - 1);
}
//getPassengers**
public ArrayList<Passenger> getPassengers(){
return passengers;
}
//setAirplaneName
public void setAirplaneName(String newAirplaneName){
airplaneName = newAirplaneName;
}
//printAllDetails
public void printAllDetails(){
System.out.printf("AirplaneName: %20s | Number of Passengers: %4d | Airplane Size: %4d\n", airplaneName, count, passengers.size());
for (int i = 0; i < count; i++){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c\n", passengers.get(i).getName(), passengers[i].get(i).getBirthYear(), passengers[i].get(i).getWeight(), passengers[i].get(i).getGender());
}
}
//removePassenger
public Passenger removePassenger(int passengerIndex){
passengers.remove(passengerIndex);
return passengers.get(passengerIndex);
}
//remove all passengers
public void removeAllPassengers(){
passengers = new ArrayList();
}
//total weight passengers
public double getTotalWeightOfAllPassengers(){
double weight = 0.0;
for (int i = 0; i < passengers.size(); i++){
weight += passengers.get(i).getWeight();
}
return weight;
}
//avg weight passengers
public double getAverageWeightOfAllPassengers(){
double avg = this.getTotalWeightOfAllPassengers() / numPassengers;
return avg;
}
//num elements above weight
public int getNumberOfPassengersAboveWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.size(); i++){
if (passengers.get(i).getWeight() > weight){
sum += 1;
}
}
return sum;
}
//num elements below weight
public int getNumberOfPassengersBelowWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.size(); i++){
if (passengers.get(i).getWeight() < weight){
sum += 1;
}
}
return sum;
}
//increase weight of passengers
public void increaseWeightOfAllPassengers(){
for (int i = 0; i < passengers.size(); i++){
passengers.get(i).gainWeight();
}
}
//increase weight of passengers with weight input
public void increaseWeightOfAllPassengers(double increaseAmount){
for (int i = 0; i < passengers.size(); i++){
passengers.get(i).gainWeight(increaseAmount);
}
}
}
The issue is in the method addPassenger. You are replacing always the first element.
You can fix in this way:
public void addPassenger(Passenger a){
passengers[count] = a;
count++
}
For better implementation, you can remove count and use numPassengers.
Therefore the method becomes:
public void addPassenger(Passenger a){
passengers[numPassengers] = a;
numPassengers++
}
and the main class:
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.addPassenger(p2);
a1.addPassenger(p3);
a1.addPassenger(p4);
a1.addPassenger(p5);
a1.printAllDetails();
//How it should work starting with name
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
For the best implementation, you can use List instead of an array for the field passengers:
private List<Passenger> passengers;
public Airplane(){
airplaneName = "";
passengers = new ArrayList<>();
}
public void addPassenger(Passenger a){
passengers.add(a);
}
You can remove the numPassengers and use size:
public int getNumPassengers() {
return passengers.size();
}

How does the scope of this private method work?

My question is: how can I see the Tuple result in the process method if it was created in the check method? How am I able to use it there, if it was created in a private method?
public class Problem13 {
private Tuple<Integer> costs;
private Tuple<String> names;
private Tuple<Integer> result;
private int budget;
private int minDelta, minCost, totalCost;
public void process(String fileName) {
if (!read(fileName))
return;
if (budget >= totalCost) {
System.out.println("You can buy all items");
return;
}
if (budget < minCost) {
System.out.println("You cannot buy items");
return;
}
minDelta = -1;
int n = costs.getLength();
Set<Integer> interval = new IntegerInterval(0, n - 1);
for (int k = n - 1; k > 0; --k) {
Combinations<Integer> combinations = new Combinations<Integer>(interval, k);
combinations.produce((tuple) -> !check(tuple));
if (minDelta == 0)
break;
}
if (result == null)
System.out.println("No solution found");
else {
int k = result.getLength();
for (int j = 0; j < k; ++j)
System.out.printf("%s ", names.get(result.get(j)));
System.out.printf("(%d)\n", minDelta);
}
}
public static void main(String[] args) {
new Problem13().process("data/input13.txt");
}
private boolean check(Tuple<Integer> tuple) {
int k = tuple.getLength();
int currentCost = 0;
for (int i = 0; i < k; ++i) {
int j = tuple.get(i);
currentCost += costs.get(j);
if (currentCost > budget)
return false;
}
int d = budget - currentCost;
if (minDelta < 0 || d < minDelta) {
minDelta = d;
result = new ArrayTuple<>(k);
for (int i = 0; i < k; ++i)
result.set(i, tuple.get(i));
}
return minDelta == 0;
}
private means private to the class. So Problem13 can see anything defined in that class, whether private, public, protected or package private.
Also, the access modifier of the method only affects who can call it, not where the results can be seen. For instance, if result was defined as a public field, any class (not just Problem13) could see it.
You can find many good breakdowns of access modifiers out there on the Interwebs. Here's one.

Finding shortest path with genetic algorithm

I am trying to develop java program for finding the shortest path with genetic algorithm in weighted graph. I am having difficulties in coding based on this algorithm. Can someone show me sample codes for this problem. Any language is okay. Any information like libraries or others that might be helpful for this problem is also okay. Most important thing right now is to test the time to find the shortest path based on this algorithm and I need to find out before due date for my assignment. So if anyone can help me,please.
I was coding based on java and I have difficulties mostly in cross over and mutation process. And also defining fitness function is also a problem.
Here is a Java example of a shortest path genetic algorithm
package ga;
import java.util.ArrayList;
import java.util.Arrays;
public class GA {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//computation time
long start = System.nanoTime();
//population size
int populationSize = 30;
//Number of Cities
int numCities = 15;
//Mutation rate
double mutationRate = 0.05;
//Crossover Rate
double crossoverRate = 0.8;
//Choose File path or if false randomly created Path
boolean useFile = false;
//Name the file to be used
String fileName = "Data.txt";
//Current Number of Generations
int numberOfGenerations = 0;
//Stop Condition
int stopAt=2500;
//Population
Population pop;
//use GA or Brute Force
boolean GAuse=true;
//Selecting File mode or Random Mode
if (useFile == false) {
pop = new Population(populationSize, numCities, crossoverRate, mutationRate);
} else {
FileReader file = new FileReader(fileName);
numCities=file.getNumCities();
crossoverRate=file.getCrossoverRate();
mutationRate=file.getMutationRate();
populationSize=file.getCities().length;
Path p = new Path(file.getNumCities());
p.setPath(file.getCities());
pop = new Population(populationSize, numCities, p,crossoverRate ,mutationRate );
}
if(GAuse==true){
//Sorting the population from Finess / Evaluating
pop.FitnessOrder();
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
//Start looking for possible solution
while (numberOfGenerations !=stopAt) {
//Select / Crossover
while (pop.Mate() == false);
//Mutate
for (int i = 0; i < pop.getNextGen().length; i++) {
pop.getNextGen()[i].setPath(pop.Mutation(pop.getNextGen()[i].getPath()));
}
//Setting the new Generation to current Generation
pop.setPopulation(pop.getNextGen());
pop.setDone(0);
//Sorting the new population from Finess / Evaluating
pop.FitnessOrder();
//Incremente number of Generations
numberOfGenerations++;
}
//Prints out the fitness of each path
double valor=0;
for (int i = 0; i < pop.getPopulation().length; i++) {
valor += pop.getPopulation()[i].getFitness();
System.out.println("Value of Fitness: "+pop.getPopulation()[i].getFitness()+"%");
}
System.out.println("");
System.out.println("Total Fitness: "+valor+"%");
System.out.println("\n-----------------------------------------------");
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
}
else{//USING BRUTE FORTE METHOD
FileReader file = new FileReader(fileName);
ArrayList<City> cities = new ArrayList<City>();
for (int i = 0; i <file.getNumCities(); i++) {
cities.add(file.getCities()[i]);
}
ArrayList<City> best = new ArrayList<City>();
Permutations permu = new Permutations();
permu.permutations(cities);
System.out.print("The shortest path is: ");
for (int i = 0; i < permu.getBest().size(); i++) {
System.out.print(permu.getBest().get(i).getId()+"("+permu.getBest().get(i).getX()+","+permu.getBest().get(i).getY()+")");
}
System.out.println("");
System.out.println("It would Cost: "+permu.getCost());
}
long elapsedTime = System.nanoTime() - start;
System.out.println("Algorithm took: "+elapsedTime+" nano seconds to find a solution");
}
}
package ga;
import java.util.ArrayList;
public class Permutations {
private int cost=999999;
private ArrayList<City> best;
public void permutations(ArrayList<City> list){
permutations(null, list, null);
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public ArrayList<City> getBest() {
return best;
}
public void setBest(ArrayList<City> best) {
this.best = best;
}
public ArrayList<City> permutations(ArrayList<City> prefix, ArrayList<City> suffix, ArrayList<ArrayList<City>> output){
if(prefix == null)
prefix = new ArrayList<City>();
if(output == null)
output = new ArrayList<ArrayList<City>>();
if(suffix.size() == 1){
ArrayList<City> newElement = new ArrayList<City>(prefix);
newElement.addAll(suffix);
int costNow=cost(newElement);
if(costNow<this.cost){
best=newElement;
this.cost=costNow;
}
return best;
}
for(int i = 0; i < suffix.size(); i++){
ArrayList<City> newPrefix = new ArrayList<City>(prefix);
newPrefix.add(suffix.get(i));
ArrayList<City> newSuffix = new ArrayList<City>(suffix);
newSuffix.remove(i);
permutations(newPrefix,newSuffix,output);
}
return best;
}
public int cost(ArrayList<City> path){
int cost=0;
int i=0;
while(i<path.size()-1){
cost+=path.get(i).distance(path.get(i+1).getX(),path.get(i+1).getY());
i++;
}
cost+=path.get(path.size()-1).distance(path.get(0).getX(), path.get(0).getY());
return cost;
}
}
package ga;
import java.util.Random;
public class Path implements Comparable {
private City [] path;
private int numCities;
private int cost;
private int fitness;
public Path(int numCities) {
this.numCities = numCities;
CreatePath();
cost =0;
calculateCost();
fitness =0;
}
public void calculateCost(){
cost=0;
int i=0;
while(i<numCities-1){
cost+=path[i].distance(path[i+1].getX(),path[i+1].getY());
i++;
}
cost+=path[path.length-1].distance(path[0].getX(), path[0].getY());
}
public int getFitness() {
return fitness;
}
public void setFitness(int fitness) {
this.fitness = fitness;
}
public int getCost() {
return cost;
}
public void setCost(int distance) {
this.cost = distance;
}
/* Overload compareTo method */
public int compareTo(Object obj){
Path tmp = (Path) obj;
if(this.cost < tmp.cost){
return 1;
}
else if(this.cost > tmp.cost){
return -1;
}
else{
return 0;
}
}
public void CreatePath(){
path= new City[numCities];
for (int i = 0; i < path.length; i++) {
path[i]=new City(i,RandomNum(1, 99),RandomNum(1, 99));
}
}
public int RandomNum(int min, int max){
return min+ (new Random()).nextInt(max-min);
}
public City[] getPath() {
return path;
}
public void setPath(City[] path) {
this.path = path;
calculateCost();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
public class FileReader {
private int numCities;
private double mutationRate;
private City[] cities;
private int curLine;
private StringTokenizer st;
private int arrayCount;
private int x, y;
private double crossoverRate;
private String fileName;
public FileReader(String fileName) {
numCities = 0;
mutationRate = 0;
City[] cities = new City[0];
curLine = 1;
arrayCount = 0;
this.fileName=fileName;
read();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
public double getMutationRate() {
return mutationRate;
}
public void setMutationRate(double mutationRate) {
this.mutationRate = mutationRate;
}
public City[] getCities() {
return cities;
}
public void setCities(City[] cities) {
this.cities = cities;
}
public int getCurLine() {
return curLine;
}
public void setCurLine(int curLine) {
this.curLine = curLine;
}
public StringTokenizer getSt() {
return st;
}
public void setSt(StringTokenizer st) {
this.st = st;
}
public int getArrayCount() {
return arrayCount;
}
public void setArrayCount(int arrayCount) {
this.arrayCount = arrayCount;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void read() {
try {
BufferedReader in = new BufferedReader(new java.io.FileReader("./"+fileName));
String line;
try {
while ((line = in.readLine()) != null) {
if (curLine == 1) {
st = new StringTokenizer(line, "=");
st.nextToken();
numCities = Integer.parseInt(st.nextToken());
cities = new City[numCities];
} else if (curLine == 2) {
st = new StringTokenizer(line, "=");
st.nextToken();
mutationRate = Double.parseDouble(st.nextToken());
}else if(curLine==3){
st = new StringTokenizer(line, "=");
st.nextToken();
crossoverRate = Double.parseDouble(st.nextToken());
}
else {
st = new StringTokenizer(line, "|");
st.nextToken();
String a = st.nextToken();
StringTokenizer stmp = new StringTokenizer(a, "=");
stmp.nextToken();
x = Integer.parseInt(stmp.nextToken());
String l = st.nextToken();
stmp = new StringTokenizer(l, "=");
stmp.nextToken();
y = Integer.parseInt(stmp.nextToken());
cities[arrayCount] = new City(arrayCount, x, y);
arrayCount++;
}
curLine++;
}
} catch (Exception e) {
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!");
}
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRate) {
this.crossoverRate = crossoverRate;
}
}
package ga;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Population {
private int populationSize;
private int numCities;
private Path[] population;
private double crossoverRate;
private City[] child1;
private City[] child2;
private double mutationRate;
private Path[] nextGen;
private int done;
public Population(int populationSize, int numCities, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
population = new Path[populationSize];
this.crossoverRate = crossoverRage;
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
Path p = new Path(numCities);
done = 0;
CreatePopulation(p);
}
public Population(int populationSize, int numCities, Path path, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
this.crossoverRate = crossoverRage;
population = new Path[populationSize];
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
done = 0;
CreatePopulation(path);
}
public void CreatePopulation(Path p) {
int i = 0;
while (i < populationSize) {
City[] tmpCity = new City[numCities];
for (int j = 0; j < tmpCity.length; j++) {
tmpCity[j] = p.getPath()[j];
}
Collections.shuffle(Arrays.asList(tmpCity));
Path tmpPath = new Path(numCities);
tmpPath.setPath(tmpCity);
population[i] = tmpPath;
i++;
}
}
public int SelectParent() {
int total = 0;
//Selecting parents
int totalCost = calculateTotalFitness();
int fit = RandomNum(0, totalCost);
int value = 0;
for (int i = 0; i < population.length; i++) {
value += population[i].getFitness();
if (fit <= value) {
return i;
}//if(fit<=value){
}
return -1;
}
public boolean Mate() {
//Generate a random number to check if the parents cross
int check = RandomNum(0, 100);
int parent1 = SelectParent();
int parent2 = SelectParent();
while (parent1 == parent2) {
parent2 = SelectParent();
}
//check if there is going to be a crossover
if (check <= (crossoverRate * 100)) {
int crossoverPoint = RandomNum(0, population[parent1].getPath().length - 1);
child1 = new City[numCities];
child2 = new City[numCities];
//crossing over
for (int i = 0; i < crossoverPoint; i++) {
child1[i] = population[parent2].getPath()[i];
child2[i] = population[parent1].getPath()[i];
}
for (int i = crossoverPoint; i < numCities; i++) {
child1[i] = population[parent1].getPath()[i];
child2[i] = population[parent2].getPath()[i];
}
//Rearrange childs considering city repetition
int cityChild1;
int cityChild2;
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < crossoverPoint; i++) {
cityChild1 = child1[i].getId();
cityChild2 = child2[i].getId();
//Get the positions of repeated values
for (int j = crossoverPoint; j < numCities; j++) {
if (cityChild1 == child1[j].getId()) {
list1.add(j);
}
if (cityChild2 == child2[j].getId()) {
list2.add(j);
}
}
}
//Find the missing values
for (int i = 0; i < numCities; i++) {
boolean found = false;
//Fixing Child1
for (int j = 0; j < numCities; j++) {
if (population[parent2].getPath()[i] == child1[j]) {
found = true;
break;
}
}
if (found == false) {
child1[list1.remove(list1.size() - 1)] = population[parent2].getPath()[i];
}
found = false;
//Fixing Child2
for (int j = 0; j < numCities; j++) {
if (population[parent1].getPath()[i] == child2[j]) {
found = true;
break;
}
}
if (found == false) {
child2[list2.remove(list2.size() - 1)] = population[parent1].getPath()[i];
}
}
// System.out.print("Parent 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent1].getPath()[i].getId() + " ");
// }
// System.out.print("\nParent 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent2].getPath()[i].getId() + " ");
// }
// System.out.print("\nChild 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child1[i].getId() + " ");
// }
// System.out.print("\nChild 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child2[i].getId() + " ");
// }
// System.out.println("");
//
// //Repeated Values
// for (int i = 0; i < list1.size(); i++) {
// System.out.print(list1.get(i) + " ");
// }
// System.out.println("");
// for (int i = 0; i < list2.size(); i++) {
// System.out.print(list2.get(i) + " ");
// }
if (AddToGenerationCheckFull(child1, child2) == false) {
return false;
} else {
return true;
}
} else {
if (AddToGenerationCheckFull(population[parent1].getPath(), population[parent1].getPath()) == false) {
return false;
} else {
return true;
}
}
}
public int getDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
public boolean AddToGenerationCheckFull(City[] child1, City[] child2) {
if (done == populationSize) {
return true;
}
Path newGenChild1 = new Path(numCities);
Path newGenChild2 = new Path(numCities);
newGenChild1.setPath(child1);
newGenChild2.setPath(child2);
if (done < populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
this.done += 2;
return false;
} else if (done == populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
done += 2;
return true;
} else {
this.nextGen[done] = newGenChild1;
done += 1;
return true;
}
}
public Path[] getNextGen() {
return nextGen;
}
public void setNextGen(Path[] nextGen) {
this.nextGen = nextGen;
}
public City[] Mutation(City[] child) {
int check = RandomNum(0, 100);
//Checks if its going to mutate
if (check <= (mutationRate * 100)) {
//finds the 2 cities that "mutate"
int point1 = RandomNum(0, numCities - 1);
int point2 = RandomNum(0, numCities - 1);
while (point2 == point1) {
point2 = RandomNum(0, numCities - 1);
}
//Cities are switched as result of mutation
City city1 = child[point1];
City city2 = child[point2];
child[point1] = city2;
child[point2] = city1;
}
return child;
}
public int RandomNum(int min, int max) {
return min + (new Random()).nextInt(max - min);
}
public void FitnessOrder() {
Arrays.sort(population);
// double cost = calculateTotalCost();
for (int i = 0; i < population.length; i++) {
// double total = cost - population[i].getCost();
// double fitness = (total * 100) / cost;
// fitness = 100 - fitness;
// population[i].setFitness(fitness);
int lol = 100000 / (population[i].getCost() + 1);
population[i].setFitness(lol);
// System.out.println("Total: "+total + " "+" Cost: "+cost+" "+" Fitness: "+fitness+"%" );
}
}
public int calculateTotalFitness() {
int cost = 0;
for (int i = 0; i < population.length; i++) {
cost += population[i].getFitness();
}
return cost;
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRage) {
this.crossoverRate = crossoverRage;
}
public Path[] getPopulation() {
return population;
}
public void setPopulation(Path[] population) {
this.population = population;
}
public int getPopulationSize() {
return populationSize;
}
public void setPopulationSize(int populationSize) {
this.populationSize = populationSize;
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
public class City {
private int x;
private int y;
private int id;
public City(int id,int x, int y){
this.x=x;
this.y=y;
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int distance(int xOther,int yOther){
return (int) Math.sqrt(((this.x-xOther)*(this.x-xOther))+((this.y-yOther)*(this.y-yOther)));
}
}

implementing Subset Sum with genetic Algorithm

import java.util.Collections;
import java.util.Vector;
public class Metaheuristic {
private static int[] DATA;
private static int NUM_CHROMOSOMES ;
private static int MAX_POWER;
private static int MAX_NUMBER;
private static int FITNESS_THRESHOLD;
private static float MUTATE = (float) .05;
private Vector population;
private boolean done = true;
int numRuns = 0;
public void GeneticAlgorithm (int[] data, int target, int n){
NUM_CHROMOSOMES = n;
MAX_POWER = data.length;
MAX_NUMBER = (int) Math.pow(2, MAX_POWER) - 1;
FITNESS_THRESHOLD = target;
DATA = new int[data.length];
DATA = data;
Metaheuristic s = new Metaheuristic();
s.start();
//System.out.println("s");
}
public Metaheuristic(){
generateRandomPopulation();
}
private void generateRandomPopulation(){
System.out.println("***Randomly Generating population with: " + NUM_CHROMOSOMES + " Chromosome(s)***");
population = new Vector();
for(int i = 0; i < NUM_CHROMOSOMES; ++i){
int randomValue = (int) (Math.random()*MAX_NUMBER);
population.add(new Chromosome(randomValue, MAX_POWER));
}
System.out.println("First Population: " + population +"\n");
}
public void start(){
Collections.sort(population);
Chromosome fitess = (Chromosome) population.lastElement();
done = fitess.fitness(DATA, FITNESS_THRESHOLD) >= MAX_POWER? true:false;
if(done){
System.out.println("DONE, solution found: " + fitess);
}
else{
numRuns++;
System.out.println("FITESS: " + fitess + " fitness: " + fitess.fitness(DATA, FITNESS_THRESHOLD ));
generateNewPopulation();
start();
}
}
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Vector temp = new Vector();
for(int i = 0; i < population.size()/2; ++i){
Chromosome p1 = selectParent();
Chromosome p2 = selectParent();
temp.add(cross1(p1, p2));
temp.add(cross2(p1, p2));
}
population.clear();
population.addAll(temp);
System.out.println("New Population: " + population + "\n");
}
private Chromosome selectParent(){
int delta = population.size();
delta = NUM_CHROMOSOMES - NUM_CHROMOSOMES/2;
int num = (int) (Math.random()*10 + 1);
int index;
if(num >= 4){
index = (int) (Math.random()*delta + NUM_CHROMOSOMES/2);
}
else{
index = (int) (Math.random()*delta);
}
return (Chromosome) population.get(index);
}
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS1.substring(0, length/2) + bitS2.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS2.substring(0, length/2) + bitS1.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private boolean shouldMutate(){
double num = Math.random();
int number = (int) (num*100);
num = (double) number/100;
return (num <= MUTATE);
}
private void mutate(Chromosome offspring){
String s = offspring.getBitString();
int num = s.length();
int index = (int) (Math.random()*num);
String newBit = flip(s.substring(index, index+1));
String newBitString = s.substring(0, index) + newBit + s.substring(index+1, s.length());
offspring.setBitString(newBitString);
}
private String flip(String s){
return s.equals("0")? "1":"0";
}
public static void main(String[] args) {
double average = 0;
int sum = 0;
for(int i = 0; i < 10; ++i){
Metaheuristic s = new Metaheuristic();
s.start();
sum = sum + s.numRuns;
average = (double) sum / (double)(i+1);
System.out.println("Number of runs: " + s.numRuns);
}
System.out.println("average runs: " + average);
}
}
import java.lang.Comparable;
public class Chromosome implements Comparable{
protected String bitString;
public static int[] DATA;
public int TARGET;
public Chromosome(){
}
public Chromosome(int value, int length){
bitString = convertIntToBitString(value, length);
}
public void setBitString(String s){
bitString = s;
}
public String getBitString(){
return bitString;
}
public int compareTo(Object o) {
Chromosome c = (Chromosome) o;
int num = countOnes(this.bitString) - countOnes(c.getBitString());
return num;
}
public int fitness(int[] data, int target){
DATA = new int[data.length];
System.arraycopy(data, 0, DATA, 0, data.length);
TARGET = target;
return countOnes(bitString);
}
public boolean equals(Object o){
if(o instanceof Chromosome){
Chromosome c = (Chromosome) o;
return c.getBitString().equals(bitString);
}
return false;
}
public int hashCode(){
return bitString.hashCode();
}
public String toString(){
return "Chromosome: " + bitString;
}
public static int countOnes(String bits){
int sum = 0;
for(int i = 0; i < bits.length(); ++ i){
String test = bits.substring(i, i+1);
sum = sum + (DATA[i]*Integer.parseInt(test));
}
return sum;
}
public static String convertIntToBitString(int val, int length){
int reval = val;
StringBuffer bitString = new StringBuffer(length);
for(int i = length-1; i >=0; --i ){
if( reval - (Math.pow(2, i)) >= 0 ){
bitString.append("1");
reval = (int) (reval - Math.pow(2, i));
}
else{
bitString.append("0");
}
}
return bitString.toString();
}
/* public static void main(String[] args){
//System.out.println(convertIntToBitString(2046, 10));
Chromosome c = new Chromosome(1234, 10);
System.out.println(c.fitness());
}*/
}
My fitness function is f(x ) = s · (C − P(x )) + (1 − s) · P(x ) in which C is my target value to reach and P(*x ) = (Sigma) wixi, where wi is the element's set and xi is 0 or 1 (the element is chosen or not). also s is 0 or 1, depends on p(x) value. please help me to write this fitness.
I have just tried it but the program run with errors.
You have several problems in your code, and obviously you didn't debug it. Here are some tips though.
First NUM_CHROMOSOMES is 0, because it's an uninitialized field (of the GeneticAlgorithm which you don't use).
Since NUM_CHROMOSOMES is 0, this for loop is useless:
for (int i = 0; i < NUM_CHROMOSOMES; ++i) {
Then, this line:
int randomValue = (int) (Math.random() * MAX_NUMBER);
Since MAX_NUMBER is never manually initialized (same as NUM_CHROMOSOMES, its value is 0, and so is randomValue.
Anyway, population is empty and since you don't test for emptyness, this line:
Chromosome fitess = (Chromosome) population.lastElement();
... throws an exception, because there is no such thing as a last element in your empty population Vector.
As a side note, StringBuffer, Vector are obsolete classes, and you never need to import Comparable, since it belongs to the java.lang package.

Making a Program that Reads and Writes Data - Then Computes Min, Max, Average

I'm making a program that reads some data from a text file and then takes that data and finds the minimum, maximum, and average of the numbers. For some reason I'm getting a lot of ridiculous errors I've never seen before. Here is my code:
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class Lab1 {
static int count = 0;
static int[] newData2 = new int[count];
// Method for reading the data and putting it into different arrays
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
}
static int min(int[] newData2) {
int min = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] < min) {
min = newData2[i];
}
}
return min;
}
static int max(int[] newData2) {
int max = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] > max) {
max = newData2[i];
}
}
return max;
}
static double average(int[] newData2) {
double average = 0;
int sum = 0;
for (int i = 0; i < newData2.length; i++) {
sum = newData2[i];
}
average = sum / newData2.length;
return average;
}
/*
* static int stddev(int[] newData2) { int[] avgDif = new
* int[newData2.length]; for(int i = 0; i < newData2.length; i++) {
* avgDif[i] = (int) (average(newData2) - newData2[i]); }
*
* }
*/
void write(String newdata, int min, int max, double average, int stddev) {
try {
File file = new File("stats.txt");
file.createNewFile();
FileWriter writer = new FileWriter("stats.txt");
writer.write("Minimum: " + min + "Maximum: " + max + "Average: " + average);
writer.close();
}catch(Exception e) {
System.out.println("Unable to write to the file.");
}
public static void main(String[] args) {
}
}
}
I have an error in my readData method, and it tells me that:
This method must return a result type of int[].
I'm literally returning an int array so I don't understand what the problem here is.
Then in my main method it says void is an invalid type for the variable main.
Here are some pointers:
each exit point of a method returning something must return something, if the line new Scanner(f); throws an exception, the first return is not reached, so you need a default one, like this:
private int[] readData() {
File f = new File("data.txt");
int count = 0;
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt(); // maybe you should handle the case where your input is too large for the array "newData"
}
return Arrays.copyOf(newData, count);
} catch (Exception e) {
System.out.println("Could not read the file.");
}
return null;
}
To reduce the size of an array, you should use Arrays.copyOf (see below)
You should avoid static fields (and in your case none are required)
Your method min and max are assuming there are elements in the array (at least one), you should not do that (or test it with an if):
private int min(int[] data) {
int min = Integer.MAX_VALUE; // handy constant :)
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
private int max(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
In your average method there are a few mistakes:
private double average(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i]; // here if you want a sum it's += not =
}
return (1.0 * sum) / data.length; // you want a double division, local "average" was useless
}
arrays are iterables so you can use "new style" for loops:
for (int value : newData) {
// use value
}
Some reading:
Java Integer division: How do you produce a double?
“Missing return statement” within if / for / while
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
//TODO: return something here if there is some kind of error
}
Because of the try-catch block you need to account for every possibility that could occur. When you return the array when the program succeeds you are expecting a return, but when there is an exception the program still expects a return value, but you did not provide one.

Categories