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();
}
Related
There is a code for the BigestCountries class.
It consists of 2 arrays:
private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";
private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;
public String[] getCountriesFoundedBetween(int min, int max){
int countriesMatched;
countriesMatched = 0;
String[] countriesFoundedBetween;
if(biggestCountries == null || biggestCountries.length == 0){
return null;
}
for(int i = 0; i < biggestCountries.length; i++){
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
countriesMatched++;
}
}
if(countriesMatched > 0){
countriesFoundedBetween = new String[countriesMatched];
} else {
return null;
}
for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES
String countryMatched = null;
System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?
countryMatched = biggestCountries[i][COUNTRY_NAME];
countriesFoundedBetween[j] = countryMatched;
System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);
}
}
}
return countriesFoundedBetween;
}
Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.
The method getCountriesFoundedBetween() can be implemented differently, without the need for nested loops, as follows.
private static String[] getCountriesFoundedBetween(int min, int max) {
if (max < min) {
throw new IllegalArgumentException("'max' less than 'min'");
}
String[] countriesFoundedBetween;
int countriesMatched = 0;
int[] indexes = new int[biggestCountries.length];
if (biggestCountries != null && biggestCountries.length > 0) {
for (int i = 0; i < biggestCountries.length; i++) {
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
indexes[countriesMatched++] = i;
}
}
countriesFoundedBetween = new String[countriesMatched];
for (int i = 0; i < countriesMatched; i++) {
countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
}
}
else {
countriesFoundedBetween = new String[0];
}
return countriesFoundedBetween;
}
The above code also returns an empty array rather than null which is preferable for methods that return arrays.
Here is a complete example using population to determine the biggest countries.
public class Countrys {
private static final int CHINA = 0;
private static final int INDIA = 1;
private static final int U_S_A = 2;
private static final int INDONESIA = 3;
private static final int PAKISTAN = 4;
private static final int BRAZIL = 5;
private static final int NIGERIA = 6;
private static final int BANGLADESH = 7;
private static final int RUSSIA = 8;
private static final int MEXICO = 9;
private static final int COUNTRY_NAME = 0;
private static final int COUNTRY_CONTINENT = 1;
private static final int COUNTRY_POPULATION = 0;
private static final int COUNTRY_AGE_FOUNDED = 1;
private static int[][] countryData = new int[][]{{1_427_647_786, 1949},
{1_352_642_280, 1950},
{ 328_239_523, 1776},
{ 273_523_615, 1945},
{ 220_892_340, 1947},
{ 210_147_125, 1889},
{ 206_139_589, 1960},
{ 164_689_383, 1971},
{ 144_384_244, 1991},
{ 128_932_753, 1810}};
private static String[][] biggestCountries = new String[][]{{"China" , "Asia"},
{"India" , "Asia"},
{"U.S.A." , "North America"},
{"Indonesia" , "Asia"},
{"Pakistan" , "Asia"},
{"Brazil" , "South America"},
{"Nigeria" , "Africa"},
{"Bangladesh", "Asia"},
{"Russia" , "Europe"},
{"Mexico" , "North America"}};
private static String[] getCountriesFoundedBetween(int min, int max) {
if (max < min) {
throw new IllegalArgumentException("'max' less than 'min'");
}
String[] countriesFoundedBetween;
int countriesMatched = 0;
int[] indexes = new int[biggestCountries.length];
if (biggestCountries != null && biggestCountries.length > 0) {
for (int i = 0; i < biggestCountries.length; i++) {
if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
indexes[countriesMatched++] = i;
}
}
countriesFoundedBetween = new String[countriesMatched];
for (int i = 0; i < countriesMatched; i++) {
countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
}
}
else {
countriesFoundedBetween = new String[0];
}
return countriesFoundedBetween;
}
public static void main(String[] args) {
String[] result = getCountriesFoundedBetween(1950, 1980);
System.out.println(Arrays.toString(result));
}
}
Running the above code produces the following output:
[India, Nigeria, Bangladesh]
If you name a Class BigestCountries still it has an attribute biggestCountries which is an array, holds information about biggest countries, I think you are not utilizing the potential of OO.
You can use Class to represent the data of a Country. With data encapsulation, you can get rid of nested array thus nested loop and control flow statement (break, continue etc), lookup index constant, keep sync-ing the index between biggestCountries and countryData etc.
Your code doing the same task twice. The first loop count the matched country and initialize a array. The second loop actually put the matched country name to the array.
Java collection framework provide data structure with dynamic size. I use ArrayList here
I think ageFound should be named yearFound?
Refactored Your code
Country.java
public class Country {
private String name;
private int population;
private int yearFound;
private String continent;
public Country(String name, String continent, int year, int population) {
this.name = name;
this.population = population;
this.continent = continent;
this.yearFound = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public int getYearFound() {
return yearFound;
}
public void setYearFound(int yearFound) {
this.yearFound = yearFound;
}
#Override
public String toString() {
return "Country [name=" + name + ", population=" + population + ", yearFound=" + yearFound + ", continent="
+ continent + "]";
}
}
BiggestCountries.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BiggestCountries {
private List<Country> countries = new ArrayList<Country>() {
{
add(new Country("China", "Asia", 1949, 1433783686));
add(new Country("Canada", "North America", 1867, 37590000));
add(new Country("United States", "North America", 1776, 328200000));
}
};
public List<Country> getCountriesFoundedBetween(int min, int max) {
List<Country> matchedCountry = new ArrayList<Country>();
Iterator<Country> itrCoutnry = countries.iterator();
while (itrCoutnry.hasNext()) {
Country country = itrCoutnry.next();
int yearFound = country.getYearFound();
if (min < yearFound && max > yearFound) {
matchedCountry.add(country);
}
}
return matchedCountry;
}
}
Test Run
public static void main(String[] args) {
List<Country> matchedCountries = new BiggestCountries().getCountriesFoundedBetween(1700, 1899);
System.out.println(matchedCountries);
}
Result
[Country [name=Canada, population=37590000, yearFound=1867, continent=North America], Country [name=United States, population=328200000, yearFound=1776, continent=North America]]
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)));
}
}
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
I'm trying to send a one D array to a class. I want the mutator method to copy the array, save it and then send it back to my tester class...so far I keep getting errors from the compiler. I know how to write a method that copies the array in main but I can't seem to get it done with the class though. Here is the code:
public class Class1D {
private int degree;
private int [] coefficient;
public Class1D(int degree){
this.degree =degree;
}
public void setCoefficent( int[] a, int degree){
this.coefficient[degree] = a[degree];
for ( int i=0; i<=a.length-1; i++)
{
this.coefficient[i] = a[i];
}
}
public int [] getCoefficient() {
return coefficient;
}
}
import javax.swing.JOptionPane;
public class copy1D{
public static void main(String[]args)
{
String input;
int degree;
input = JOptionPane.showInputDialog(" what is the degree of the polynomial?");
degree = Integer.parseInt(input);
degree= degree+1;
int [] array = new int[degree];
for ( int i =0; i<=array.length-1; i++)
{
input = JOptionPane.showInputDialog(" Enter coefficients:");
array[i] = Integer.parseInt(input);
}
for ( int i =0; i<=array.length-1; i++)
{
System.out.print(array[i] + " ");
}
Class1D array2 = new Class1D(degree);
}
}
}
You should send the a array to the constructor of Class1D and set it to your member variable as follows:
public Class1D(int degree, int[] a){
this.degree =degree;
this.coefficient = a.clone();
// You can also another way that is faster, use:
// System.arraycopy(a, 0, this.coefficient, 0, a.length);
}
And your call to the construction will be:
Class1D c1d = new Class1D(degree, array);
import javax.swing.JOptionPane;
public class copy1D{
public static void main(String[]args)
{
String input;
int degree;
input = JOptionPane.showInputDialog(" what is the degree of the polynomial?");
degree = Integer.parseInt(input);
degree= degree+1;
int [] array = new int[degree];
for ( int i =0; i<=array.length-1; i++)
{
input = JOptionPane.showInputDialog(" Enter coefficients:");
array[i] = Integer.parseInt(input);
}
for ( int i =0; i<=array.length-1; i++)
{
System.out.print(array[i] + " ");
}
makecopy(array,degree);
Class1D c1d = new Class1D(degree, array);
}
public static void makecopy(int[]a, int deg)
{
int [] b = new int [deg];
for ( int i =0; i<=a.length-1; i++)
{
b[i] = a[i];
}
System.out.println(" I have copied the array ");
for ( int i =0; i<=a.length-1; i++)
{
System.out.print(b[i]+ " ");
}
}
}
public class Class1D {
private int degree;
private int [] coefficient;
public Class1D(int degree){
this.degree =degree;
}
public Class1D(int degree, int[] a){
this.degree =degree;
this.coefficient = a.clone();
}
public int []getCoefficient() {
return coefficient;
}
}
Have to find both max and min in a set of data of a team's field goal percentage.
import java.io.*;
import java.util.Scanner;
public class kstatebball
{
public static void main(String [] args)
throws FileNotFoundException
{
Scanner in = new Scanner(new File("data1.txt"));
String[] firstname = new String [100];
String[] lastname = new String [100];
int fgm[] = new int [100];
int fga[] = new int [100];
double fgp = 0;
int maxFGP;
int minFGP;
System.out.print(" Player FGM FGA FGP%\n");
int count = 0;
for( int i = 0;in.hasNext(); i++)
{
firstname[i] = in.next();
lastname[i] = in.next();
fgm[i] = in.nextInt();
fga[i] = in.nextInt();
fgp = (1.0 * fgm[i]) / (1.0 * fga[i]) * 100;
count++;
System.out.printf("%10s %10s %3d %3d %3.1f \n",firstname[i],lastname[i],fgm[i],fga[i],fgp);
}
maxFGP = maxFGP(fgm,fga,count);
minFGP = minFGP(fgm,fga,count);
System.out.printf("\n\nThe player with the highest field goal percentage is: %3d ",maxFGP(fgm,fga,count));
System.out.printf("\nThe player with the lowest field goal percentage is : %3.1f",fgp);
}
public static int maxFGP(int[] fgm, int[] fga, int count)
{
int max = 0;
for(int i = 0; i < count; i++)
{
if((1.0 * fgm[i]) / (1.0 * fga[i]) * 100 > max)
max = i;
}
return max;
}
public static int minFGP(int[]fgm, int[]fga, int count)
{
int min = 0;
for(int i = 0; i > 13; i++)
{
if(fgm[i] > fgm[count])
count = i;
}
return min;
}
}
Need help with the "if" statement for it to return the correct max.
We have our percentages for all of the players, but need to use the methods in order to find the player with the greatest field goal percentage and also the lowest.
Here's the data file I am using:
Marcus Foster 123 288
Thomas Gipson 102 178
Shane Southwell 88 224
Will Spradling 58 144
Wesley Iwundu 53 111
Nino Williams 49 96
Nigel Johnson 28 80
Jevon Thomas 15 58
D.J. Johnson 34 68
Omari Lawrence 27 65
Shawn Meyer 2 4
Ryan Schultz 2 9
Jack Karapetyan 1 4
Brian Rohleder 1 2
Should be like this:
public static int maxFGP(int[] fgm, int[] fga, int count)
{
int max = 0;
double maxValue=(1.0 * fgm[0]) / (1.0 * fga[0]) * 100;
for(int i = 0; i < count; i++)
{
if((1.0 * fgm[i]) / (1.0 * fga[i]) * 100 > maxValue)
{
max = i;
maxValue=(1.0 * fgm[i]) / (1.0 * fga[i]) * 100;
}
}
return max;
}
note: you already set int max = 0; so no need to loop from i=0. change int i=1 instead
To print the name of the player with max value:
System.out.printf("\n\nThe player with the highest field goal percentage is: %3d ",firstname[maxFGP(fgm,fga,count)]);
max is an array index, I would suggest you add another another method to calculate the percentage
public static int maxFGP(int[] fgm, int[] fga, int count)
{
int max = 0;
for(int i = 1; i < count; i++){
if(fieldGoalPercentage(fgm, fga, i) > fieldGoalPercentage(fgm, fga, max))
max = i;
}
return max;
}
Java's an object oriented language. You're probably a beginner, but here's another way to think about it.
Start with a Player object:
package misc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* misc.Player
* #author Michael
* #link http://stackoverflow.com/questions/21843505/calculating-max-field-goal-percentage-in-a-method-in-java-program
* #since 2/17/14 10:07 PM
*/
public class Player {
private final String firstName;
private final String lastName;
private final int numAttempts;
private final int numMakes;
public static void main(String[] args) {
List<Player> team = new ArrayList<Player>() {{
add(new Player("Larry", "Bird", 40, 80));
add(new Player("Robert", "Parish", 4, 10));
add(new Player("Dennis", "Johnson", 35, 50));
}};
System.out.println("before sort: " + team);
Collections.sort(team, new Comparator<Player>() {
#Override
public int compare(Player that, Player other) {
if (that.getFieldGoalPercentage() < other.getFieldGoalPercentage()) {
return -1;
} else if (that.getFieldGoalPercentage() > other.getFieldGoalPercentage()) {
return +1;
} else {
return 0;
}
}
});
System.out.println("after sort: " + team);
}
public Player(String firstName, String lastName, int numMakes, int numAttempts) {
this.firstName = (isBlank(firstName) ? "" : firstName);
this.lastName = (isBlank(lastName) ? "" : lastName);
this.numAttempts = (numAttempts < 0 ? 0 : numAttempts);
this.numMakes = (numMakes < 0 ? 0 : numMakes);
if (this.numMakes > this.numAttempts) {
throw new IllegalArgumentException(String.format("number of makes %d cannot exceed number of attempts %d", numMakes, numAttempts));
}
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getNumAttempts() {
return numAttempts;
}
public int getNumMakes() {
return numMakes;
}
public double getFieldGoalPercentage() {
double fieldGoalPercentage = 0.0;
if (this.numAttempts > 0) {
fieldGoalPercentage = ((double) numMakes)/numAttempts;
}
return fieldGoalPercentage;
}
public static boolean isBlank(String s) {
return ((s == null) || (s.trim().length() == 0));
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
return firstName.equals(player.firstName) && lastName.equals(player.lastName);
}
#Override
public int hashCode() {
int result = firstName.hashCode();
result = 31 * result + lastName.hashCode();
return result;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("misc.Player{");
sb.append("firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", numAttempts=").append(numAttempts);
sb.append(", numMakes=").append(numMakes);
sb.append(", percentage=").append(getFieldGoalPercentage());
sb.append('}');
return sb.toString();
}
}