Java Need help implementing an algorithm - java

This algorithm is so advanced for my basic programming skills that I just don't see how I could implement it. I'm posting this in a new question because I can't keep bothering the guy who gave me the algorithm alone about this in the comment section in the previous question.
MaxSet(node) = 1 if "node" is a leaf
MaxSet(node) = Max(1 + Sum{ i=0..3: MaxSet(node.Grandchildren[i]) },
Sum{ i=0..1: MaxSet(node.Children[i]) })
Thanks too mehrdad for the algorithm.
The problem here for me is to implement the part of the two sum lines, how can I do that? And I need to mark every node that this algorithm chooses. It's just a "marked" variable in the node class set to true. I don't understand were it makes a decision too choose a node?
EDIT to include my code so far:
public int maxSet(Posisjon<E> bt){
if (isExternal(bt)){
return 1;
}
return Math.max(1 + helper1(bt), helper2(bt));
}
private int helper1(Posisjon<E> node){
int tmp = 0;
if (hasLeft(node)){
if(hasLeft((Position<E>)node.leftChild())){
tmp += maxSet(node.leftChild().leftChild());
}
if(hasRight((Position<E>)node.leftChild())){
tmp += maxSet(node.leftChild().rightChild());
}
}
if(hasRight(node)){
if(hasLeft((Position<E>)node.rightChild())){
tmp += maxSet(node.leftChild().leftChild());
}
if(hasRight((Position<E>)node.rightChild())){
tmp += maxSet(node.leftChild().rightChild());
}
}
return tmp;
}
private int helper2(Posisjon<E> node){
int tmp = 0;
if(hasLeft(node)){
tmp +=maxSet(node.leftChild());
}
if(hasRight(node)){
tmp +=maxSet(node.rightChild());
}
return tmp;
}
This seems to be working, what is left now. Is to actually mark the nodes as chosen? Were would I do that?
Updated with code:
public ArrayList<Posisjon<E>> getSelectionSet(Posisjon<E> bt, ArrayList<Posisjon<E>> s){
if(bt.marked){
s.add(bt);
}
if(hasLeft(bt)){
if(hasLeft(bt.leftChild())){
getSelectionSet(bt.leftChild().leftChild(),s);
}
if(hasRight(bt.leftChild())){
getSelectionSet(bt.leftChild().rightChild(),s);
}
}
if(hasRight(bt)){
if(hasLeft(bt.rightChild())){
getSelectionSet(bt.rightChild().leftChild(),s);
}
if(hasRight(bt.rightChild())){
getSelectionSet(bt.rightChild().rightChild(),s);
}
}
return s;
}
public int maxSet(Posisjon<E> bt){
if (bt.visited){
return bt.computedMax;
}
bt.visited = true;
int maxIfCurrentNodeIsSelected = 1 + helper1(bt);
int maxIfCurrentNodeIsNotSelected = helper2(bt);
if (maxIfCurrentNodeIsSelected > maxIfCurrentNodeIsNotSelected){
bt.marked = true;
bt.computedMax = maxIfCurrentNodeIsSelected;
}else{
bt.marked = false;
bt.computedMax = maxIfCurrentNodeIsNotSelected;
}
return maxSet(bt);
}
After submission, I will post the entire code for this!

You currently have does not memoize the return value of the function each time. Every time you call maxSet, you should check if you have already computed the result or not. If you have, just return it. If you haven't compute it and store it somewhere. Otherwise, your algorithm will be inefficient. (This approach is called "Dynamic Programming." Learn about it.)
// pseudocode:
public int maxSet(Posisjon<E> bt){
if (visited[bt])
return computedMax[bt];
visited[bt] = true;
// You don't need to manually check for being a leaf
// For leaves 'maxIfCurrentNodeIsSelected' is always larger.
int maxIfCurrentNodeIsSelected = 1 + helper1(bt);
int maxIfCurrentNodeIsNotSelected = helper2(bt);
if (maxIfCurrentNodeIsSelected > maxIfCurrentNodeIsNotSelected) {
shouldSelect[bt] = true;
computedMax[bt] = maxIfCurrentNodeIsSelected;
} else {
shouldSelect[bt] = false;
computedMax[bt] = maxIfCurrentNodeIsNotSelected;
}
}
public Set getSelectionSet(Posisjon<E> bt, Set s) {
if (shouldSelect[bt]) {
s.Add(bt);
// You should check for nulls, of course
getSelectionSet(bt.leftChild.leftChild, s);
getSelectionSet(bt.leftChild.rightChild, s);
getSelectionSet(bt.rightChild.leftChild, s);
getSelectionSet(bt.rightChild.rightChild, s);
} else {
getSelectionSet(bt.leftChild, s);
getSelectionSet(bt.rightChild, s);
}
return s;
}
call getSelectionSet with the root node and an empty Set as arguments after you called maxSet.

Related

Print Tree with 4 nodes (simple forest) for checking a benchmark

I implemented an experimental OOP language and now benchmark garbage collection using a Storage benchmark. Now I want to check/print the following benchmark for small depths (n=2, 3, 4,..).
The tree (forest with 4 subnode) is generated by the buildTreeDepth method. The code is as follows:
import java.util.Arrays;
public final class StorageSimple {
private int count;
private int seed = 74755;
public int randomNext() {
seed = ((seed * 1309) + 13849) & 65535;
return seed;
}
private Object buildTreeDepth(final int depth) {
count++;
if (depth == 1) {
return new Object[randomNext() % 10 + 1];
} else {
Object[] arr = new Object[4];
Arrays.setAll(arr, v -> buildTreeDepth(depth - 1));
return arr;
}
}
public Object benchmark() {
count = 0;
buildTreeDepth(7);
return count;
}
public boolean verifyResult(final Object result) {
return 5461 == (int) result;
}
public static void main(String[] args) {
StorageSimple store = new StorageSimple();
System.out.println("Result: " + store.verifyResult(store.benchmark()));
}
}
Is there a somewhat simple/straight forward way to print the tree generated by buildTreeDepth? Just the short trees of n=3, 4, 5.
As other has already suggested, you may choose some lib to do so. But if you just want a simple algo to test in command line, you may do the following, which I always use when printing tree in command line (write by handle, may have some bug. Believe you can get what this BFS algo works):
queue.add(root);
queue.add(empty);
int count = 1;
while (queue.size() != 1) {
Node poll = queue.poll();
if (poll == empty) {
count = 1;
queue.add(empty);
}
for (Node n : poll.getChildNodes()) {
n.setNodeName(poll.getNodeName(), count++);
queue.add(n);
}
System.out.println(poll.getNodeName());
}
Sample output:
1
1-1 1-2 1-3 1-4
1-1-1 1-1-2 1-1-3 1-2-1 1-2-2 1-3-1 1-3-2 1-4-1
...
And in your case you use array, which seems even easier to print.
Instead of using object arrays, use a List implementation like ArrayList. For an improved better result subclass ArrayList to also hold a 'level' value and add indentation to the toString() method.

nearest neighbor algorithm copy element (city) to output array java

So I have a program written so far that reads in a csv file of cities and distances in the following format:
Alaska Mileage Chart,Anchorage,Anderson,Cantwell,
Anchorage,0,284,210,
Anderson,284,0,74,
Cantwell,210,74,0,
So the algorithm works and outputs the cities in the order they should be visited following the shortest path using the nearest neighbor algorithm always starting with Anchorage as the city of origin or starting city.
Using this data, the example output for the algorithm is: 1,3,2. I have ran this with a 27 element chart and had good results as well. I am using this small one for writing and debugging purposes.
Ideally the output I am looking for is the Name of the City and a cumulative milage.
Right now I am having working on trying to get the cities into an array that I can print out. Help with both parts would be appreciated or help keeping in mind that is the end goal is appreciated as well.
My thought was that ultimately I may want to create an array of {string, int}
so my output would look something like this..
Anchorage 0
Cantwell 210
Anderson 284
I am able to set the first element of the array to 1, but can not get the 2nd and 3rd element of the new output array to correct
This is the code I am having a problem with:
public class TSPNearestNeighbor {
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbor()
{
stack = new Stack<>();
}
public void tsp(int adjacencyMatrix[][])
{
numberOfNodes = adjacencyMatrix[1].length;
// System.out.print(numberOfNodes);
// System.out.print(Arrays.deepToString(adjacencyMatrix));
int[] visited = new int[numberOfNodes];
// System.out.print(Arrays.toString(visited));
visited[1] = 1;
// System.out.print(Arrays.toString(visited));
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\n");
//System.arraycopy(arr_cities, 0, arr_final, 0, 1); // Copies Anchorage to Pos 1 always
//System.out.print(Arrays.deepToString(arr_final)+ "\n");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes-1)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\n");
minFlag = false;
continue;
}
stack.pop();
}
}
Given the existing structure you are using, you can output the cities in the path using:
public void printCities(Stack<Integer> path, int[][] distances, List<String> names) {
int cumulativeDistance = 0;
int previous = -1;
for (int city: path) {
if (previous != -1)
cumulativeDistance += distances[previous][city];
System.out.println(names.get(city) + " " + cumulativeDistance);
previous = city;
}
}
I'd like to answer your question slightly indirectly. You are making life hard for yourself by using arrays of objects. They make the code difficult to read and are hard to access. Things would become easier if you create a City class with appropriate methods to help you with the output.
For example:
class City {
private final String name;
private final Map<City,Integer> connections = new HashMap<>();
public static addConnection(City from, City to, int distance) {
from.connections.put(to, distance);
to.connections.put(from, distance);
}
public int getDistanceTo(City other) {
if (connections.containsKey(other))
return connections.get(other);
else
throw new IllegalArgumentException("Non connection error");
}
}
I've left out constructor, getters, setters for clarity.
Now outputting your path becomes quite a bit simpler:
public void outputPath(List<City> cities) {
int cumulativeDistance = 0;
City previous = null;
for (City current: cities) {
if (previous != null)
cumulativeDistance += previous.getDistanceTo(current);
System.out.println(current.getName + " " + cumulativeDistance);
previous = current;
}
}

I don't know how to implement a recursive syntax analyzer

I have the following context free grammar:
E = (E)
E = i | ε
Given an input String, I have to determine whether this String is accepted by this grammar or not, with a recursive syntax analyzer. For example, if I have the input:
((i))<- this is valid
(((i))))<- this is invalid
()<- this is valid
and I have the code that is supposed to do all of these
public static boolean E() {
int pOpen;
pOpen = 0;
if (lexico.equals("(")) {
pOpen++;
E();
} else if (lexico.equals("i")) {
if (pOpen == 0)
return true; //this is valid
else
verifyParenthesis();
}
}
public static boolean verifyParenthesis() {
int pClose = 0;
while ((lexico = nextSymbol()).equals(")"))
pClose++;
}
But I am not sure how to verify that the number of open parentheses ( is the same as the number of close parentheses ).
Do I have to use a while on the verifyParenthesis method?
Recursive as you with. Enjoy.
public static boolean expressionIsCorrect(String expr) {
if(!expr.contains("(") && !expr.contains(")")) {
return true;
}
int indexOfLeft = -1;
int indexOfRight = -1;
indexOfLeft = expr.indexOf("(");
indexOfRight = expr.lastIndexOf(")");
if (indexOfLeft>=indexOfRight) {
return false;
}
return expressionIsCorrect(expr.substring(indexOfLeft+1, indexOfRight));
}
Don't hesitate to ask question if you don't understand what's going on, but try to get it yourself first.

Binary Search Tree: Display contents of the tree in a tree like fashion (recursive)

I been at it for a while I can't figure it out. I am suppose to do a reverse order traversal (right-root-left) and pass the level of the root to the function ShowTree.
What exactly is the level of the root? Is it the height? If yes, this is the code for it:
public int getHeight()
{
return getHeight(_root);
}
private int getHeight (BSTnode top)
{
if (top == null)
return 0;
else
{
int lftHeight = getHeight(top._left);
int rhtHeight = getHeight(top._right);
if (lftHeight > rhtHeight)
return 1 + lftHeight;
else
return 1 + rhtHeight;
}
}
So I assign the value of getHeight to level and pass it to ShowTree. I am suppose to use the level of each node to compute how many spaces to insert in front of the data of each node.
public String ShowTree (int level)
{
return ShowTree(_root,level);
}
private String ShowTree(BSTnode myroot, int level)
{
String result = "";
if (myroot == null)
return "";
else
{
result += ShowTree (myroot._right, level + 1);
result += myroot._data.toStringKey();
result += ShowTree (myroot._left, level + 1);
return result;
}
}
However this diplays the tree like this:
c
b
a
When it should print like this:
c
b
a
In your ShowTree(BSTnode, int) method...
String result = ""; // no extra whitespace
Dont you mean...
String result = " "; //extra whitespace

Making change recursively: How do I modify my algorithm to print all combinations?

I have an algorithm that recursively makes change in the following manner:
public static int makeChange(int amount, int currentCoin) {
//if amount = zero, we are at the bottom of a successful recursion
if (amount == 0){
//return 1 to add this successful solution
return 1;
//check to see if we went too far
}else if(amount < 0){
//don't count this try if we went too far
return 0;
//if we have exhausted our list of coin values
}else if(currentCoin < 0){
return 0;
}else{
int firstWay = makeChange(amount, currentCoin-1);
int secondWay = makeChange(amount - availableCoins[currentCoin], currentCoin);
return firstWay + secondWay;
}
}
However, I'd like to add the capability to store or print each combination as they successfully return. I'm having a bit of a hard time wrapping my head around how to do this. The original algorithm was pretty easy, but now I am frustrated. Any suggestions?
CB
Without getting into the specifics of your code, one pattern is to carry a mutable container for your results in the arguments
public static int makeChange(int amount, int currentCoin, List<Integer>results) {
// ....
if (valid_result) {
results.add(result);
makeChange(...);
}
// ....
}
And call the function like this
List<Integer> results = new LinkedList<Integer>();
makeChange(amount, currentCoin, results);
// after makeChange has executed your results are saved in the variable "results"
I don't understand logic or purpose of above code but this is how you can have each combination stored and then printed.
public class MakeChange {
private static int[] availableCoins = {
1, 2, 5, 10, 20, 25, 50, 100 };
public static void main(String[] args) {
Collection<CombinationResult> results = makeChange(5, 7);
for (CombinationResult r : results) {
System.out.println(
"firstWay=" + r.getFirstWay() + " : secondWay="
+ r.getSecondWay() + " --- Sum=" + r.getSum());
}
}
public static class CombinationResult {
int firstWay;
int secondWay;
CombinationResult(int firstWay, int secondWay) {
this.firstWay = firstWay;
this.secondWay = secondWay;
}
public int getFirstWay() {
return this.firstWay;
}
public int getSecondWay() {
return this.secondWay;
}
public int getSum() {
return this.firstWay + this.secondWay;
}
public boolean equals(Object o) {
boolean flag = false;
if (o instanceof CombinationResult) {
CombinationResult r = (CombinationResult) o;
flag = this.firstWay == r.firstWay
&& this.secondWay == r.secondWay;
}
return flag;
}
public int hashCode() {
return this.firstWay + this.secondWay;
}
}
public static Collection<CombinationResult> makeChange(
int amount, int currentCoin) {
Collection<CombinationResult> results =
new ArrayList<CombinationResult>();
makeChange(amount, currentCoin, results);
return results;
}
public static int makeChange(int amount, int currentCoin,
Collection<CombinationResult> results) {
// if amount = zero, we are at the bottom of a successful recursion
if (amount == 0) {
// return 1 to add this successful solution
return 1;
// check to see if we went too far
} else if (amount < 0) {
// don't count this try if we went too far
return 0;
// if we have exhausted our list of coin values
} else if (currentCoin < 0) {
return 0;
} else {
int firstWay = makeChange(
amount, currentCoin - 1, results);
int secondWay = makeChange(
amount - availableCoins[currentCoin],
currentCoin, results);
CombinationResult resultEntry = new CombinationResult(
firstWay, secondWay);
results.add(resultEntry);
return firstWay + secondWay;
}
}
}
I used the following:
/**
* This is a recursive method that calculates and displays the combinations of the coins included in
* coinAmounts that sum to amountToBeChanged.
*
* #param coinsUsed is a list of each coin used so far in the total. If this branch is successful, we will add another coin on it.
* #param largestCoinUsed is used in the recursion to indicate at which coin we should start trying to add additional ones.
* #param amountSoFar is used in the recursion to indicate what sum we are currently at.
* #param amountToChange is the original amount that we are making change for.
* #return the number of successful attempts that this branch has calculated.
*/private static int change(List<Integer> coinsUsed, Integer currentCoin, Integer amountSoFar, Integer amountToChange)
{
//if last added coin took us to the correct sum, we have a winner!
if (amountSoFar == amountToChange)
{
//output
System.out.print("Change for "+amountToChange+" = ");
//run through the list of coins that we have and display each.
for(Integer count: coinsUsed){
System.out.print(count + " ");
}
System.out.println();
//pass this back to be tallied
return 1;
}
/*
* Check to see if we overshot the amountToBeChanged
*/
if (amountSoFar > amountToChange)
{
//this branch was unsuccessful
return 0;
}
//this holds the sum of the branches that we send below it
int successes=0;
// Pass through each coin to be used
for (Integer coin:coinAmounts)
{
//we only want to work on currentCoin and the coins after it
if (coin >= currentCoin)
{
//copy the list so we can branch from it
List<Integer> copyOfCoinsUsed = new ArrayList<Integer>(coinsUsed);
//add on one of our current coins
copyOfCoinsUsed.add(coin);
//branch and then collect successful attempts
successes += change(copyOfCoinsUsed, coin, amountSoFar + coin, amountToChange);
}
}
//pass back the current
return successes;
}

Categories

Resources