the problem consists in that you have to solve a problem where exists n-cities and n-colors , every city have a color but the cities adjacent can't have the same color.
The teacher send this homework for investigate how to solve it , we are working on java - eclipse and we are so confused . Can you help us being really explicit , thanks so much. the last topic was recursion.
P.D: some people say that it solve by graphs but we are not sure and we dont understand really good .
If I were you, I would make 2 loops for, one inside the other, like this:
for (i = 0; i < n_cities; i++)
{
for (j = 0; j < n_colours; j++)
{
}
}
In this way, you will be able to walk all the possible combinations. In the second loop, you will have to make the comparison if the cities around citie i have the same colour, if not, try with the next colour, and this for all the n-iterations.
How to know if the cities adjacent are with the same colour? Well, you can create a n-vector in which you will save all the colours of all the cities. The position of the vector could be the i-citie and the value saved in the position could be the colour of this citie.
I expect it will be useful for you :)
There are probably many solutions, but the first one that came to mind is having an ArrayList containing CityColor instances. My CityColor class holds the city name and color. When adding to the ArrayList, you would check to make sure the adjacent elements of the ArrayList do not have the same color. If it does have the same color, use recursion to select another color until you get an acceptable color.
Your ArrayList would have objects such as:
public class CityColor {
private String city;
private String color;
public CityColor(String city, String color) {
this.city = city;
this.color = color;
}
// set/get methods for the variables
}
If you have an array of colors, you can use Math.Random to select a random color. If the color matches an adjacent color, use recursion to select another.
Related
I'm trying to implement a class to check if two game objects intersect. Can anyone give me a better solution / more elegant to this problem?
Basically I want to addCollision and know if one object collidesWith another. A double entry matrix seemed a good idea.
private class CollisionMatrix {
private boolean[][] matrix;
private HashMap<Tag, Integer> matrixIndexes = new HashMap<Tag, Integer>();
public CollisionMatrix() {
int i = 0;
for (Tag tag : Tag.values())
matrixIndexes.put(tag, i++);
matrix = new boolean[i][i];
}
private void addCollision(Tag tag1, Tag tag2) {
int p1 = matrixIndexes.get(tag1);
int p2 = matrixIndexes.get(tag2);
matrix[p1][p2] = true;
matrix[p2][p1] = true;
}
private boolean collidesWith(Tag tag1, Tag tag2) {
int p1 = matrixIndexes.get(tag1);
int p2 = matrixIndexes.get(tag2);
return matrix[p1][p2] || matrix[p2][p1];
}
}
This is not a complete answer, but it should set you on a path to get a more complete solution.
The simplest (not efficient) way to do this is to have a list of the objects that can collide with each other and then for every frame in time, got through every object in the list and check if the object collides (Shares the same space or bounding volume) with another one in the list.
pseudo code:
L: list of objects that can potentially collide.
t: time
for each frame in t {
for each object obj in L {
P: list of objects without obj
for each object otherObj in P {
does obj collide with otherObj
}
}
}
While this technically works, it's not a good solution as it will be very slow as soon as you start having many objects, and it doesn't take that many to make it slow.
To make this possible in real time, you would need to add some acceleration techniques.
One of these acceleration techniques is using "Bounding volume hierarchy" or BVH. https://en.wikipedia.org/wiki/Bounding_volume_hierarchy
In a nutshell, BVH is technique or algorithm to enable quick lookups of which objects are likely to collide.
It typically uses some type of tree structure to keep track of the positions and volumes occupied by the said objects. Tree structures provide faster lookup times than just linearly iterating a list multiple times.
Each level of the tree provides a hierarchy of bounding volumes (space the object is likely to occupy). Top levels of the tree provide a bigger volume for the particular object (a more rough, less granular or less fitting to the object's shape), but easier to discard if the object in question is not in that same space (you would know with little calculations that the object would never collide with anything in that same bounding volume). The deeper in the tree you go, the more granular or more fitting to the objects shape the bounding volumes get, until you get the objects which collide.
Hope this helps :)
I've exhausted my understanding of Tableau. I'm trying to color every icon below the risk average the color red, and above the color green. Here is an attempt at an articulation in Java of my intention (this code may not be correct, but I want the intention translated into Tableau).
This is my Tableau code that doesn't work:
IF [Commercial Services] <= [Risk Average] *The variable I want to create*
THEN "Red"
ELSEIF [Commercial Services] > [Risk Average]
THEN "Green"
END
Here's the Java code I think is closer to what I need converted:
final int NUM_ROWS = 39;
int count = 0;
while(count < NUM_ROWS) {
if(count.commercial_services < count.risk_average) {
shape.color = "Red";
} elseif(count.commercial_services > count.risk_average) {
shape.color = "Green";
} else {
shape.color = "Blue";
}
count++;
}
Please help me create a variable that I could use to color each risk in reference to the risk average.
I have attached a spreadsheet and an image for reference.
Thanks in advance.
That is not the way Tableau works. For such purposes, you should first create a flag-like calculated field to form values according to your conditions. And then use that field as a shape or color identifier dragging it to the Marks card.
So for your case you may create a field like below (which is almost the same you did), which means it will have the value of "Red" for CS<=RA condition and "Green" for the other condition. Only that Tableau does not know what to do with these string variables at the moment. You may assign -1 or 1 instead of these strings, it does make no change.
IF [Commercial Services] <= [Risk Average]
THEN "Red"
ELSE "Green"
END
And now you have new column in your data which have "Red" or "Green" values at each row. You may now drag this field to Marks card and select is as Color or as normal pill and select its type as Shape then use standard arrows or make your custom shapes according to your needs. At this phase, you will be selecting with which colours or shapes should your "Red" & "Green" values be represented by.
I or someone else might be in more help if you share your tableau workbook with what you have done so far.
I'm trying to create random items in a libgdx project.I'm relatively new to Java,but here is the code I've come up with for the method.
I've been at this for a week now,and figured I'd ask here for an answer.
I've been trying to come up with something that works first.So please do forgive the shabby code.
The number parameter of the method is the number of items that will be created.
The item just needs to have a random x positon,which is generated within the constraints of the width of the container.
The game is as bottom up scroller,with different platforms being generated.
private Item[] generateRandomItems(int number){
Money[] items=new Money[number];
for(int i=0;i<number;i++){
Random r=new Random();
int x =r.nextInt(120)+3;//136 is the width of the container to which the item is to be generated
Money tempitem=generateMoney(x);//generateMoney() just returns a new instance of the Money class with the created x passed in as a param.
if(i!=0) {
for (int j=0;j<i;j++) {
boolean failed=true;
while (failed) {
//getItem() returns the bounding rectangle/circle f the item
if (!Intersector.overlaps(tempitem.getItem(), items[j].getItem())) {
failed = false;
items[i] = tempitem;
}else{
Random random= new Random();
int newX=random.nextInt(120)+3;
tempitem=generateMoney(newX);
}
}
}
}else{
items[i]=tempitem;
}
}
return items;
}
I don't know if this is a correct way to do it or not,but the created Items do collide sometimes.I've been trying to find what's wrong with the code for sometime now.Any suggestions to improve the code are also appreciated.
Edit::I Know that the code is unnecessarily complicated.This is my first attempt at procedural generation.So please do forgive me.
Instead of generating a new random position if there is a collision, you should move it deliberately left or right until there is no collision. To illustrate the problem reusing random generation after each collision, if you have 10 slots and 9 slots are already filled, it could take a long time to find that open slot using random generation as you would be almost certain to hit the same object numerous times. However, if you keep track of where you’ve checked and deliberately move to a new location each time, then the worst case scenario is you’d hit each object one time before finding the empty slot.
You can check how much of an overlap there is and move the object by that amount to clear the object, then check to make sure it didn’t collide with another object next to it, if it did then keep moving it over until there is a free spot. If you hit the edge of the screen, move to the opposite side and keep moving until you find a free spot.
Also, as good coding practice you should avoid hard coding numbers (like 120+3) into method calls. Since you use the same value in multiple places, if you decide to change the width of your container to 500, then you have to change it in all those places...and if you forget to change one you’re opening yourself up for a nightmare of bug hunting. Instead you can either set an integer such as containerWidth=120 or set the container width directly using container.setWidth(120) and then use container.getWidth() each time you call your random method to get the width of the container the random value is being constrained too. Either way will work fine, whichever is better for your workflow. And I know you said this was quick and sloppy code just to get it going, so you may already be aware of this.
Thanks for the answers.I now know that checking each generated item for collision without saving the previously generated item is bad.
But I got the previous code working after some help,and wanted to share it with anyone who would need it in the future.
I moved the checking part into a new method,and added a new flag to see if the item was generated correctly,after checking for collision from all the items before it.
private Item[] generateRandomItems(int number){
Money[] items=new Money[number];
for(int i=0;i<number;i++){
Random r=new Random();
int x =r.nextInt(120)+3;
Money tempitem=generateMoney(x);
if(i>0) {
boolean generated=false;
while (!generated) {
boolean f = checkIfItemOverlapsWithPrevious(items, tempitem);
if (!f) {
items[i] = tempitem;
generated = true;
} else {
Random random = new Random();
int newX = random.nextInt(120) + 3;
System.out.println("Collided");
tempitem = generateMoney(newX);
}
}
}else{
items[i]=tempitem;
}
}
return items;
}
private boolean checkIfItemOverlapsWithPrevious(Money[] items, Money tempitem) {
for(Money item :items){
if(item!=null) {
if (Intersector.overlaps(tempitem.getItem(), item.getItem())) {
return true;
}
}
}
return false;
}
I am working on a lab, it's a connect four game. I'm having trouble specifically with basic concepts like how classes communicate with each other, how to use private instance variables, how to use an ArrayList, how to compare JLabels or set them as something comparable...
To give a brief breakdown I have four classes GUI, Game, Player, Name
I can create the GUI by using two four loops, the game is a grid with 7 columns of 6 pieces. The pieces are images,
JLabel Piece = new JLabel("images/blank.png");
for example to denote an empty spot.
The GUI is based on a JFrame, single content pane and four panels, one for a header which indicates who is playing and who won, another for the 7 buttons accompanying the 7 rows, the grid itself of the possible places to be played and then a button panel which gives you the option to replay.
I'm lacking in a lot of concepts. For instance, the replay button shouldn't appear until the game has ended.
I don't understand how to use an ArrayList. I tried to use
ArrayList<ArrayList<JLabel>> myList = new ArrayList<ArrayList<JLabel>>();
So when I create the GUI by running two for loops like so
For ( c = 0 ; c<8 ; c++) {
ArrayList<JLabel> column = new ArrayList<JLabel>();
For ( r = 0 ; r<7 ; r++) {
ArrayList<JLabel> row = new ArrayList<JLabel>();
JLabel empty = new JLabel("images/blank.png");
row.add(empty);
}
column.add(row);
}
Even this small step I've already got confused.
I know the two for loops above are not correct specifically the ArrayList.
I don't know how to create the arraylist and then use them.
using something like
column.get().get();
myList.get().get();
to get a specific piece.
I don't know how to pass that to an argument so that for example if I push on button 7 for column 7, and no pieces have been played yet, I can start from the lowest area column 7 row 6 and update that to a played piece, red or yellow for the appropriate player.
This is vague and I doubt I'll get anywhere but I am desperate for help. There isn't much time available from the TA's / Teacher and I believe I am lacking significantly to be able to finish this project.
I understand how it works/what I have to do in words but in terms of applying Java code...
I'd appreciate any help.
OK first off you should use an array of Enums. ArrayLists are intended for lots of items and that can have rapidly changing numbers. Arrays are intended to house data in a grid of some sorts. Since you are using a static board, use arrays! They are also much less memory-intensive. Example:
//Note you should use [column][row] as that is common practice.
States[][] grid = new States[7][6];
//And initialize it:
for(int i = 0; i < grid.length; i++)
for(int o = 0; o < grid[i].length; o++)
grid[i][o] = EMPTY_JLABEL;
Then declare an enum (this is a new class) (NOTE: replace FULL_PLAYER_ONE_JLABEL and FULL_PLAYER_TWO_JLABEL with the JLabels that have the image for each.):
public enum States {
FULL_PLAYER_ONE(FULL_PLAYER_ONE_JLABEL), FULL_PLAYER_TWO(FULL_PLAYER_TWO_JLABEL), EMPTY(EMPTY_JLABEL);
//The image of the appropriate state.
private JLabel label;
//Enum constructors must be private
private States(JLabel label) {
this.label = label;
}
public JLabel getLabel() {
return label;
}
}
In your GUI, have a JButton that is only added to the frame when the game is over. Also add a button to indicate when each column has been clicked by the player.
JButton button = new JButton();
//Initialize JButton and add to frame...
//Anytime before the frame is set to visible:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* Perform tests for for what should happen.
For example test whose turn it is then call a method to add a piece to that column. Then call a checker to see if someone has won. If so, display the replay button, otherwise do nothing (allow other player to move).
*/
}
}
I've seen this in a code of tetris game and I'm wondering how these values are able to draw the line, T-shape, S-shape, Z-shape, L-shape, inverted-L and a sqaure.
I get the four parametes maybe because of the four blocks needed per piece. But how did they come up with values like that? Have those something to do with the color too?
int blocks[][] = {
{0x0f00, 0x4444, 0x0f00, 0x4444}, // LINE
{0x04e0, 0x0464, 0x00e4, 0x04c4}, // T
{0x4620, 0x6c00, 0x4620, 0x6c00}, // S
{0x2640, 0xc600, 0x2640, 0xc600}, // Z
{0x6220, 0x1700, 0x2230, 0x0740}, // 7
{0x6440, 0x0e20, 0x44c0, 0x8e00}, // inverted 7
{0x0660, 0x0660, 0x0660, 0x0660}, // square
}
I'm new in Java and I want to learn to "draw" using those values. Thank you very much!
Each row of the table is one shape. Each column is a different rotation for the shape. The square, for instance, is the same no matter how you rotate it. The line (first row) flips between two patterns. I found this in a web search:
http://codeincomplete.com/posts/2011/10/10/javascript_tetris/