I need help creating this program

• 04-21-2010, 08:32 PM
LostinJavaLand
I need help creating this program
I am stuck in programming this last project for java 1 class.
Here is the assignment:

Part I: Print out the two arrays: (Be sure to do this first)
Anne 30
Bob 150
Ralph 305
Tim 225
Barbara 135
Jane 160
Steve 80
Tom 200
Mike 165
Shirley 90
Pam 100
Frank 120

Part II: The elevators in our building have an 1100 lb. load limit. Determine which people in the list above get on the elevator. Print their names, weights, total weight, and how many got on.

Part III: Rearrange these people in ascending sequence by weight and print the two arrays. Determine again how many may ride the elevator, printing out their names, weights, total weight and the number of how many people got on.

Part IV: Rearrange these people in ascending sequence by name (USE A DIFFERENT SORT ALGORITHM THAN THE ONE YOU USED IN PART II) and print the two arrays. Determine again how many may ride the elevator, printing out their names, weights, total weight and the number of how many people got on.

Part V: Have the program determine which method allowed the most people to get on the elevator.

I have made multiple classes, but I am completely lost of what to do next.
public class Person
{
private String name;
private int weight;

//default
public Person()
{
name = "";
weight = 0;
}

public Person(String n, int w)
{
name = n;
weight = w;
}
public String getName()
{
return name;
}
public int getWeight()
{
return weight;
}
public void setName(String n)
{
name = n;
}

public void setWeight(int w)
{
weight = w;
}

public String toString()
{
return name + "is " + weight + " pounds.";
}
}
my second class
public class People
{
private Person[] elev;
private int count;

public People(int size)
{
elev = new people[size];
count = 0;
}
{
elev[count] = x;
count++;
}
if list.i.getName()compareTo
public String toString()
{
String out ="";
for (int i=0; i<count; i++)
out+= (i + ":\t" + elev[i]);
return out;
}
}

and my main
import java.util.Scanner;
import java.io.*;

public class Elevator
{
public static void main (String[] args) throw IOException
{
Scanner scan = new Scanner(new File("elevData.txt"));
int s = scan.nextInt();
People holder = new People(s);

do
{
}
while(scan.hasNext());

System.out.println("The array is " + holder);

}
}
Any help would be much appreciated.
• 04-21-2010, 09:32 PM
gcalvin
Please use CODE tags when posting code.

I like your thinking, but the assignment says "two arrays" and not one array of Person objects. I'd probably still do it your way, if you think you can get away with it.

"elev" is a bad name for your array variable in your People class. Just call it "people" or "persons". There is no reason for the People class to know anything about elevators. The class name itself is not great -- class names should generally be singular nouns. "Group" might be better.

You need to write your sort methods (probably in your People class) and then you need a Person[] fillElevator(Person[] potentialRiders, int weightLimit) method in your Elevator class. Create your Person[] result array, then iterate through potentialRiders, adding each Person to result until you reach weightLimit. You also need a listRiders() method.

That should get you going. Show us what you come up with, and remember to use CODE tags.

-Gary-
• 04-21-2010, 10:21 PM
LostinJavaLand
Thanks for your help. This is what I have come up with so far.
Code:

```public class Group {         private Person[] persons;         private int count;                 public Group(int size)         {                 persons = new people[size];                 count = 0;         }         public void add(Person x)         {                 persons[count] = x;                 count++;                                }         public Person[] fillElevator(Person[] potentialRiders, int weightLimit)         {                         weightLimit = 1100;                 totalWeight = 0;                 potentialRiders = 0;                 for(int i=0; i<persons.length; ++i)                 {                                                 if(totalWeight <= weightLimit)                                 potentialRiders++;                         else                                 break;                        }                 }         public         {                 if persons[i].getName()compareTo         }         public sortWeights(int[] w;String[]n)         {                 int weightIndex;                 for (int i=0; i < persons.length-1; i++)           {                         weightIndex = i;                         for (int j = i+1; j < persons.length; j++)                                 if (persons[j] < persons[weightIndex])                                         weightIndex = j;                         int temp = persons[i];                         persons[i] = persons[weightIndex];                         persons[weightIndex] = temp;                 }         }         public String toString()         {                 String out ="";                 for (int i=0; i<count; i++)             out+= (i + ":\t" + persons[i]);                 return out;         }```
How do I add the potentialRiders' weights to the weightLimit? How does the other stuff I have look?
• 04-21-2010, 10:51 PM
gcalvin
fillElevator() goes in your Elevator class, not your Group class. Group knows about a collection of Persons, but doesn't (shouldn't) know anything about elevators. Also, weightLimit is going to be passed into the method, not assigned within it (unless it's an instance variable, which it probably should be -- an Elevator should know its weightLimit). You have one Person[] passed in to the method (potentialRiders) and you need to create another Person[] that you will return (result). And since we're using raw arrays, you'll probably need two passes -- one to get the count, and another to actually load the array. (It's clumsy, and that's why developers tend to prefer ArrayList.)

sortWeight() needs a return type (maybe void?). I would probably call it sortByWeight(), make it void, and have it just sort the internal persons array in place. Actually, it seems that's what you're doing, but you've passed in two parameters that you never use.

This is not going to work:
Code:

`                                if (persons[j] < persons[weightIndex])`
because Person is not Comparable (maybe you want getWeight() here?) Also,
Code:

`                        int temp = persons[i];`
I think you mean:
Code:

`                        Person temp = persons[i];`
You're on the right track, though. Good luck!

-Gary-
• 04-28-2010, 03:22 PM
LostinJavaLand
I've been working on this for awhile. Today's the last day for me to turn it in. I cannot get it to work correctly. I have output, but with muchas problemas.
Here is my Person class:
Code:

```public class Person {         private String name;         private int weight;                 //default         public Person()         {                 name = "";                 weight = 0;         }                 //overloaded         public Person(String n, int w)         {                 name = n;                 weight = w;         }         public String getName()         {                 return name;         }         public int getWeight()         {                 return weight;         }         public void setName(String n)         {                 name = n;         }                 public void setWeight(int w)         {                 weight = w;         }                 public String toString()         {                 return name +"\t"+ weight;         } }```
Here is my People class
Code:

```public class People {         private Person[] persons;         private int count = 0;                 public People(int size)         {                 persons = new Person[size];                 count = 0;         }         public void add(Person x)         {                 persons[count] = x;                 count++;                                }         public int howMany()         {                 int total = 0, i = 0;                 do                 {                         total += persons[i].getWeight();                         System.out.println("\n" + (i+1) + ":" + persons[i]);                                        i++;                                                         }while (total <= 1100);                         System.out.println("The total weight is " + (total- (persons[i-1].getWeight())) );                         return i-1;                                }         public int sortWeights()         {                 int weightIndex;                 for (int i=0; i < count; i++)           {                         weightIndex = i;                         for (int j = i+1; j < persons.length; j++)                                 if (persons[j].getWeight() < persons[weightIndex].getWeight())                                         weightIndex = j;                         Person temp = persons[i];                         persons[i] = persons[weightIndex];                         persons[weightIndex] = temp;                                         }                 return howMany();         }         public int sortNames()         {                 int nameIndex;                 for (int i=0; i < count; i++)           {                         nameIndex = i;                         for (int j = i+1; j < persons.length; j++)                         if(persons[i].getName().compareTo(persons[nameIndex].getName())>0)                                         nameIndex = j;                                 Person temp = persons[i];                 persons[i] = persons[nameIndex];                 persons[nameIndex] = temp;                 }                 return howMany();         }                 public String toString()         {                 String out ="";                 for (int i=0; i<count; i++)             out += ("\n"+(i+1) + ":\t" + persons[i]+"\n");                 return out;         } }```
Here is my driver called Elevator:
Code:

``` import java.util.Scanner;   import java.io.*;     public class Elevator   {       public static void main (String[] args) throws IOException       {         Scanner scan = new Scanner(new File("elevData.txt"));         int s = scan.nextInt();               int count=0;         int i = 0;         int ctA = 0; int ctB = 0; int ctC = 0;                         People holder = new People(s);               System.out.println("The original array is ");                   System.out.println(holder);                                      do         {                                 Person loader = new Person();             loader.setName(scan.next());             loader.setWeight(scan.nextInt());             holder.add(loader);                                 i++;         }         while(scan.hasNext());                                     ctA = holder.howMany();         System.out.println("For a regular day " + ctA +" people got on.");                                               System.out.println("The array in ascending sequence by weight is ");         ctB = holder.sortWeights();         System.out.println("After sorting the people by weight "+ctB +" people got on");               System.out.println("The array in ascending sequence by name is ");         ctC = holder.sortNames();         System.out.println("After sorting the people by name "+ctC+" people got on");                     if(ctA > ctB && ctA > ctC)         {             System.out.println("The first system worked the best");         }         else if(ctB > ctA && ctB > ctC)         {             System.out.println("The second system worked the best");         }         else         {             System.out.println("The last system worked the best");         }       }   }```
And here is my text file that I used.
12
Anne 30
Bob 150
Ralph 305
Tim 225
Barbara 135
Jane 160
Steve 80
Tom 200
Mike 165
Shirley 90
Pam 100
Frank 120

I would be extremely thankful for your help.
• 04-28-2010, 04:00 PM
JosAH
Quote:

Originally Posted by LostinJavaLand
Part V: Have the program determine which method allowed the most people to get on the elevator.

I especially like this part of the assignment so I dusted off an old knapsack class of mine; a knapsack has a capacity (your elevator can lift 1100lbs), a person takes up capacity (their weight) and have a value (all equal for each person). How to fill up the knapsack given the capacity constraint so that the sum of the values is maximized (read: as many peoply can be stuffed in that elevator).

A person is either stuffed in that elevator or not. When s/he is, the problem is reduced to a lesser capacity and a set of persons minus this current person. When a person doesn't fit in the elevator obviously we don't even try to stuff him in. That's how my program works. It reads the following data file:

Code:

```1100 12 1 30 1 150 1 305 1 225 1 135 1 160 1 80 1 200 1 165 1 90 1 100 1 120```
The first line contains the capacity of the elevator and the number of persons. The following lines are the values of the persons and their weight. I saved this file in c:/tmp/data.txt

Here is the class:

Code:

```import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Knapsack {         private Item[] items;         private int nofItems, capacity;         private void initialize() throws FileNotFoundException {                 Scanner input= new Scanner(new File("c:/tmp/data.txt"));                 capacity= input.nextInt();                 nofItems= input.nextInt();                 items= new Item[nofItems];                 for (int i= 0; i < nofItems; i++)                         items[i]= new Item(input.nextInt(), input.nextInt());                 total= 0L;                 cut= 0L;         }         private Solution solve(int allowed, int cap) {                 Solution take, dontTake;                 if (allowed < 0)                         return new Solution(nofItems);                 total++;                 dontTake= solve(allowed-1, cap);                 if (items[allowed].weight > cap) {                         cut++;                         return dontTake;                 }                 take= solve(allowed-1, cap-items[allowed].weight).take(items, allowed);                 return (take.value > dontTake.value)?take:dontTake;         }         private long total;         private long cut;                 public static void main(String[] args) throws FileNotFoundException {                 Knapsack k= new Knapsack();                 k.initialize();                 Solution b = k.solve(k.nofItems-1, k.capacity);                 System.out.println("Total Value: " + b.value);                 System.out.println("Total Steps: " + k.total);                 System.out.println("Total Cuts : " + k.cut);                 int w= 0;                 for (int i= 0; i < k.nofItems; i++) {                         if (b.taken[i]) {                                 System.out.println(i + ": " + k.items[i]);                                 w+= k.items[i].weight;                         }                 }                 System.out.println("Total weight: "+w);         } } class Solution {         boolean[] taken;         int value;         Solution(int nofItems) {                 this.taken= new boolean[nofItems];         }         Solution take(Item[] items, int rank) {                 this.value+= items[rank].value;                 this.taken[rank]= true;                 return this;         } } class Item {         int value, weight;         public Item(int value, int weight) {                 this.value= value;                 this.weight= weight;         }         public String toString() {                 return value + " " + weight;         } }```
The solution it came up with is:

Code:

```Total Value: 9 Total Steps: 3526 Total Cuts : 342 0: 1 30 1: 1 150 3: 1 225 4: 1 135 5: 1 160 6: 1 80 9: 1 90 10: 1 100 11: 1 120 Total weight: 1090```
The elevator is nearly full ;-)

kind regards,

Jos
• 04-28-2010, 04:41 PM
LostinJavaLand
Thank you very much Jos. Nifty program.
• 04-28-2010, 08:16 PM
m00nchile
Yeah, JosAH's method does give the absolute solution to the problem at hand, but I think what your teacher had in mind was to just fill the persons into the elevator sequentially from your array, first unsorted, then sorted by weight, then sorted by name. Then you compare the results to see which array sequence gives the best (most persons) result. If you decide to use Jos' solution, be sure to study it and understand it, in case your teacher gets suspicious, since it's a bit more advanced than what the assignment was about (that is, if I understood the instructions correctly).
Oh, and to Jos, really cool solution by recursion. I'm currently attending a class that focuses on recursion at my uni, this will come in pretty handy!
• 04-28-2010, 09:10 PM
Meta
i have a question about this guys program. are those separate programs, that interact with each other. our are they in one program?
• 04-28-2010, 09:12 PM
gcalvin
It is one program consisting of multiple classes in multiple source code files. This is not at all unusual for Java.

-Gary-

EDIT: To be clearer, I was talking about LostInJavaLand's code. JosAH's is one program consisting of multiple classes in one source code file. This is legal because only one of the classes in the file is public and has a main() method.
• 04-28-2010, 09:28 PM
Meta
can you explain how they work together , if they are separate files
• 04-28-2010, 09:35 PM
gcalvin
Quote:

Originally Posted by Meta
can you explain how they work together , if they are separate files

Well, let's start with his Person class. It's public, has a public constructor, and several public methods. That means that any other code can create Person objects and call their methods, in very much the same way that your code can create ArrayList or JTextField or Random objects. His People class takes advantage of that and creates an array of Person objects. And his Elevator class in turn creates and uses a People object.

You do have to make sure that all the necessary .class files are in directories that are on your CLASSPATH, but other than that and the access restrictions (public, private, protected, etc.) there's not much to it.

-Gary-
• 04-29-2010, 08:55 AM
JosAH
Quote:

Originally Posted by m00nchile
Oh, and to Jos, really cool solution by recursion. I'm currently attending a class that focuses on recursion at my uni, this will come in pretty handy!

Thanks; the core of the algorithm is really simple: assume all those people are standing in line; the range of people [0, allowed] can potentially be put in the elevator. For every person the algorithm either tries to put that person in the elevator (if it can still fit the person in) or it doesn't. Note that first the 'don't take' option is executed all the way down to where no more persons are left to chose; only then a new solution is created and people are stuffed in when the algorithm (recursively) reaches the 'take' option. Basically all combinations are checked and the best solution is kept. At the end some statistics are printed: the higher the 'cut' number (depending on the order of the people) the better the algorithm performed. Try different orders for those people and see for yourself.

kind regards,

Jos
• 04-29-2010, 09:05 AM
r035198x
Quote:

Originally Posted by JosAH
.. the higher the 'cut' number (depending on the order of the people) the better the algorithm performed ...

That's an especially cool property.

r035198x(<----choking from all the dust from Jos' sack.
• 04-29-2010, 10:41 AM
JosAH
Quote:

Originally Posted by r035198x
That's an especially cool property.

It's cute isn't it? And the bounding condition is just trivial: if a person is too heavy to fit in the elevator (given a certain filling already) there's no need to explore all combinations with that person on board because they're all infeasible. Even for this small problem (12 persons) it had to travers 4096 possibilities but by applying 342 cuts it only had to investigate 3526 possibilities). Cutting on branches always pays back. Personally I'm too stupid to come up with a more 'intelligent' cut strategy.

Quote:

r035198x(<----choking from all the dust from Jos' sack.
There are a whole lot more tricks in there so you'd better watch out! ;-)

kind regards,

Jos