Java datatype for sudoku grid - java

I am currently trying to plan/write a sudoku solver in Java.
The aim is for me to learn as much as I can about the language (as a beginner).
The solver will not be a "brute-force" solver, but will instead be a system of functions that implement logical algorithms, capable of being completed by a human.
But which data type do I use?
ArrayList of ArrayLists
2D array
Something Else
I know in a lot of cases it comes down to preference and features, but, because I am looking to implement a number of "solve" functions, I need a 2d data-type that I can iterate over quickly and efficiently and avoid repetitive code (such as nested for loops).
Which data type provides the best 2D iteration?

2-D array is probably your best option since sudoku grids are fixed:
byte[][] grid = new byte[9][9];
It will definitely give you the best space and computation performance (even though you will observe no difference on a small 9x9 grid!).
Now if you are more comfortable using an other data structure or wants to play with a more object-oriented one, go for it and enjoy the language.

A two dimensional array is probably the best solution. An array of array lists does not make much sense because ArrayLists are designed to be of dynamic size which is not the case here.

I would suggest writing your own datatype based on a 2d-array. You can implement a method like "iterate" or "return all cells" to avoid repetitive nested foor-loops and still access all elements.
ArrayLists are useful if the size of your field would be unknown or need to be dynamic for whatever reason but since sudoku always has a 9x9 grid you wont need that and if you just started learning java you should stick to the basics (in this case wrapping a class around a 2d-array which is a good start imho).
Just one more point why you should use a 2d-array:
It is very easy to return/check/solve a column or row using a 2d-array since rows and columns share one common index on the sudoku grid (and so they do in your 2d-array).
This might be a point for you to start from. Nothing more than a small inspiration.
class Sudokugrid{
private int[][] field;
Sudokugrid(){
this.field = new int[9][9];
}
public int get_cell(int x, int y){
return this.field[x][y];
}
public void set_cell(int x, int y; int value){
this.field[x][y] = value;
}
//(...)
}

Related

What should I use instead of an array of generic lists?

I want to create a game which has for example 20x30 fields,my first thought was that each field would be a list(becouse sometimes some field contains more than one object),but after reading a few questions about the array of generic lists,I've realised it's not a good solution.
The game is going to be a very simple version of Raft,playing it in console with commands like "left" so the character moves one field left.
So can you recommend a good container or something to design the fields?
An illustration of the game:
http://imgur.com/a/8YpeA
If you are implementing a fixed-sized rectangular "playing surface", then I would recommend a Cell[][] where the Cell type is a custom class that represents the state of a cell on the surface.
There is no need to use generics here ... unless you are trying to implement an abstraction that can be used in many games.
Also, there is no need for list-like functionality. You don't remove or add cells to the board. You move pieces / players / whatever from one cell to another.
(If your board is not based on discreet cells, the you will need to use some other approach. But any 2D playing surface with a bounded number of discrete cells can be mapped to a Java array, one way or another.)
So can you recommend a good container or something to design the fields?
Recommendations for libraries and tools are OFF-TOPIC.
There are two ways you can create generic arrays:
Create private static inner class of a type:
transient Node<K, V>[] table;
public MyHashMap(int limit) {
this.limit = limit;
table = (Node<K, V>[]) new Node[limit];
}
Use Array.newInstance(class, size)
moreover using generics for custom implementations is not a good choice.

3d ArrayList vs arrayList of stack

I'm trying to recreate a board game. This board game has a 4x4 dimension which can be represented by a 2D arraylist. However, what i'm having difficulty doing is deciding what would be the best method of implementing a 4x4 board game where each row and column can hold 4 items(In the fashion of a stack where the top item is the greatest int). Would a 2D arraylist of stacks be the most efficient in this case, or would a 3D arraylist be the way to go. Similarly, how would I initialize a 3D arraylist of integers? Thanks!
Efficiency is going to be fine either way, do whatever is easiest for the kinds of things you need to do with the squares. Will you be referencing things by their X,Y coordinates? Then you might want to just use a 2-d array of tiles, so you can reference things as
tile = board[x][y]
This assumes that the origin is at the top-left of the board. It's also very efficient, if that were actually an issue.
You asked "...what would be the best method of implementing a 4x4 board game...". But it seems like you should not care about the implementation right now. It sounds like you should care about the interface. Define an interface that precisely mirrors what you want to would like to represent:
interface Board {
int getNumRows();
int getNumCols();
int getStackHeight(int r, int c);
int getStackValue(int r, int c, int h);
}
As it was mentioned before, efficiency should hardly be an issue, and IF it becomes an issue, you'll probably be glad when you can change your implementation without affecting anything else in your game.

Storing 15,000 items in Java

I have a document with 15,000 items. Each item contains 6 variables (strings and integers). I have to copy all of these into some sort of two dimensional array, what the best way to do it?
Here are my ideas so far:
Make a GIANT 2D array or array list the same way you make any other array.
Pros: Simple Cons: Messy(would create a class just for this), huge amount of code, if I make a mistake it will be imposable to find where it is, all variables would have to be string even the ints which will make my job harder down the road
Make a new class with a super that takes in all the variables I need.
Create each item as a new instance of this class.
Add all of the instances to a 2D array or array list.
Pros: Simple, less messy, easier to find a mistake, not all the variables need to be strings which makes it much easier later when I don't have to convert string to int, a little less typing for me Cons: Slower? Will instances make my array compile slower? And will they make the over all array slow when I'm searching to items in it?
These ideas don't seem all to great :( and before I start the three week, five hour a day process of adding these items I would like to find the best way so I won't have to do it again... Suggestions on my current ideas or any new ideas?
Data example:
0: 100, west, sports, 10.89, MA, united
*not actual data
Your second options seems to be good. You can create a class containing all the items and create an array of that class.
You may use the following:
1. Read the document using buffered reader, so that memory issues will not occur.
2. Create a class containing your items.
3. Create a List of type you need and store the elements into it.
Let me know in case you face further problems.
If you already have the document with the 15000 * 6 items, in my experience you would be better served writing a program to use regex and parse it and have the output be the contents of the java array in the format you want. With such a parsing program in place, it will then also be very easy for you to change the format of the 15000 lines if you want to generate it differently.
As to the final format, I would have an ArrayList of your bean. By you text thus far, you don't necessarily need a super that takes in the variables, unless you need to have subtypes that are differentiated.
You'll probably run out of static space in a single class. So what I do is break up a big class like that into a file with a bunch of inner nested classes that each have a 64K (or less) part of the data as static final arrays, and then I merge them together in the main class in that file.
I have this in a class of many names to fix:
class FixName{
static String[][] testStrings;
static int add(String[][] aTestStrings, int lastIndex){
for(int i=0; i<aTestStrings.length; ++i) {
testStrings[++lastIndex]=aTestStrings[i];
}
return lastIndex;
}
static {
testStrings = new String[
FixName1.testStrings.length
+FixName2.testStrings.length
+FixName3.testStrings.length
+FixName4.testStrings.length
/**/ ][];
int lastIndex=-1;
lastIndex=add(FixName1.testStrings,lastIndex);
lastIndex=add(FixName2.testStrings,lastIndex);
lastIndex=add(FixName3.testStrings,lastIndex);
lastIndex=add(FixName4.testStrings,lastIndex);
/**/ }
}
class FixName1 {
static String[][] testStrings = {
{"key1","name1","other1"},
{"key2","name2","other2"},
//...
{"keyN","nameN","otherN"}
};
}
Create a wrapper (Item) if you have not already(as your question does not state it clearly).
If the size of the elements is fixed ie 1500 use array other wise use LinkedList(write your own linked list or use Collection).
If there are others operations that you need to support on this collection of items, may be further inserts, search( in particular) use balanced binary search tree.
With the understanding of the question i would say linked list is better option.
If the items have a unique property (name or id or row number or any other unique identifier) I recommend using a HashMap with a wrapper around the item. If you are going to do any kind of lookup on your data (find item with id x and do operation y) this is the fastest option and is also very clean, it just requires a wrapper and you can use a datastructure that is already implemented.
If you are not doing any lookups and need to process the items en masse in no specific order I would recommend an ArrayList, it is very optimized as it is the most commonly used collection in java. You would still need the wrapper to keep things clean and a list is far cleaner than an array at almost no extra cost.
Little point in making your own collection as your needs are not extremely specific, just use one that is already implemented and never worry about your code breaking, if it does it is oracles fault ;)

Comparing functionality between Vectors and Arrays in Java

I've been thinking about this one for a long time. What is the difference between Vectors and Arrays? I know they do similar things, if not exact.
String Array
String[] array = new String[4];
String Vector
Vector<String> vector = new Vector<String>(4);
It seems kind of redundant to me why there would be both arrays and vectors. Are there any advantages or disadvantages to using one or the other?
Vectors are resizable. Arrays are not.
The difference is that 'Vector' is an extension by programmers, whereas an array is a built-in function of the language itself.
You can edit how the Vector behaves (by editing its source code), whereas an array is defined by the compiler.
And obviously, Vectors can be potentially sized (depending on implementation). Arrays are static and cannot be resized - you have to recreate it and copy the data over.
Vector is synchronized. Arrays are not(?).
Array cannot be re-sized, while Vectors can.
Vector uses Arrays internally. The main advantage of a Vector compared to an Array is its automatical increase of capacity. An Array keeps its size once created, a Vector does not
It seems kind of redundant to me why there would be both arrays and
vectors
For one, Vectors can be resized. If you declare an array of size 10, you are left with 10 always, unless you copy the contents to another larger sized array. Methods of Vector are synchronized.
Vectors are part of the collections framework. Vector is a List. There are other lists, ArrayLists, LinkedLists etc with specific features. There are Sets and Maps. All of them hold "lists" of items, but each of them give specific advantages in specific situations.
You might want to read about java collections.
Vectors will automatically resize for you to accommodate as many entries as you want in them. An array is fixed in size, and will give you an OutOfBounds exception when you try to add more than you allocated.
When you provide the size for a vector, that's just the original size it starts with. It'll automatically grow/shrink as necessary.
1- Vectors are resize-able, arrays are not
2- Vectors are responsible for memory allocate and release, arrays are not. This makes vectors safer to use than arrays.
3- Vectors have a good performance on their implemented functions, which you may not reach by your own programming with arrays.
4- Finally I think it's wiser to use vectors, most of the times.
An array is a basic java data structure, whose size is fixed when defined.
A Vector is part of the Java Collections Framework, and contrary to your beliefs, or not even close to the same thing as an array. Among many other things, Vectors are resizable and can interact with other collections.
Java array types are not necessary. They actually create a lot of problems. Avoid them if you can.
We could do better to replace them with a standard class Array<T>. Some new post-Java languages are taking this approach.
(History alert) In the old days, Java didn't have generics, a non-generic collection class would suck to use (with lots of castings). Then array types were really poor man's generics because they carry element type info. That's why many methods return arrays, instead of List.
I think the above suggestion is not good. Check this link to get brief idea.
Difference b/w Array and Vector
Vectors help to insert and delete elements easily while arrays helps to sort and access elements with ease.
Vectors can hold different type of elements
Arrays only the type defined when forming them
You can use array list which is some what similar to vector and provided much better features

Are there any efficient 2D ArrayList classes for Java?

I know that it's possible to create a 2D ArrayList with ArrayList<ArrayList<E>>, but that is cumbersome and a real casting nightmare when it comes to adding and retrieving objects.
Are there any 2D ArrayList classes that do this sort of thing more efficiently? I am writing a true 2D ArrayList class from the ground up, and I'm wondering if there is anyone else who has done this sort of thing in an efficient manner.
no, unfortunately there isn't 2d ArrayList class. your alternative options are (in case 0/1/2 of the Diamension is constant):
MyType[][] myList = new MyType[n][m];
or
ArrayList<MyType>[] myList = new ArrayList<MyType>[n];
or
ArrayList<ArrayList<MyType>> myList = new ArrayList<ArrayList<MyType>>();
another option is to save all your data in 1d ArrayList and create a function that recieve (x,y) and return the place x in the ArrayList. this way you demonstrate outside a 2d array, but save the elements easily in 1d ArrayList
Using the "ArrayList>" type approach is fine and pretty standard for this kind of thing from what I have seen. You can easily write a 2D array list class that provides convenience methods for adding / removing items, etc, and it will be far from "cumbersome" or "a casting nightmare" to use this. Have a look at this implementation as an example. It is not quite perfect but it illustrates how easy it is to use this kind of approach.
Have a look at FastTable in javolution and Table implementations in guava
Google Collections has a Table collection. It's laid out as Rows/Cols and accesible directly, bycol, and by rows. Different implementations of Table have different efficiencies based on access type
I built a 3D "grid" data structure, if it is any help.
https://github.com/mikera/mikera/blob/master/src/main/java/mikera/engine/TreeGrid.java
The key trick is sub-dividing space into "blocks" so that sparse data can be efficiently stored.
You can use it as a 2D collection if you like by ignoring the z dimension (keeping it at 0), though that is probably a bit of overkill. Still, an option if you want this kind of structure. Alternatively, you could simplify it down to 2D.

Categories