Hey i think i have some logic problem, but yet i cant really see where it is.
I know that the Problem is somewhere between HashSet, but thats it.
I am using a HashMap and the key is numberOfEpisode and the values are HashSet.
So if these animes in my List of Array has the same amount of Episode, like 12 then add them to a new HashSet and then into the HashMap.
Code
HashSet<Strings> animeNames;
for(Anime anime : animius.getListOfAnime){
animeNames = new HashSet<>();
for(Anime anime2 : animius.getListOfAnime){
for(Episode episode : anime.getListOEpisode){
for(Episode episode2 : anime2.getListOfEpisode{
if(episode.getNumber == episode2.getNumber){
animeNames.add(anime.getName);
animius.getEpisodeAndAnimeIndex.put(episode.getNumber, animeNames)
}
}
}
}
}
Output
After Formatting it. And Lets say only anime1 has similarities towards anime 2, but anime 2 has 2 Keys one with 12 Episode and the other one with 24 Episode.
12 ---- anime1, anime2 <--- this is correct
24 ---- anime1, anime2 <--- this is wrong
Expected Output
12 ---- anime1, anime2
24 ---- anime2
Attempted Solutions
I have created 2 HashSet with one which contains the values of anime.getName and the other one which contains anime2.getName.
I also played around with putting the new instantiation of animeNames and animeNames2 differently in the for each loops
If I haven't misunderstood you, you don't need to have 4 nested for loops. You just want to check for each anime in your collection what number of episodes they have and store that. Essentially group animes together by number of episodes. The code below does that.
HashMap<Integer, Set<Anime>> animeMap = new HashMap<>();
for(Anime anime : animius.getListOfAnime){
int numberOfEpisodes = anime.getListOEpisodes().size();
if (animeMap.contains(numberOfEpisodes) {
animeMap.get(numberOfEpisodes).add(anime);
} else {
HashSet<Anime> animeNames = new HashSet<>();
animeNames.add(anime);
animeMap.put(numberOfEpisodes, animeNames);
}
}
Related
I'm using the choco solver library to generate a set of puzzles. I need to run the solver, check how many solutions there are and if there is more than one, add an extra constraint. Repeating this will give me a set of constraints (clues) that has a unique solution.
However once I've run model.getSolver(findAllSolutions()) any additional checks return zero solutions.
I'm guessing I need to somehow reset the model solver but can't find a way of achieving this - I'd rather not generate a new model and recreate the exiting constraints if I have to.
The original code has 110 IntVar's and a huge number of constraints, but I've created a much smaller example.
Note: in the real application I use model.getSolver().findAllSolutions(new SolutionCounter(model,2)) to speed things up, but I've omitted that step here.
Model model = new Model();
// setup two doors A and B, one has the value 0 the other 1
IntVar doorA = model.intVar("Door A", 0, 1);
IntVar doorB = model.intVar("Door B", 0, 1);
model.allDifferent(new IntVar[]{doorA, doorB}).post();
// setup two windows A and B, one has the value 0 the other 1
IntVar windowA = model.intVar("Window A", 0, 1);
IntVar windowB = model.intVar("Window B", 0, 1);
model.allDifferent(new IntVar[]{windowA, windowB}).post();
// assign the first constraint and count the solutions
model.arithm(doorA,"=",0).post();
// this should force door B to be 1 - there are two remaining solutions
List<Solution> solutions = model.getSolver().findAllSolutions();
System.out.println("results after first clue");
for (Solution s : solutions) {
System.out.println(">"+s.toString());
}
assertEquals("First clue leaves two solutions",2,solutions.size());
// add second clue
model.arithm(windowA,"=",1).post();
// this should force window B to by 0 - only one valid solution
List<Solution> solutions2 = model.getSolver().findAllSolutions();
System.out.println("results after second clue");
for (Solution s : solutions2) {
System.out.println(">"+s.toString());
}
assertEquals("Second clue leaves one solution",1,solutions2.size());
For anybody else looking for this, it turns out that the answer is simple.
model.getSolver().reset();
I have created an app that recieves orders and i want to be able to cycle 4 sets of orders so each device can choose what set of orders it sees. I want to split the orders by the order_id so
a: 1 5 9 13 ect
b: 2 6 10 14 ect
c: 3 7 11 15 ect
d: 4 8 12 16 ect
I recieve the orders through a loop but can change to a list of array lists if nessecary. I have tried a couple ways to get the result im after but have had no luck. Thank you in advance
EDIT (Rough idea of what i want)
//Data from Json
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
final int objectsItem = oneObject.getInt("order_id");
if(checkboxA == checked)
{
//Show orders 1,5,9,13 ect
}
if(checkboxB == checked)
{
//Show orders 2,6,10,14 ect
}
if(checkboxA == checked)
{
//Show orders 3,7,11,15 ect
}
if(checkboxA == checked)
{
//Show orders 4,8,12,16 ect
}
}
`
This way i can show all orders, all parts of orders, so the orders can be equally split between many devices without interacting with each other - Hope this makes more sense
What about using a Map? You can set every order_id as the key for an entry and all orders as the value of the entry (for example List of orders).
For example:
Map<Character, List<Integer>> map;
Than you can get a certain order_id with:
List<Integer> orders = map.getValue('a');
for (Integer order : orders) {
//do logic here
}
I have a list "List issues" this list will hold all the issues from all the projects.
From this "issues" object i can get issues.Project, Issues.Status inside the loop.
I wanted to do the below mentioned operations.
List<Issue> issues = issueCollector.get().getAppropriateIssues();
for (int i=0;i< issues.size();i++)
{
Issue iss = issues.get(i);
}
eg:
**Project IssueKey Status**
PRJ 1 issKey 1 Closed
PRJ 1 issKey 2 Resolved
PRJ 2 isskey 1 Open
PRJ 3 issKey 1 Closed
PRJ 3 issKey 2 Resolved
PRJ 3 issKey 3 Closed
I wanted to get the count of issues with respect to the PROJECT and store it in a variable. How to get the values like below and store in a collection vairable?
eg : PROJECT | Count(Issues)
PRJ 1 2
PRJ 2 1
PRJ 3 3
To get the count of issues in a project with the status in closed or resolved and store it in a variable. How to get the values like below and store in a collection vairable?
eg :
PROJECT | Count(Issues count whose in CLOSED or RESOLVED)
PRJ 1 2
PRJ 3 3
Then from this two variable, i want to check condition like
if(PRJ1(2 issues) == PRJ1(2 issues(with status)))
{
Add this PROJECT to a LIST of STRING
List<STRING> val = new List();
val.add(PROJECT);
}
For flexibility, (it can be that you have to check open issues or sum of this or that), I advise to introduce a small class IssueStatus which keeps all project issue counts. Java 8 allows you to construct it within another class btw.
class IssueStatus {
int numOfClosed = 0;
int numOfResolved = 0;
int numOfOpen = 0;
// not sure if status is string or enum
addStatusCount(String status) {
// logic to inc the num
// eg if "closed", then use numOfClosed++
}
getNumOfClosed() { return numOfClosed; }
getNumOfResolved() { return numOfResolved; }
getNumOfOpen() { return numOfOpen; }
getTotalIssues() { return numOfClosed + numOfResolved + numOfOpen; }
}
You can consider to add a project name to the object. But here, I've used a map to associate a given status to a project.
Map<String, IssueStatus> issueStatusMap = new ...
To populate the map, just use your loop
for (int i=0;i< issues.size();i++) {
Issue iss = issues.get(i);
// check if given project is already in map -> if not, add IssueStatus instance
if (! issueStatusMap.contains(iss.Project)) {
issueStatusMap.put(iss.Project, new IssueStatus());
}
// add issue status cound
issueStatusMap.get(iss.Project).addStatusCount(iss.Status);
}
You can use java 8's stream().forEach( ... ) to fill in the map though. Now, it's easy to have statistic information from your map.
// now you only have to get the data simply
// 1) sum of issues
for(Map.Entry<String, IssueStatus> entry : issueStatusMap.entrySet()) {
s.o.p("project name: " + entry.getKey() + " has " + entry.getValue().getTotalIssues());
}
// or use the sum of the three getNum... methods
// 2) count only closed + resolved
for(Map.Entry<String, IssueStatus> entry : issueStatusMap.entrySet()) {
IssueStatus is = entry.getValue();
s.o.p("project name: " + entry.getKey() + " status count: closed + resolved = " + (is.getNumOfClosed() + is.getNumOfResolved()));
}
Of course you can do all java 8's stream and group by, but I don't advise it because you have to perform another loop each time you're doing your task. This can be an exhaustive operation if the list of issues is very large.
Like in this example, if you want to get sum of counts and sum of "closed" and "resolved" issues by using Collectors.groupingBy, then you're going through that issue list two times. My solution requires one looping, with the cost of some extra heap space to store the objects. And when gathering the data, another small loop is used to go through all project status object instead of all issues. (if there are 100 projects with 5000 issues, then there is a big win)
Finally, to answer your last thing (I admit that this one isn't clear for me)
if(PRJ1(2 issues) == PRJ1(2 issues(with status)))
which is simply
IssueStatus status = issueStatusMap.get("<your projectName>");
if( status.getNum... == status.getNum... ) {
// do something
}
Use java8 collectors api for perform the grouping. check link https://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/
A simple approach; assuming that you actually have a Project class; you can use a Map<Project, List<Issues>> and from there:
Map<Project, List<Issues>> issuesByProject = new HashMap<>();
for (Issue issue : issues) {
if (issue status ... can be ignored) {
continue;
}
Project proj = issue.getProject();
if (issuesByProject.containsKey(proj)) {
issuesByProject.get(proj).add(issue);
} else {
List newListForProject = new ArrayList<>();
newListForProject.add(issue);
issuesByProject.put(proj, newListForProject);
}
}
This code iterates your list (using the simpler and to-be-preferred for-each looping style). Then we first check if that issue needs to be processed (by checking its status for example). If not, we stop that loop iteration and hop to the next one (using continue). If processing is required, we check if that map contains a list for the current project; if so, we simply add that issue. If not, we create a new list, add the issue, and then put the list into the map.
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.