I'm trying to create a program that arranges 6 cards on a grid in a specific way so that no card is adjacent to other cards of the same type (the types being king, queen and jack). The grid is 4x4 but I can only place cards inside the following pattern:
[ ][ ][x][ ]
[x][x][x][ ]
[ ][x][x][x]
[ ][ ][x][ ]
Now, my main problem is when my method tries to check the adjacent cells for card types. When it starts at 0,0 it tries to check [row-1][column] which obviously won't work since that translates to -1,0. The problem is, I have no idea how implement this properly.
I apologise if this question has been asked before, as I wasn't sure what to search for exactly (or how to properly name this problem).
private boolean bordersCard(int row, int column, char cardChar)
{
Candidate center = board[row][column];
Candidate top;
Candidate bottom;
Candidate left;
Candidate right;
if (board[row-1][column] != null){
top = board[row+1][column];
}
else
{
top = new Candidate('?', 0);
}
if (board[row+1][column] != null){
bottom = board[row+1][column];
}
else
{
bottom = new Candidate('?', 0);
}
if (board[row][column-1] != null){
left = board[row][column-1];
}
else
{
left = new Candidate('?', 0);
}
if (board[row][column+1] != null){
right = board[row][column+1];
}
else
{
right = new Candidate('?', 0);
}
if ((center.getCardChar() == top.getCardChar()) || (center.getCardChar() == bottom.getCardChar()) ||
(center.getCardChar() == left.getCardChar()) || (center.getCardChar() == right.getCardChar())){
return false;
}
return true;
}
You have to add if fences to prevent the invalid checks:
if (row > 0 && board[row-1][column] != null){
top = board[row+1][column];
}
If any of the indexes are out of bounds assign them to NULL. In Candidate create a method isSameType(Candidate other);
isSameType(Candidate other)
{
if(other == null)
return false;
else
retrun getCardChar() == other.getCardChar();
}
change your if to:
if(center.isSameType(top) || center.isSameType(bottom) || ...)
{
return false;
}
As you have determined, checking [-1][0] doesn't work. But you don't need to check that non-existent slot. Just make sure you don't run off the beginning or the end of the array. Also, make sure you are performing the same math operation inside your if as in your condition:
if ((row - 1) >= 0 && (row - 1) < board.length && board[row-1][column] != null){
top = board[row-1][column]; // Use -1 to match condition.
}
Related
I am pretty far along on my project dealing with singly circular linked lists and am still having trouble with one point. My trouble stems from not being able to/knowing how to call the node before the node containing the first of the four consecutive colors and referring it to the beginning.
Prompt for Marbles game:
Place random marbles in a circle and if four of the same color appear, remove them and add four times the color score to the total score.
I would really appreciate if someone could help me figure how to resolve this problem..
Here's the code I'm working on:
public void deleteQuadruples()
{
//if the list has 4 nodes, delete all and make a new head
if (size == 4 && (start.getaMarble().getNumber() == start.getNextLink().getaMarble().getNumber()
&& start.getNextLink().getaMarble().getNumber() == start.getNextLink().getNextLink().getaMarble().getNumber()
&& start.getNextLink().getNextLink().getaMarble().getNumber() == start.getNextLink().getNextLink().getNextLink().getaMarble().getNumber()))
{
sum = 4*start.getaMarble().getNumber();
start = new Link(null, null);
addFirstMarble();
}
//else go thru the list and find whether or not there are four consecutive marbles of the same color/number and if so take them out
else
{
Link tmp = start;
if (tmp == null)
{
return;
}
do
{
/*int colorNumber = tmp.getaMarble().getNumber();
int counter = 1;
tmp = tmp.getNextLink();
if(colorNumber == tmp.getaMarble().getNumber())
{
counter++;
}
if(counter == 4)
{
score += 4*tmp.getaMarble().getNumber();
counter = 1;
//delete the 4 consecutive elements
}
if(tmp.getNextLink() == start && counter == 3 && start.getaMarble().getColor() == tmp.getaMarble().getColor())
{
score += 4*tmp.getaMarble().getNumber();
start = start.getNextLink();
//delete the 4 consecutive elements
}*/
for(Link cursor = start; cursor != end; cursor = cursor.getNextLink)
{
Link temp;
counter = 1;
if(cursor.getaMarble().getNumber() == cursor.getNextLink().getaMarble().getNumber())
{
counter++;
}
if(cursor.getaMarble().getNextLink().getNumber() != cursor.getNextLink().getNextLink().getaMarble().getNumber())
{
counter = 1;
}
if (counter == 4)
{
//deletes the four consecutive nodes with same color
//something.getNextLink() = start;
score += 4* cursor.getaMarble.getNumber();
}
}
}
while (tmp != start);
}
}
I made some changes to your code (it may not compile but will give an idea)
public void deleteQuadruples()
{
if (start == null || size == 3)
return;
//if the list has 4 nodes, delete all and make a new head
if (size == 4 && (start.getaMarble().getNumber() == start.getNextLink().getaMarble().getNumber()
&& start.getNextLink().getaMarble().getNumber() == start.getNextLink().getNextLink().getaMarble().getNumber()
&& start.getNextLink().getNextLink().getaMarble().getNumber() == start.getNextLink().getNextLink().getNextLink().getaMarble().getNumber()))
{
sum = 4*start.getaMarble().getNumber();
start = new Link(null, null);
addFirstMarble();
}
//else go thru the list and find whether or not there are four consecutive marbles of the same color/number and if so take them out
else
{
Node end = start;
while (end.getNextLink().getaMarble().getNumber() != start.getNextLink().getaMarble().getNumber())
{ end = end.getNextLink(); }
// no data
if(end.getNextLink().getaMarble().getNumber() == start.getaMarble().getNumber())
return;
// we have data
else {
sum = 4*start.getaMarble().getNumber();
// loop four times
// set the end.getNextLink() with start.getNextLink()
}
}
}
I'm suppose to create a code that recognizes if my hand has the same card faces
public static boolean sameFace(String hand) {
hand = "s9s7s2sQsK";
char f = hand.charAt(0);
if( hand.charAt(0)==hand.charAt(2) && hand.charAt(0)==hand.charAt(4)
&& hand.charAt(0)==hand.charAt(6) && hand.charAt(0)==hand.charAt(8));
return (hand.charAt(0) == hand.charAt(2) && hand.charAt(0) == hand.charAt(4)
&& hand.charAt(0) == hand.charAt(6) && hand.charAt(0) == hand.charAt(8));
sameface = hand;
if (hand==true;)
return (hand==true;) ;
}
As can be seen above, if all positions are the same characters, it comes true(False, if even one isn't the same.) How can I then use the result of that "return" to let my program recognize it has the same faces or not? If that is even possible.
From what i know, based on my code, it's saying "Yes, positions x=y=z are the same" how can I then tell it "Since they are the same, they have the same card faces."
I tried to put this at the end
sameface = hand;
if (hand==true;)
return (hand==true;) ;
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
You do that simply by returning the result of the expression:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
return f == hand.charAt(2) &&
f == hand.charAt(4) &&
f == hand.charAt(6) &&
f == hand.charAt(8);
}
Or if you want to be friendly to a different number of cards, use a loop:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
for (int i = 2, len = hand.length(); i < len; i += 2) {
if (f != hand.charAt(i)) {
// Not a match
return false;
}
}
// All matched
return true;
}
I have created in my program my own LinkedList (not from java.util) of cards.
Each card is an object made of 2 ints - the first one is a value ("wartosc" in my code) of a card (from 1 to 13), second is a colour ("kolor" in my code) for a card (from 0 to 3).
The list is randomly generated and the list is created when a value is 0.
Now I have to modify "add" method ("dodaj" in my code) to make it add cards in correct place in the list. Not sorting method adds cards and the rest works fine (all cards are shown) but when I use method that is supposed to add cards in order and when I then try to print list of cards it shows only like from 2 to 5 of them - all sorted except for the last one. But when I print the size of list ot shows numbers like 20 or even 40, even though I print only 4. So i would like to know what is wrong. Here is the code:
public class Lista {
private Element pocz; //start
public int rozmiar;
public Lista() {
boolean zrobione = false;
while (zrobione != true) {
Karta karta = new Karta();
if (karta.getWartosc() == 0) {
zrobione = true;
} else {
this.dodaj(karta);
}
}
}
public void dodaj(Karta k){
if(pocz == null)
pocz = new Element(k);
Element pom = new Element(k);
Element obecny = pocz;
boolean zrobione = false;
if(obecny != null && !zrobione){
while(obecny.getNext() !=null && (obecny.getNext().getKarta().wartosc > obecny.getKarta().wartosc || (obecny.getNext().getKarta().wartosc == obecny.getKarta().wartosc && obecny.getNext().getKarta().kolor > obecny.getKarta().kolor))){
obecny = obecny.getNext();
}
obecny.setNext(pom);
zrobione = true;
}
rozmiar++;
}
// public void dodaj(Karta k) {
// if (pocz == null) {
// pocz = new Element(k);
// }
//
// Element pom = new Element(k);
// Element obecny = pocz;
// if (obecny != null) {
// while (obecny.getNext() != null) {
// obecny = obecny.getNext();
// }
// obecny.setNext(pom);
// }
// rozmiar++;
// }
public int getRozmiar(){
return rozmiar;
}
public void drukujOKolorze(int kolor){
if(kolor<0 || kolor>4)
System.out.println("Bledny kolor");
else{
Element obecny = null;
if(pocz != null){
obecny = pocz.getNext();
while(obecny.getNext() != null){
if(obecny.getKarta().kolor == kolor)
System.out.println(obecny.getKarta().toString());
obecny = obecny.getNext();
}
}
}
}
public void drukujOWartosci(int wartosc){
if(wartosc<0 || wartosc>13)
System.out.println("Bledna wartosc");
else{
Element obecny = null;
if(pocz != null){
obecny = pocz.getNext();
while(obecny.getNext() != null){
if(obecny.getKarta().wartosc == wartosc)
System.out.println(obecny.getKarta().toString());
obecny = obecny.getNext();
}
}
}
}
public void wyswietl(){
if(pocz != null){
Element obecny = pocz.getNext();
while(obecny != null) {
System.out.println(obecny.getKarta().toString());
obecny = obecny.getNext();
}
}
}
}
Sorry for not using English names - I will put below a short dictionary :)
Lista() is constructor of List it checks if generated value is 0, then uses "dodaj" method
"dodaj" method is "add" the first one is supposed to sort cards
second "dodaj" that i put i comment for now was the 1st one that just adds new
cards. They aren't sorted but next methods work as intended when I use this one.
getRozmiar() returns size of List, "rozmiar" means "size"
"drukujOKolorze" and "drukujOWartosci" are supposed to print respectively:
cards of given colour and cards of given value - they work fine.
and finally "wyswietl" which is "print". When i use the second "dodaj" it prints all the cards that are in list. When I use the first "dodaj" it shows only like 2 to 5 cards and the last one is never sorted while "getSize()" shows that there is more cards in the list.
I hope You guys will help me. I have no idea what goes wrong here and no, I can't use compareTo. My task is to write method that will put cards in order.
When you find the place that you want to put your card, you are setting it as the next item in the linked list, but not re-attaching the rest of the list after the new entry, effectively removing all cards after the insertion point.
Imagine it as an actual chain of metal links.
You open one of the links in the middle, breaking the chain into two pieces, then add the new link to one side. However, you are not attaching the other half of the chain to the new link, so it is lost.
Try this:
public void dodaj(Karta k){
if(pocz == null)
pocz = new Element(k);
Element pom = new Element(k);
Element obecny = pocz;
boolean zrobione = false;
if(obecny != null && !zrobione){
while(obecny.getNext() !=null && (obecny.getNext().getKarta().wartosc > pom.getKarta().wartosc || (obecny.getNext().getKarta().wartosc == pom.getKarta().wartosc && obecny.getNext().getKarta().kolor > pom.getKarta().kolor))){ // Modified line
obecny = obecny.getNext();
}
pom.setNext(obecny.getNext()); // Added line
obecny.setNext(pom);
zrobione = true;
}
rozmiar++;
}
The program is using backtracking to find out a way out of the maze(which it does fine). The problem occurs when I try to print out the correct path I took.
This is my solveMaze() method.
boolean result = false;
while(result==false){
if((row > 29) || (row < 0) || (col > 19) || (col < 0)) //check if position is within the array
return false;
if(maze[row][col].getVar().equals("E")) // check if youre at the exit
return true;
if(maze[row][col].getVar().equals("1")) // check if youre hitting a wall
return false;
if(maze[row][col].position.size() > 2){ // check if youre at an intersection
intersection[numIntersection] = maze[row][col]; // add intersection to intersection array
numIntersection++;
}
//this section does not need to be checked if youve never visited the position before
if(maze[row][col].getVisted() == true && numIntersection > 0){
if(intersection[numIntersection-1] == null)
return false;
else if(intersection[numIntersection-1] != null){ //as you backtrack to the last intersection pick up your "markers"
maze[row][col].setVar("0");
if(maze[row][col].position == intersection[numIntersection-1].position && intersection[numIntersection-1].getVisted()==true){ //remove intersection from the array as you pass back thru
maze[row][col].setVar("+");
intersection[numIntersection-1] = null;
numIntersection--;
}
}
}
if(maze[row][col].position.empty()==true) //check if the stack is empty
return false;
maze[row][col].position.pop();
if(maze[row][col].getVisted() == false)
maze[row][col].setVar("+"); //mark path as you land on unvisted positions
maze[row][col].setVisted(true);
//look north
if(solveMaze(row-1,col)== true)
return true;
//look east
if(solveMaze(row,col+1)== true){
return true;
}
//look west
if(solveMaze(row,col-1)== true){
return true;
}
//look south
if(solveMaze(row+1,col)== true){
return true;
}
}
return false;
}
As I backtrack I am picking back up my markers but it seems to be picking up markers on the correct path also and prints a maze with a broken up path.
So im working on this program that will recursively solve a maze that i get from a txt file. I put the maze into a 2d array. Here is an example of the most simple maze.
+-+-+-+
|S| |
+ + + +
| |E|
+-+-+-+
i know im probably not going about solving the maze in the best way but i think my way works i just need to know how to break out of my recursion loop. What im doing is checking if there is a boarder in the next place and if there is a '*' two places later if not then i move there and put down a marker. This got me to the end of the maze but it breaks after. I need a way to break out of the loop. I just started learning about recursion so i think this is the problem but im not exactly sure.
The wrong choice method will return me to the last place where there is a cell with an open boarder and a no '*' with in two places.
public static void solveMaze(int COL, int ROW){
//find first open cell and choose it
if(drawArray[COL][ROW+1] == ' ' && drawArray[COL][ROW+2] != '*'){
//if(drawArray[COL][ROW+2] == 'E')
drawArray[COL][ROW+2] = '*';
ROW+= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL+1][ROW] == ' ' && drawArray[COL+2][ROW] != '*'){
drawArray[COL+2][ROW] = '*';
COL+= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL][ROW-1] == ' ' && drawArray[COL][ROW-2] != '*'){
drawArray[COL][ROW-2] = '*';
ROW-= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL-1][ROW] == ' ' && drawArray[COL-2][ROW] != '*'){
drawArray[COL-2][ROW] = '*';
COL+= 2;
solveMaze(COL,ROW);
}
else
wrongChoice(COL,ROW);
}
One can provide a partial result (initially empty) as parameter. And one can return a result.
Another parameter for recursion often is the set of possible candidates.
For instance something like:
public static void solveMaze(int COL, int ROW, Path pathTaken) {
Path pathTaken = new Path();
if (solveMazeRecursively(START_COL, START_ROW, pathTaken)) {
...
}
}
private static boolean solveMazeRecursively(int COL, int ROW, Path pathTaken) {
if (drawArray[COL][ROW+1] == 'E') {
System.out.println(pathTaken);
return true;
}
// The real work...
if (drawArray[COL][ROW+1] == ' ' && drawArray[COL][ROW+2] != '*'){
drawArray[COL][ROW+2] = '*';
ROW += 2;
takenPath.add(COL, ROW+2);
if (solveMazeRecursively(COL,ROW, takenPath)) {
return true;
}
takenPath.remove(COL, ROW+2);
}
Recursion implies being lazy checking first whether nothing has to be done (solution present, or impossible to continue), and otherwise delegating to new function instances.