I'm making a program to make a list of people, with 3 different marks of time (in double)
To do it, I made 4 arrays, One String, to save people names, and 3 Doubles to save the 3 marks on the years 2010, 2011, and 2012.
In the menu, I have to implement an option to sort the list on 2012s mark, in descending order.
Like this
m12[0] = 12.1
m12[1] = 34.1
m12[2] = 23.1
m12[3] = 23.5
into:
m12[1] = 34.1
m12[3] = 23.5
m12[2] = 21.1
m12[0] = 12.1
I did it with a basic algorithm, but now I want to know if it's possible to get the actual order of the arrays, ([1],[3],[2],[0]) and apply it to the other arrays I have to print it as a list based on the 2012 mark in descending order.
Thats the code I have to make the normal order list:
if(option==2){
System.out.println("# , Name, 2010, 2011, 2012");
for(i=0;i<dorsal.length-1;i++){
if(dorsal[i]!=0){
System.out.println(dorsal[i]+"- "+nom[i]+", "+m10[i]+", "+m11[i]+", "+m12[i] );
}
}
System.out.println("Press ENTER to return");
intro.nextLine();
}
Sorry if I didnt explained it very good, I started programming 3 months ago and I'm so newbie.
//EDIT
I'll paste here the head of the exercise:
Thats exactly the programs needs to do. I'm stucked at point 3.
The objective is to develop a program to manage a list of members of
in a competition of long jump. The number of places available is 15.
Their data will be introduced in the same order in which the athletes
enroll. Design a program that shows the following options:
1 – Register a participant
2 – List all the participant’s data
3 – List all the participant’s data by mark
4 – Quit
If 1 is selected, data of one of the participants will be introduced:
Name, best mark in 2012, best mark in 2011 and best mark in 2010.
If 2 is selected, we have to list all participant’s data ordered by dorsal
number (the order they’ve enrolled)
If 3 is selected, we have to list all participant’s data ordered by 2012
mark, from greater to smaller.
After processing each option, the main menu must be shown again,
till the option 4 is selected, quitting the program.
Thanks.
Define a class to contain the data for each person, such as:
public class Person
{
private String name;
Private Map<Integer,Double> marks = new HashMap<Integer,Double>();
public Person(String name) { this.name = name; }
public void setMark(int year, double mark) {
this.marks.put(year,mark);
}
public void getMark(int year) {
// return zero if there's no mark for the requested year
return this.marks.containsKey(year) ? this.marks.get(year) : 0;
}
}
Then write a Comparator<Person>
public PersonComparatorOnMarkDescending implements Comparator<Person>
{
private int yearToCompare;
public PersonComparator(int yearToCompare) {
this.yearToCompare = yearToCompare;
}
public compare(Person p1, Person p2)
{
Integer p1Mark = p1.getMark(yearToCompare);
Integer p2Mark = p2.getMark(yearToCompare);
return p2.compareTo(p1);
}
}
You can then define a List<Person> or a Person[] array and use the sorting methods available in java.util. Instantiate the comparator with, for instance:
Comparator<Person> comp = new PersonComparatorOnMarkDescending(2012);
This approach lets you sort the collection on any year's marks.
Related
I have the following objects:
enum Slot
{
HANDS, LEGS, CHEST, HEAD, FEET;
}
class Clothing
{
// The slot this piece of clothing is worn on.
Slot s;
// The color of the clothing, used for `gradeOutfit`
Color c;
}
class Person
{
Map<Slot, Clothing> body;
// look through his outfit and give a score
// for how well he looks
int gradeOutfit()
{
return ...
}
}
I have one Person object and a collection of Clothing. This collection has many Clothing objects of each Slot. For example, it might look like this:
MyCloset = { GREEN_HAT, RED_VEST, BLACK_VEST,
BLUE_JEANS, BROWN_PANTS, RED_SHOES, BLACK_HAT, BLUE_GLOVES, PURPLE_VEST }
In the reality of my program, there are a lot more items than just these but this is just a simplified example.
Problem:
I need to find a combination of these clothes that lead to the highest gradeOutfit score. That means my Person will have to make sure he tries on every Clothing item with every other Clothing item (within limits, ex. it's impossible for two hats to be worn because both are for HEAD Slot). A Person cannot have their gradeOutfit called until they are wearing a Clothing item for every Slot.
I was thinking recursion is the best way to do this but then I think I'd get a stack overflow very fast if I had a decent amount of items. I tried doing it iteratively but I cannot seem to find a good easy way to loop through everything. My program basically looks like
Person p = new Person();
for (Clothing i : MyCloset)
{
for (Clothing h : MyCloset)
{
if (i == h) continue;
if (!p.isWearing(h.slot())
{
p.wear(h);
}
}
int score = p.gradeOutfit();
}
But I know this is just a terrible approach. In order to ensure that every clothing item has been paired up with every other Clothing item, I would need so much more looping logic than just this. No matter what I try, it turns into spaghetti code. I also need to avoid looping over the same outfit twice and make sure that no outfit combination is forgotten about.
What is the best way to approach something like this?
This is an example of a mathematical optimization problem. You seem to already have the objective function (the function that calculates the gradeOutfit score - taking as an input five clothings, one per slot) and you need some constraints (e.g. each clothing in a combination of 5 belongs to a different slot). You need a Java solver library to do this. If your objective function is linear, a linear solver will do. As I have only experience with commercial solvers, I cannot recommend an open-source one, a list of options can be found here.
A simpler (but not extremely elegant) way, without a solver:
Create 5 sets of Clothing objects, one per slot (you can use Java
HashSet for this).
Iterate over all combinations, each time taking one item from each of the 5 sets. You need n1 x n2 x n3 x n4 x n5 combinations, where ni is the number of clothing instances per slot.
It also seems to me that the gradeOutfit function should not be part of the Person class - as it is actually the property of an outfit, not a person (i.e. two persons with the same outfit have exactly the same scores). I 'd prefer to have an Outfit class and put it there.
You have very poorly created the data structure.
enum Slot
{
HANDS, LEGS, CHEST, HEAD, FEET;
numbers = new int[values.length()]
}
enum COLOR
{
RED,BLUE,...;
}
enum Clothing {
GREEN_HAT(HEAD,GREEN), ...;
Slot slot;
Color color;
public static Clothing (Slot slot, Color color){...}
}
class Outfit extends Map <Slot, Clothing> {
countScore(){};
public static Outfit(){
//foreach slot this.put(slot, Clothing.values().get(0));
}
}
...
int n=slot.values.length()-1;
Outfit currentOutfit = new Outfit();
Outfit bestOutfit = new Outfit();
int currentActiveSlot = 0;
// make a cycle for combination of all Outfits
for an enum , you have to use the method "values()" to loop on it:
For (clothe c: clothes.values())
I have an Ordering System that comprises of a number of steps before the data is finally submitted and stored in the database. I have already completed and implemented the web version of the same Ordering System. Below is the Multidimensional Array in PHP that I created dynamically based on the below values.
In the first step of Order, a Plan is to be selected. Based on that plan, the total number of days will be decided.
Plan 1 - Days Served 26
Plan 1 - Meals Served Per Day 2
Plan 1 - Refreshments Served Per Day 2
Plan 2 - Days Served 5
Plan 2 - Meals Served Per Day 3
Plan 2 - Refreshments Served Per Day 0
and so on...
In the second step, starting date of the Order is to be selected. Weekends are to be excluded and only Weekdays will be counted as days served.
The PHP Multidimensional Array generated dynamically is below
Array
(
[Day 1] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
[Day 2] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
In the above code, day number is added dynamically and numeric value in meal_id_1, meal_code_1 and meal_type_1 is also added dynamically.
To connect the App and Web Application logically, I want to post the selection from the App in similar Array.
Since I have Meals and Refreshments to be selected based on the plan, therefore I will be loading Meals for Day 1 and then based on the Plan selected Refreshments for Day 1. There will be 1 Activity for Meals, which be loaded with updated Day number and same for the Refreshments.
Using the below code, I am able to get the Unique ID of the Meals selected in an ArrayList.
int count = 0;
int size = list.size();
List<String> selected_meals = new ArrayList<String>();
for (int i = 0; i<size; i++){
if (list.get(i).isSelected()){
count++;
String selected_meal_string = list.get(i).getMeal_id();
selected_meals.add(selected_meal_string);
}
}
How can I transfer this selection to a Global Multidimensional Array so that in the final step I can post it to be saved in the database?
as per my comment I think you are really looking to use a class here, please see the example below to get you started. You may require some research into how OOP (Object Oriented Programming) works though.
public class Meal {
//I dont know what type of data each attribute is supposed to be so I chose ints. Feel free to change.
private int mealId;
private int mealCode;
private int mealType;
public Meal(int mealId, int mealCode, int mealType){
this.mealId = mealId;
this.mealCode = mealCode;
this.mealType = mealType;
}
public int getMealId() {
return mealId;
}
public int getMealCode() {
return mealCode;
}
public int getMealType() {
return mealType;
}
}
Now the Day class:
import java.util.ArrayList;
public class Day {
private ArrayList<Meal> meals = new ArrayList<>();
public Day(Meal...meals){
//This uses magic params to allow you to pass in as many meals as you want.
for(Meal meal : meals){
this.meals.add(meal);
}
}
public ArrayList<Meal> getMeals() {
return meals;
}
}
Now wherever your main method is:
import java.util.ArrayList;
public class Control {
public static void main(String [] args){
ArrayList<Day> days = new ArrayList<>();
//Create your meals.
Meal meal1 = new Meal(1, 1, 1);
Meal meal2 = new Meal(2, 3, 4);
//Add the meals to a day.
Day day1 = new Day(meal1, meal2);
//Add the day to the list of days.
days.add(day1);
//Getting the meal code for the first meal on the first day. This looks complex, but you would likely break it down before getting values.
System.out.println(days.get(0).getMeals().get(0).getMealCode());
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
just got some computer science from my friend, I believe it is a intro to programming assignment, and I was trying on it, but it seems there are so many issue, seems I am majoring CS, can someone help me on those questions step by step, would be appreciated. in instructions are following:
Create a public class Movie with private instance variables String title
and int year. The class should declare that it implements the
Comparable interface, and should provide the following:
• A constructor that takes 2 arguments: a String and an int (in that order)
for initializing title and year.
• A method that satisfies the Comparable interface. Movies should be compared first by title and then by year.
{ The Maltese Falcon 1941, The Thomas Crown Affair 1968, The Thomas Crown Affair 1999}
An equals() method that is compatible with the method that satisfies the
Comparable interface.
• A toString() method that prints “Movie” followed by 1 space followed by
the title followed by 1 space followed by open-parenthesis followed by
the year followed by close-parenthesis. Example:
The Maltese Falcon (1941)
• A public static method getTestMovies(), which returns an array of 10
unique Movie instances. The 0th and 1st array elements must be 2 movies
with the same title but from different years (e.g. The Thomas Crown
Affair 1968 and The Thomas Crown Affair 1999, or True Grit 1969 and
True Grit 2010). The 2nd and 3rd elements must 2 movies with different
titles but from the same year (e.g. The Martian 2015 and Bridge of Spies
2015). The 4th and 5th elements must be 2 different objects that
represent the same movie.
• A hashCode() method. Use the following:
public int hashCode()
{
return title.hashCode() + year;
}
the following is what I have so far, I have the constructor and the starter, but I am sure how to do it.
public class Movie implements Comparable<Movie>{
private String title;
private int year;
public Movie(String title, int year){
this.title = title;
this.year = year;
}
#Override
public int compareTo(Movie that) {
int value = 0;
if(this.title == that.title)
{
if(this.year < that.year){
value = 0;
}
else{
value = -1;
}
}
return value;
}
public static void getTestMovie(){
}
public boolean equals(Object x)
{
}
}
Any Helps are appreciated!
When you want sorting other than natural order, you should Comparator rather than Comparable. Please follow below link for more info :
What is the difference between compare() and compareTo()?
Regarding string comparison use str1.equals(str2). For the reason follow below link :
What is the difference between == vs equals() in Java?
For rest of the questions, please post some tried code.
You can't use this.title == that.title on Strings. You should use this.title.equals(that.title).
Except, for this code, you shouldn't. You should use this.title.compareTo(that.title).
If that return non-zero, return that value, because it represents the ordering when titles differ.
If it returned zero, the titles were equal, and you need the secondary check on year. For that use Integer.compare(this.year, that.year).
I want to iterate through a hibernate query results inside stringtemplate. I've been looking for examples but I can't find anything.
can you please help? thanks
The syntax looks like
<items :{ item | <item> }>
Putting it together in Java:
List<String> teams = Arrays.asList("Cats", "Birds", "Turtles");
ST s = new ST( "<teams :{team | <team> }>");
s.add("teams", teams);
System.out.println(s.render());
In this example, I iterate over the List and print each team that is in the teams list. The result that would be printed is:
Cats Birds Turtles
We can explore the syntax that makes this happen. Before we do, remember, that the default delimiters in StringTemplate are less than < and greater than >. Since we didn't specify a different delimiter < > will be what we use in our example.See more about delimiters
:{ }
This set of symbols, the colon : and the open and closed brace {} can be read as "for each". In the example template, the code reads, for each team in teams print team. The left side of the vertical pipe | indicates the variable that will be created for each iteration. It will hold the current team from the list of teams. The print is composed of the <team> on the right side of the vertical pipe | and the left side of the closing brace }. Anything that is on the right side of the vertical pipe | and before the closing base } will be evaluated to be printed.
:{ current value | everything in here will be printed }
In order to build on the concept, let's use a more complex data structure.
public class Player {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() { return age; }
public String getName() { return name; }
}
Now we can create a few players for our team:
Player[] players = new Player[] {
new Player("Bill", 29),
new Player("Steve", 30),
new Player("Toby", 15)
};
String playerTemplate = "<players:{ player |<player.name> is <player.age> <\\n>}>"
ST s = new ST( playerTemplate );
s.add("players", Arrays.asList(players));
System.out.println(s.render());
Giving a result of
Bill is 29
Steve is 30
Toby is 15
Couple of things to note. We didn't access the properties age and name directly. ST called the methods getAge and getName. ST doesn't look to the properties. Instead, it looks to find the access methods.
What if we just wanted to iterate over a list that contained another list. We can do that as well.
First, let's build up our data structure and fill it with a couple of lists.
List<List<String>> listOfLists = asList(
asList("One", "Two", "Three"),
asList("Four", "Five"),
asList("Six", "Seven", "Eight", "Nine")
);
The template will look like the following.
<list :{ items |<items :{ item |<item> }><\n>}>
Our template, in this case, will just be a combination. The outer shell will iterate over the list we will hand in.
<list :{ items | what we will print }>
Then for each item, we will print out the items in its list.
<items :{ item |<item> }>
Once we put it all together
String template = "<list :{ items |<items :{ item |<item> }><\\n>}>";
ST st = new ST( template);
st.add("list", listOfLists);
System.out.println(st.render());
We get a result that looks like the following.
One Two Three
Four Five
Six Seven Eight Nine
Building on this concept a little more we can create a second data structure that contains a list of players. This will demonstrate how to iterate within iteration.
The first thing we will need is a data structure that contains a list. For this we can create a Team for our players to be a part.
public class Team {
private List<Player> players;
private String name;
public Team (String name, List<Player> players) {
this.players = players;
this.name = name;
}
public List<Player> getPlayers() {
return players;
}
public String getName() {
return name;
}
}
Notice that our team contains players. This composition will allow us to build up two iterations.
Now that we have our data structure lets set everything together to make a couple of teams with some players.
List<Team> teams = asList(
new Team("Billings", asList(
new Player("Bill", 29),
new Player("Steve", 30),
new Player("Toby", 15)
)),
new Team("Laurel", asList(
new Player("Chad", 32),
new Player("Chuck", 29),
new Player("Will", 24),
new Player("Ben", 26)
))
);
Now lets create a template and fill in a few details:
String simpleTeamTemplate = "<teams:{ team |<team.name> has <length(team.players)> players<\\n>}>";
ST template = new ST( simpleTeamTemplate );
template.add("teams", teams);
System.out.println(template.render());
That will print out
Billings has 3 players
Laurel has 4 players
Our simple template is just about the same as our first template from above. The only real difference is that we are using a built-in method provided by ST length(). See more on functions here
Let's increase the complexity of the templates a little to add in our second iteration.
First, we will create our playersTemplate. This is almost identical to our playerTemplate template from above. The only difference is that we have our players coming from a team: team.players.
String playersTemplate = "<team.players :{ player |<player.name> is <player.age><\\n>}>";
Now we will construct a second template that contains the first. In this template we can iterate over teams and for each team we will print out the name, number of players length(team.players), and everything in the playersTemplate.
String teamTemplate = "<teams:{ team |<team.name> has <length(team.players)> players<\\n>"+playersTemplate+"}>";
Now let's put that all together.
ST teamsTemplate = new ST( simpleTeamTemplate);
teamsTemplate.add("teams", teams);
System.out.println(teamsTemplate.render());
That will print for us the following.
Billings has 3 players
Bill is 29
Steve is 30
Toby is 15
Laurel has 4 players
Chad is 32
Chuck is 29
Will is 24
Ben is 26
Now, you aren't really going to want to combine your templates in this way. Appending strings together to compose templates is rather silly. StringTemplate offers tools to make this combination of partial templates very easy. If you are curious about combining templates you can find out more here
%staffForOrg: {staff|
<tr>
<td>%staff.telephoneNumber%</td>
</tr>
}%
this code works perfectly.
staffForOrg is a list of my model. I used hibernate to retrieve the records.
I have an assignment that requires me to take a large dataset, store it in an array, and then create methods that interpret the data in various ways. The file data I am given is in the form like so:
0 138
0 139
0 140
0 141
0 142
0 799
4 1
4 10
4 12
4 18
etc... (it is very large)
This data is supposed to represent a social network of people, with the numbers representing individuals. Each line contains a person on the left who has 'trusted' the person on the right. I am supposed to interpret this data so that I can find all the persons a particular person trusts, how many people trust a particular person, and how to find the most trusted person. However, I am at a complete loss as to how to write these methods, and so I was wondering if you guys could help me out. Here's the code I have so far:
public class SocialNetwork {
static Scanner scanner = new Scanner(System.in);
static void findTrusted()
{
System.out.println("Please input person number you would like to find Trustees for");
trustee = (scanner.next());
}
public static void main(String[] args){
File inData = new File("dataset.txt");
ArrayList<Integer> links = new ArrayList<Integer>();
try
{
Scanner in = new Scanner(inData);
in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
while (in.hasNext())
{
int trustee = in.nextInt();
int trusted = in.nextInt();
links.add(trustee);
links.add(trusted);
}
in.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
As you can see, my findTrustee method has very little in it. I just don't know where to even start. I have come up with a little pseudocode to try and dissect what needs to be done:
prompt user for input on which person(integer) to find his/her trustees
search arraylist links for person(integer) inputted
print all persons(integers) on the right side of the lines that begin with person requested
However, I just don't quite know how to do this.
The structure links doesn't really help you. It has no idea of "from" and "to". You are storing Persons as numbers, but not storing any relationships between two people. You're really working in graph theory, and when you can you should look at reference works and Java libraries for graph theory.
So, what is a trust link? It is an object that has two people, the trustee and trusted people. Create a class for this:
public class Trust {
private final int trustee;
private final int trusted;
public Trust(final int trustee, final int trusted) {
this.trustee = trustee;
this.trusted = trusted;
}
// Getters, equals, hashCode, toString, formatted output for humans.
}
Have your class SocialNetwork be able to create these. By the way, create a SocialNetwork instance in your main method, and stop using static for everything else.
public Trust createTrust(Scanner scanner) {
int trustee = scanner.nextInt();
int trusted = scanner.nextInt();
return new Trust(trustee, trusted);
}
You might need to add exception handling and end of file handling.
Make links a list of Trust objects, and then write methods that scan that list as needed.
/**
Return a list of all the people who trustee trusts.
#param trustee A person in the system.
#return a list of the people trustee trusts.
*/
public List<Integer> trusting(int trustee) {
final List<Integer> trusted = new ArrayList<>();
for (Trust link: links) {
// Add something from link to trusted if it should.
// This looks like homework; I'm not doing everything for you.
}
return trusted;
}
Write other methods as you need them. Then, think about whether these data structures are efficient for this problem. Could Maps be better? MultiMaps from other libraries? An open source graph theory library of some sort? Perhaps you should use a database instead. Perhaps you should have a Person class instead of using just integers; that way you can label people with their names.
I think there are quite a number of ways you can implement this (regardless of performance). For example, you can use HashMap, array of array (or list of lists if you really like list...)
I will give an example using list maybe, since you seem using it... (although I think this is a bit odd)
Say, you have a list holding the people on the left.
ArrayList<ArrayList> leftList = new ArrayList<ArrayList>();
For leftList,loop through it till you reach the max no. of the left column (now you may see why an array/HashMap is better...) by doing something like:
leftList.add(new ArrayList());
in each loop.
Then all you have to do now is to read the file and plug the list of trustees to rightList corresponding to the truster. E.g. I have 1 3, 1 4 and 2 3; your implementation will achieve sth like:
leftList.get(1).add(3) / leftList.get(1).add(4) / leftList.get(2).add(3)
depending which line you are reading.
With this setup, I guess you can solve those three questions quite easily? Otherwise, just look for more advice here. But make sure you think through it first!
Hope my answer gives you some ideas.