I am having a hard time of how to approach the problem of creating a 2D matrix in Java using a Singly Linked List as the underlying data structure. The goal is to have the user input the number of rows and columns and we create this matrix and the user has the option to display, insert, fill, or compute the row and column sums. Each node in the matrix should have a right pointer and a down pointer (when applicable). If you could help me out, I'd really appreciate it.
EX) Display function of a 2x3 matrix should look something like this
00->01->02
10->11->12
00 should point down to 10, 01 to 11 and 02 to 12
hopefully that visual representation helps
Thanks!
If node in your list have references to more than two elements (previous and next), it is not a list, it's more complicated data structure.
For your problem I recommend you to create function, which allows you to transfer Cartesian coordinates into linear coordinates. Then add elements into list by linear coordinates (I think, ArrayList is more suitable for you). Technically, your matrix will be stored in a single list.
Implementation of a simple singly linked list should be easily available online. A few modifications are needed in the linked list (Assuming singly here means unidirectional, right and down, but not left and up):
1. You'll need to two variables, to keep track of rows and columns.
2. You'll need a size variable, increment it after each element is added.
3. Modify the add method, so that whenever the size is > column (when a column fills up), point your down pointer of above node to the adding node, node[size-column].down = thisNode. (assuming you insert them column by column)
4. Display method should be pretty easy, iterate through column, if index > column, move to a new line.
5. Compute Row/Column sums by iterating through .next/ .down, (while hasnext, sum += next)
You can find the solution code for this problem here:
https://github.com/manoj7shekhawat/dataStructures/blob/master/Examples/Chap05/matrix/matrixApp.java
Related
Overview of the problem: You are a truffle collector, and are given a grid of numbers representing plots of land with truffles on them. Each plot has a certain number of truffles on it. You must find the optimal path from the top of the grid to the bottom (the one that collects the most truffles). Importantly, you can start from any cell in the top row. When you are at a cell, you can move diagonally down to the left, directly down, or diagonally down to the right. A truffle field might look like this:
The truffle fields also do not have to be square. They can have any dimensions.
So, I have created an iterative algorithm for this problem. Essentially, what I have done is iterate through each cell in the top row, finding the greedy path emanating from each and choosing the one with the largest truffle yield. To elaborate, the greedy path is one in which at every step, the largest value that can be reached in the next row from the current cell is chosen.
This algorithm yields the correct result for some truffle fields, like the one above, but it fails on fields like this:
This is because when the algorithm hits the 100 in the third column, it will go directly down to the 3 because it is the largest immediate value it can move to, but it does not consider that moving to the 2 to the left of it will enable it to reach another 100. The optimal path through this field obviously involves both cells with a value of 100, but the greedy algorithm I have now will never yield this path.
So, I have a hunch that the correct algorithm for this problem involves recursion, likely recursive backtracking in particular, but I am not sure how to approach creating a recursive algorithm to solve it. I have always struggled with recursion and find it difficult to come up with algorithms using it. I would really appreciate any ideas you all could provide.
Here is the code. My algorithm is being executed in the findPath method: https://github.com/jhould007/Programming-Assignment-3/blob/master/Truffle.java.
You could use recursion, but there's a simple iterative fix to your approach as well.
Instead of the top row, start with the bottom one. Create a 1D array values and initialise it with the values of the bottom row.
Start iterating curr_row from row max_row-1 to 0. For each iteration, create a temporary array temp and initialise it with 0's.
For a row curr_row in the iteration, value[i] represents the max value that you can get if you start from row curr_row+1 (basically the next row) and column i.
To update temp in each iteration, we just need to pick the best path from the next row, which can be fetched from values array.
for column in range [0, max_column]:
temp[column] = truffle_value[column] + max(value[column], value[column+1], value[column-1])
// since temp holds the values for the next iteration in our loop
value = temp
In the end, the answer will simply be max(values).
I have coded a standard Hash Table class in java. It has a large array of buckets, and to insert, retrieve or delete elements, I simply calculate the hash of the element and look at the appropriate index in the array to get the right bucket.
However, I would like to implement some sort of iterator. Is there an other way than looping through all the indices in the array and ignoring those that are empty? Because my hash table might contain hundreds of empty entries, and only a few elements that have been hashed and inserted. Is there a O(n) way to iterate instead of O(size of table) when n<<size of table?
To implement findMin, I could simply save the smallest element each time I insert a new one, but I want to use the iterator approach.
Thanks!
You can maintain a linked list of the map entries, like LinkedHashMap does in the standard library.
Or you can make your hash table ensure that the capacity is always at most kn, for some suitable value of k. This will ensure iteration is linear in n.
You could store a sorted list of the non-empty buckets, and insert a bucket's id into the list (if it's not already there) when you insert something in the hash table.
But maybe it's not too expensive to search through a few hundred empty buckets, if it's not buried too deep inside a loop. A little inefficiency might be better than a more complex design.
If order is important to you you should consider using a Binary Search Tree (a left leaning red black tree for example) or a Skip List to implement your Dictionary. They are better for the job in these cases.
I am implementing a Flame clustering algorithm as a way of learning a bit more about graphs and graph traversal, and one of the first steps is constructing a K-nearest-neighbors graph, and I'm wondering what the fastest way would be of running through a list of nodes and connecting each one only to say, it's nearest five neighbors. My thought was that I would start at a node, iterate through the list of other nodes and keep the ones that are closest within an array, making sure that everything past the top n are discarded. Now, I could do this by just sorting a list and keeping the top n entries, but I would much rather keep less fewer things in memory and so I was wondering if there was a way to just have the final array and update that array as I iterate through, or if there is a more efficient way of generating a k nearest neighbors graph.
Also, please note, this is NOT a duplicate of K-Nearest Neighbour Implementation in Java. KNNG is distinct from KNN.
Place the first n nodes, sorted in a List. Then iterate through the rest of nodes and if it fits in the current list (i.e. is a top n node), place it in the corresponding position in the list and discard the last top n node. If it doesn't fit in the top n list, discard it.
for each neighborNode
for(int i = 0; i < topNList.size(); i++){
if((dist = distanceMetric(neighborNode,currentNode)) > topNList.get(i).distance){
topNList.remove(topNList.size()-1)
neighborNode.setDistance(dist);
topNList.add(i, neighborNode);
}
I think the most efficient way would be using a bound priority queue, like
https://github.com/tdebatty/java-graphs#bounded-priority-queue
I am attempting to recreate a board game in Java which involves me storing a set of valid places pieces can be placed (for the AI). I thought that perhaps instead of storing as a list of Points, it would be run-time faster if I had an array/list/dictionary of the X coordinates in which there was an array/list of the y coordinates, so once you found the x coordinate you would only have to check its Ys not all the remaining points'.
The trouble I have is that i must change the valid points often. I came up with some possible solutions but have difficulty picking/implementing them:
HashMap < Integer, ArrayList > with X as an integer key and the Ys as an ArrayList.
Problem: I would have to create a new ArrayList every time I add an X.
Also I am unsure about runtime performance of HashMap.
int[X][Y] array initialized to the board size with each point set to its relative location (point 2,3 sets[2][3]) unset point being an invalid integer.
Problem: I would have to iterate through all the points and check every point.
List of Points This would simply be a Linked/Array List of Points.
Problem: Lists are slower than arrays.
How would using a Linked list of Points compare to checking the whole array like above?
Perhaps I should use a 2d linked list? What would be the fastest runtime way to do this?
You're worrying about the wrong things. Accessing collection/map/array items is extremely fast. The graphical part will be way more performance-sensitive. Just use whatever data structure is most natural. It's unlikely that you're going to be storing enough items to really matter anyway. Build it first, then figure out where your performance problems really are.
if you use an ArrayList of Points you have nearly the same performance as with an array (in Java)
and I think this is the fastest solution, because as you already mentioned you have to iterate through the complete int-array and a HashMap and the relying ArrayLists have to be changed depending on changing/adding coordinates
I've a requirement in which i need to read values and their coordinates and place them into a matrix for displaying it later.
so lets say i've the following:
<name='abc', coordinates='1,3'>
<name='xyz', coordinates='2,1'>
...............................
Now i need to put these in a 'matrix collection' based on their coordinate values and get display as table (with cells in the table occupying respective coordinates slot).
Is there a collection/way to do this in java? Mind you, i don't need a swing or any graphic library techniques. I just need a datastructure to do this.
Thank you
BC
You could use the Table class from Guava.
If you know in advance the boundaries of your grid, you can use a 2 dimensional array:
int[][] matrix = new int [n][n];
If you do not, one way to emulate this is with a List of Lists:
ArrayList <ArrayList<Integer> > matrix = new ArrayList <ArrayList <Integer> >();
Nothing's going to do this automatically for you AFAIK. You'll need to start with extracting the data. Depending on how it's offered to you, you could use regular expressions or some specialized parser (if it's XML, there's a broad selection of tools in Java).
Next up, you're going to need to split that coordinate String. Check method split of class String.
Finally, those coordinates are gonna need to become integers. Check method parseInt of class Integer.
With these now numerical coordinates, you can insert the value into an array. If you know the maximum coordinates beforehand, you can immediately create the array. If the coordinates can be any value without bounds, you'll need some dynamic structure or regularly make a larger array and copy over the old contents.