Connect Four Program using 2D Arrays in Java - java

These are the specs for the program I need to complete. Could someone please help me!! I really need to get this program done! Will take any help/advice I can get! Thank you all so much!
You must create two programs named Board and ConFour that have the
following criteria:
1) Proper Introduction
2) Comments that accurately describe the program features
3) Board should have one attribute; a two dimensional array of
character values representing the Connect Four game board. Be sure
to include a constructor (without parameters) that instantiates the
2D-array with 6 rows and 7 columns
4) Board should contain at least four methods. The first method should
be setBoard() which adds an empty character value to every position in the board. The second method, setPosition(), should place the character representing a player (X or O) in the column of their choosing. The third method named checkWinner() should check the board to see if there are four of the same character (X or O) in a row, column or either diagonal. Lastly, printBoard(), should print the contents of the board.
5) ConFour should represent the game play. Have the user(s) enter
START to start the game (they should be able to continuously play after each game)
6) Start each turn by printing the board followed by asking the user to
enter the column they want (be sure to alternate players). If the user enters an incorrect column number, make them re-enter. First player to get four in a row, column or either diagonal is the winner.

Here is a little bit of my thoughts:
To start off, try to make algorithms that check for 4 Xs/Os in a row, which should be 4 for each player. You could also just make 4 algorithms that require you to input the number you are checking for. The directions you need to check are horizontal (check array[i][x+1], where i is the constant in the for loop and x is the number you find to be X or O), vertical (check array[x+1][i] ), right-facing diagonal (check array[i+1][x+1] ), and left-facing diagonal (check array[i-1][x-1].
To print the board, just use 2 for loops that print the values of the array.
For the intro, use a bunch of System.out.println() statements.
The entering of coins is the weird part. You have to create height variables (Or a height function) that stores/checks the height of the coins, then places it on top/next to the other coin. Then check if anyone wins and move on the next player. Keep repeating it until someone wins. Warning: Do not use a while loop. They can't check more than one boolean at a time (but you could put a bunch of if(check) {
boolean itsalltrue = true;
}s, too.
Well, that's all that I can think of (I deliberately did not write the code because I would like you write your own). Enjoy!

Is this for a class? Did you literally just copy and paste the assignment? Try spending some time looking through the notes provided for you, or search more specific questions here. Here's an example of a similar question with code:
Simple 2d array java game

Related

Searching a matrix for a chain of sums

I'm still trying to improve on my coding skills, and this question has got me spinning in my tracks a little bit, so any help is greatly appreciated. I know how to create the random array very easily, no problem with that. However, the logic of finding the chain is proving very difficult for me. I believe the proper approach is some sort of depth first searching algorithm, but I'm not entirely sure of how to implement that in this scenario, or whether that is even correct.
My basic question is, should I be using depth first search, and if so, should I be doing it recursively? Any tips or hints on implementation are also welcome!
Make a program that creates a 3x3 grid of random
positive numbers where 0 <= n <= 9. The program should
find all possible combinations of numbers that add up to the area of
the grid, or 9, using these rules (similar to Boggle):
a. The numbers must be "chained" in sequentially adjacent cells, where
"adjacent" cells are those horizontally, vertically, and diagonally
neighboring
b. The chain does not have to be in a line. For example, it could go
horizontally once, then vertically once, and finally diagonally once
c. At least the “grid width - 1” cells must be used in the chain (a
3x3 grid means that at least two cells must be used)
d. A chain cannot repeat a grid cell that it has already used
e. Chains that use the exact same cells as a previous chain are
considered repeats and should not be counted
I know that for each element, when you are searching through each adjacent element, you must check and keep track of whether it's been visited before, so you don't repeat numbers.
public class GridSolver {
int[][] workingGrid;
public GridSolver(int[][] workingGrid){
this.workingGrid = workingGrid;
}
public String solve(){
int length = this.workingGrid.length;
boolean[][] visited = new boolean[length][length];
for(int rows=0; rows<length; rows++){
for(int columns=0; columns<length; columns++){
if(visited[rows][columns] == false){
dfs(workingGrid[rows][columns]);
}
}
}
return null;
}
public HashSet<ArrayList<Integer>> dfs(int element){
HashSet<ArrayList<Integer>> chains = new HashSet<>();
checkLeft();
checkTopLeft();
checkTopMiddle();
checkTopRight();
checkRight();
checkBottomRight();
checkBottomMiddle();
checkBottomLeft();
return null;
}}
This is what I have so far and I realize that it is pretty sloppy and not the best thought out scheme, but that's why I'm here I guess :P.
Also just to explain some of my thinking in the code, the dfs()method has a return type of HashSet because I know that you can't have duplicate chains, and it is a set of a list of the chains. Also the "check" methods are not implemented, I just wrote them down because I know that you will need to process each of these adjacent blocks for each number.
Once again, any help is greatly appreciated, and thank you for humoring me as a beginner here!

longest path in a maze

i have an assignement to find the longest path in a maze using recursion. i also have to show the process of searching for the path. I think i get the idea of how its supposed to be done but i get myself into truble when it comes to the code. Now i don't want the code done for me. I just need some pointers and some tips on my logic. . this is my recursive method so far. I guess there is no point sharing the graphics methods since the recursive method is where im stuck at.
void findPath(Point a){ // starting point
if (a == mazeEnd){
pathAdd(a);
return;
}
if (wall(a)) return;
if (visited(a)) return;
if (a == mazeStart) pathAdd(a);
length++
printPath;
findPath(new Point(a.x+1, a.y));
findPath(new Point(a.x, a.y+1));
findPath(new Point(a.x-1, a.y));
findPath(new Point(a.x, a.y-1));
}
UPDATE: ok thank you all for the tips and let me further explain. the entire board is a grid. i read the walls, starting and enting point from a file. i create a list for the walls and palce them on the board. wall(a) checks if a coordinate is the walls array. pathAdd is a method taht adds a coordinate to the path array. but doesnt that means that after it has complyted all the paths, the path array will have every coordinate in that board except the ones that are walls? At least in the wway i have coded it. Thats my major issue i think. If i can get the list to only hold one path i guess ill figure out how to get the largest out of it.
There's a few omissions I see.
You never add the current point to your path - you only ever add the start or the end.
You never mark any points as visited.
You check to see if things are visited, but you don't have a way of knowing if they were visited in this path or some other path. Consider the scenario where there is some islands of walls, and you could reach a point via two or more routes: one of those routes may be longer than the other routes, but you're more likely to reach it via the short route first. It will end up being ignored, when it should be considered as a candidate for both routes.
You are triggering length++ on every call to find path. If you do your first node, and then the 4 nodes around it, you're going to have a length of 5 when your longest is 2. That's no good!
If you passed a list into the method, when you found a path that made it to the end of the maze, you could add it to the list. then when recursion finishes, you can iterate through the list to find the longest path.
You are restricting to move further when a cell/point is visited. But I didn't see you marked a cell/point as visited in your code. You can do this just before moving into the four directions. If you do not do this, your recursion will never get an end.
findPath(a) should return a length. Specifically it should return the max(findPath(up) || findpath(down) || findPath(left) || findPath(right)) + 1. If wall(a) or visisted(a), you can return a large negative number and for mazeEnd(a) return 1. To print the path you need to add the new Point that returns the greatest length with pathAdd(). Hope that helps :)

Vectors in Java - Yahtzee Game

I've been asked to program a Yahtzee game on Java. The thing is, I've got a vector of 5 values (which represent dice) and the values are randomly generated with this code:
Value= 1 + (int)(Math.random() * (5.999))
Now, the problem is that once the numbers are generated (or the dice have been thrown), the player is allowed to choose some of the values and hold them (make them constant), so then when the new values are generated, the ones selected don't change.
I've been trying to do this with a boolean variable, but with no luck. What would be the way to keep the values of a vector constant? I'd really appreciate any help, Thanks!
I suggest using a List<Integer>. Remove any values the player does not keep and then fill it back to size 5 at next throw.
Another way would be making a Dice class with randomize() and hold() methods, and have randomize() generate a new random value only if hold() has not been called.

Implemeting a File Character Analysis

I'm stuck on my assignment and wanted some pointers on an algorithm.
I am presented with text files that represent different images. blank space is where no pixels are on and '&' represents an on pixel.
The aim is i am given a 100 x 100 image text file to analyse and work out the probability that the object is there and then the co-ordinate of where it is on the file.
I know that i have to use character analysis of some sort but i feel that i have to check for example 10x10 grids at a time, analyse how many pixels are on and work out the certainty that the object is there. (This is because more or less pixels can be on and the object still present)
Thanks for your help.
I think I understand your question correctly. One thing that will change the answer is whether or not you know the object beforehand. If you are looking for an arbitrary pattern, it is somewhat more difficult, but still feasible. To find an object that you know what it will look like will come down to nested for loops and a solid understanding of 2D arrays. You can pull in each line of the text file and look for an '&'. If it finds one, it begins looking for the rest of the pattern based on the location relative to that first '&'.
For example, if you are looking for a diagonal line from top left to bottom right, you would continue along until you came to the first '&'. After that, you would look at the cell one column over and 1 row down. If that is an ampersand as well, you know that you have a diagonal line. If not, just keep going along after the first '&'.
for (int c = 0; c < textArray.length; c++)
{
for (int i = 0; i < textArray[c].length; i++)
{
Look at the character
If it is '&'
Look for the next character and so forth
If the pattern is there
return true
}
}
See if that helps get your algorithm rolling. You will need to make sure to check for legal bounds in your arrays in order to combat out of bounds exceptions.

Interview question: Create an object oriented design for Sudoku

I answered that I will have have a 2d Array.
And then I will have 3 functions
one to check the horizontal condition.
another function to check vertical condition
and another one the check the 3*3 block condition.
But he is not satisfied, can any one give a good answer for this question?
I found this stack overflow link related to my question.
Programming Design Help - How to Structure a Sudoku Solver program?.
But I want a proper object oriented design (like what should be the classes, inheritance and other details) which are the same things interviewer expected from me.
To me, your design starts with a "region" class. You can then extend this to be a "horizontal region" "vertical region" and "square region" as the three types of regions. Edit: upon further consideration you don't really need to make this distinction unless it's for display purposes... algorithmically it will be the same.
Then you can make your 2d array of "elements" and add the elements appropriately to your regions, which provides a network for your calculations. Your elements have a list of potential values, and your regions are responsible for removing those potential values. When you have a value found, it triggers the regions it is a member of to remove the potential values from those too.
For base classes of a solver, I see a good start with Cell, ValidationRegion, Board, and Pattern as your main classes.
Cell: Has the current value of the cell, the remaining possible values of the cell, and if the cell is fixed or not.
ValidationRegion: Has references to the appropriate 9 Cells on the Board. This class doesn't really need to know if it is representing horizontal, vertical, or a square regions, because the rules are the same. This class has a validate() method to verify that the current state of the region is possible.
Board: Has the entire layout of Cells, and initializes the fixed ValidationRegions appropriately by passing the appropriate Cells by reference. It also has a solve method that applies Patterns in a pre-defined order until a solution is reached or it is determined that no solution is possible (brute-force pattern must therefore be the last ditch effort).
Pattern: Abstract class that has an apply(Board) method that applies the given pattern to the specified board object (removes possibilities from Cells and sets them when it knows there is only one possibility left). From Sudoku Dragon - Sudoku Strategy, you'll likely implement patterns like OneChoicePattern, SinglePossibilityPattern, OnlySquareRule, etc.
If the question was just "What's an object-oriented design for Sudoku" and you went off and started telling him stuff, he may have been disappointed that you didn't ask for actual requirements. "Sudoku" is pretty broad. Just a data representation? A solver? A means to play? A validator? A puzzle creator?
Until you know what he wanted you to build, you can't really design a solution.
For an Object-Oriented approach to Sudoku I'd do something like this (just using simple names):
A NumberSpace is a single square on the Sudoku board and capable of holding a number from 1-9.
A Block is a grouping of 9 NumberSpaces in a 3x3 pattern, Which would probably just be represented in the class as a multidimensional array of NumberSpace objects. Methods on this could include (bool)validate which would test to make sure no number is repeated per block.
Finally, a Board would represent the entire gaming area where which would be another array (3x3) of Blocks. Methods for this class would include means for verifying the validity of columns/rows.
Two outstanding classes raise from this problem, the main game board and a cell holding a value.
In C#, this would be:
// Main game board
public class BoardGame{
List<List<Cell> cells = new List<List<Cell>>();
public BoardGame(int dimention){
// Initialize and add cells to the cells attribute
}
public bool HorizLineContainsValue(int lineNumber, value){
// return true if any cell in horiz. line number contains value
}
public bool VertLineContainsValue(int lineNumber, value){
// return true if any cell in vertic. line number contains value
}
}
public class Cell {
// X index on the game board
public int X{get; set;}
// Y index on the game board
public int Y{get; set;}
// Value of this cell
public int Value{get; set;}
// Set game board
public GameBoard GameBoard{set;}
public boolean AcceptValue(int value){
// Ask the game board if cells on horizontal line X have this value
// Ask the game board if cells on vertical line Y have this value
// And return true or false accordingly
}
}
If you wish to consider the 3*3 block then you might go for the composite design pattern which will fit this problem very well.
Here is a link to a very interesting and pragmatic book resolving a complex game using OOAD and design patterns
I am not sure about this, but I have a feeling that the interviewer probably wanted something like MVC pattern etc, a high level design/architecture. Then, within this context, you will have three modules/components: model, view and controller. Each of which is then made up of one or more classes. For most interactive applications, this pattern or some variation/related pattern is applicable.
I would say this would have been enough. Since, in an interview you don't have enough time to come up with details of classes, neither it is necessary to do so (at least in typical cases).

Categories