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).
Related
I'm writing a chess engine in Java and using bitboards to represent the board (12 64-bit numbers). The size of an instance of this class(its retained size) is 152Bytes according to IntelliJ debugger.
When trying to see a few moves a head, for each move I consider I create a new instance to represent the new Board state. Below is what the Board class looks like approximately.
public long WP=0L, WN=0L, WB=0L, WR=0L, WQ=0L, WK=0L, BP=0L, BN=0L, BB=0L, BR=0L, BQ=0L, BK=0L;
long NOT_WHITE_PIECES;
long WHITE_PIECES;
long BLACK_PIECES;
long OCCUPIED;
long EMPTY;
public void updateBitboards() {}
public void updateMailbox() {}
public void movePiece(Move move) {}
public void drawBitboard() {}
Other fields and methods are static so I don't think they affect the size of an instance.
The problem is, even if I want to consider only the first 4 moves in chess, there's ~8,000,000 possible combination of moves. So I'm going to end up storing a total of 8,000,000*152B = 1,216,000,000B... which is 1.2GB.
I feel like I'm missing something here. How can I increase the number of positions I consider at a time?
First, you don't want to create a new instance of the board state each move. If you are using e.g. Minimax then you make the move, make recursive call, then unmake the move. This way you always just have one board state which it considers.
Then to minimize the number of moves you need to consider you want to make enhancements to the algorithm. The most common to start with is alpha-beta pruning which you can read more about here: https://www.chessprogramming.org/Alpha-Beta. Alpha beta pruning will always yield the same result as a minimax, but you consider less positions since you don't search the hopeless ones.
Then there are tons of other pruning techniques that you can do to reduce the search tree. Most of these will not yield the same result since you "manually" choose to cut off certain positions that you "think" is going to be bad. This could be things like the assumption that there is always better to do something than nothing (null move pruning).
Other easy things you can do to speed up algorithm is to look at move ordering. To make Minimax most efficient you always want to look at the best move first in each position. That way you will get more cutoffs and not search as many moves. Everything you need to know about chess programming you can find at https://www.chessprogramming.org/.
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
I'm writing a simple program and want to know if an approximate position is clicked. I've got a hashmap with the position as key value and want to display a currently invisible object if the user clicks close enough to the position of the object - not just right at it. The position class just holds an x and a y value.
HashMap<Position, Place> places = new HashMap<>(); //Assume this is populated
#Override
class WhatIsHere extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
Place place = places.get(new Position(me.getX(), me.getY()));
if (place != null) {
place.setVisible(true);
} else {
System.out.println("Nothing there");
}
}
}
This bit of code finds the place if you click right on it though I don't know how to look for, say, me.getX()+-10 and find objects in that range.
Do I need to set four ints holding x-10 and x+10 etc. and just loop through all the positions inbetween? It seems awfully dumb to do it that way.
I dislike exercises that require use of a particular collection, regardless of whether it is the best choice. One of the most important things to learn about the collections, and more generally about data structures, is picking which to use for a given job.
However, I understand you have to use HashMap. Here is one way to do it.
Divide the space up into small squares. Identify each square by e.g. the Point at the minimum x and minimum y. Create a HashMap that maps the square that are near at least one of your objects to the list of nearby objects.
To look up a point, calculate the Point identifying the square containing it. Look up that Point in the map. If it is not present, your point is not near any object. If it is present, check your point against each object in the list according to your nearness rules.
For some configurations of your objects, you may be able to ensure that each square is near at most one object. If so, you can replace the list with the object.
You might want to use TreeMap and you would be able to get a sub map which seems to be what you are looking for.
1.What data structure to use for electric circuit representation
for Kirchoff Rules computation purposes
how to differentiate between different types of electric components
how to 'recognize' wire inter-connections between them
2.how to implement Kirchoff Rules
how to obtain current and voltage loops
how to store and evaluate Kirchoff equations
[original question text]
Specifically, how would the program recognize something is in series and parallel and how will it differentiate between a battery, resistor, capacitor, inductors, etc..
Java's an object-oriented language. Start thinking about how you'd model your system as objects.
You have a few object candidates already:
Battery
Resistor
Capacitor
Inductor
These would have input and output nodes. The output from one is the input to the next.
What about transistors? You'll have more than one input. What then? Those are non-linear. How do you model those?
You'll build in the proper behavior for each one and wire them together.
You'll have some kind of transient forcing function here. Input current or voltage waveforms. Output is current and voltage at each node versus time.
This is the electrical engineer's equivalent of finite element analysis.
These are really transient ODE, right? How do you plan to solve them? Numerical integration?
agree with duffymo's answer just some things to add (I am C++ friendly so I stick to it)
first some data to represent components
struct pin
{
char name[]; // name id for pin ("C","B","E"...
int part_ix,pin_ix; // connected to patrs[part_ix].pins[pin_ix]
double i,u; // actual: current,voltage
int direction; // in,out,bidirectional
};
struct part
{
char name[]; // name id for part ("resistor","diode",...
pin pins[n]; // n pins of the part (resistor has 2 , transistor has 3, ...)
// here add all values you need for simulation like:
double R,H21E,...
// or even better do a matrix for it so when you multiply it by input currents and voltages
// of every pin you get the correct currents and voltages
double m[n][n+n];
};
also you can add list of pins connections instead of part_ix,pin_ix to save some processing time.
circuit
part parts[];
simple dynamic list of components the interconnections are inside it
loops
you have to extract closed circuit loop from interconnections for current equations and get nodes that connect current loops for voltage equations. This would lead you to system of equations. Nodes have more that 2 connections and closed current loops are just sequence of connections leads back to itself. Look here:
https://stackoverflow.com/a/21884021/2521214
it is one of my answers where part of the code finds closed loops
evaluation
can use gauss elimination for that. Problematic are non linear components like diodes, transistors ... so may be you will need to add more matrices (approximate to polynomial with bigger degree) then you will need to multiply by all currents and voltages powered by (0,1,2,3,...). I think ^3 will be enough for most components and do not forget that some non linear component also need to remember their states (or last current,voltage,... ...).
Also sometimes is better to use symbolic expressions instead of matrix approach but for that you will need expression evaluation engine. I use this approach a lot for self resizing geometry in CAD/CAM meshes.
I am trying to come up with a Java hand history class for Texas Hold'em and wanted to bounce an idea off here.
Requirements are that every action is stored and there is an efficient way to traverse each HandHistory object (which would represent a single played hand) to match common 'lines' like the standard continuation bet (i.e. the preflop raiser who was in late position preflop and probably is in position postflop is checked to and then makes a 75%ish pot bet).
Ignore for the moment that the definitions for each of the lines is fuzzy at best. As a first stab, I was thinking of organizing it like so:
public class HandHistory {
private Integer handnumber;
//in case we saw things at showdown, put them here
private HashMap<Player,String> playerHands;
private String flopCards;
private String turnCard;
private String riverCard;
private HashMap<BetRound,LinkedHashMap<Integer,ArrayList<PlayerAction>>> actions;
}
So, for each betround we store a linked hashmap whose keys are integers that are the offsets from first position to act for that betround, so preflop UTG is 0.
We generate the actions in position order already, so use a linked hashmap so we can iterate nicely later and skip over positions that are sitting out,etc.
Each arraylist will contain the actions that that position had in that betround. Most of the time this array will have one element, but in cases like, limps and then calls, it will have two.
Can anyone see a better data structure to use for this?
small change, since holdem has a fixed number of betting rounds, maybe
private HashMap<BetRound,LinkedHashMap<Integer,ArrayList<PlayerAction>>> actions;
could just be:
private LinkedHashMap<Integer,ArrayList<PlayerAction>>[] actions= new ... ;
also, here's a couple of books that may be of interest:
http://www.amazon.com/Poker-strategy-Winning-game-theory/dp/0399506691
http://www.amazon.com/Mathematics-Poker-Bill-Chen/dp/1886070253
class Card {
// ??? probably just an int (0 to 51), but certainly not a String.
// Instead of using class Card below, directly using an int woulb be OK.
}
class Hand {
Set<Card> hand; // size 2
}
class Draw { // not sure of the exact poker name for the 5 cards
Set<Card> flop; // size 3
Card turn;
Card river;
}
class Bet {
Player player;
// or maybe "Double" instead; then amount == null means player dropping out.
// or use 0.0 to mean dropped out.
double amount;
}
class BettingRound {
// Includes initial "entry" and all subsequent calls.
// Should include players dropping out also.
List<Bet> bets;
}
class Game {
Draw draw;
Map<Player, Hand> hands;
// rounds 0 and 1 are special since turn and river are not shown
List<BettingRound> rounds;
}
You should also know how much money each player has, I guess. You could keep track of that with a third field (total cash before the bet) in class Bet.
After thinking about it for a bit more, I think I have answered my own question. I've decided not to try to both store every action in a tabular way and try to get quick lookup of frequency counts for betting lines in the same data structure.
Instead, I am going to use my class above as the database-like storage to disk and use a DAG for the betting lines where the edges are tuples of {action, position, players ahead} and the vertices are frequency counts. I think a DAG is correct over a trie here since I do want multiple edges coming into a vertex since lines with common suffix are considered close.