public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
public int catalan(int a) {
if (Method was never executed with that input) {
howManyVariaties++;
int catalanNumber = 0;
for (int i= 0; i < n; i++) {
catalanNumber += catalan(i) * catalan( n- 1 -i);
return catalanNumber
To sum it up I only want to check how the maximum stack depth is.
Can someone help me?
Add a Set to your class that keeps track of what input was used and check that set inside the method
public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
private Set<Integer> alreadyHandled = new HashSet<>();
public int catalan(int a) {
if (alreadyHandled.add(a)) {
//rest of code
}
}
//...
}
Related
I'm trying to test out my program to see how it works, but I'm not sure how to call upon it in the main method. I've tried doing Assignment5Solution.findOrder() but it does not work. Any help with this issue would be greatly appreciated. The code is supposed to take the number of classes a student has to take along with the prerequisites for each course if there are any, and put the correct order of what classes the student should take.
package Assignment5;
import java.lang.reflect.Array;
import java.util.*;
/**
*
* #author harpe
*/
class Assignment5Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int E = prerequisites.length;
Graph G = new Graph(numCourses);
for (int i = 0; i < E; i++) {
G.addEdge(prerequisites[i][1], prerequisites[i][0]);
} // Graph is constructed
DFS d = new DFS(G); // depth first search
return d.reverseDFSorder();
}
public class DFS {
private boolean[] marked;
private int[] courseOrder; // i.e., reverse post order
private boolean hasCycle;
private int index; // index for the array courseOrder, index 0 is for the course taken first, …
private HashSet<Integer> callStack; // used to detect if there are cycles on the graph
DFS(Graph G) {
marked = new boolean[G.V()];
courseOrder = new int[G.V()];
index = courseOrder.length - 1; // index 0 of courseOrder will be course taken first, lastIndex will be taken last
callStack = new HashSet<Integer>(); // HashSet is a hash table, for O(1) search
for (int v = 0; v < G.V(); v++) { // to visit each node, including those on islands or isolated
if (!marked[v] && !hasCycle) {
dfs(G, v);
}
}
}
private void dfs(Graph G, int v) {
marked[v] = true;
callStack.add(v); // use HashSet to simulate callStack
for (int w : G.adj(v)) {
if (!marked[w]) {
dfs(G, w);
} else if (callStack.contains(w)) // search in HashSet is O(1)
{
hasCycle = true; // this is a cycle!
break;
}
}
callStack.remove(v);
courseOrder[index--] = v; // index starts from array length -1, decrease by 1 each time, and then ends at 0
}
public int[] reverseDFSorder() {
if (hasCycle) {
return new int[0]; // return an empty int array (with size 0)
}
return courseOrder;
}
} // end of class DFS
public class Graph {
private int V;
private List[] adj;
Graph(int V) // constructor
{
this.V = V;
adj = new List[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<Integer>();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public Iterable<Integer> adj(int v) {
return adj[v];
}
public int V() {
return V;
}
} // end of class Graph
} // end of class Solution
public int[] findOrder(int numCourses, int[][] prerequisites) {}
would need to be:
public static int[] findOrder(int numCourses, int[][] prerequisites) {}
The static keyword means you do not need to a declare an object of the class to use it. So you can use it using:
Assignment5Solution.findOrder(numCourses, prerequisites)
//numCourses and prerequisites can be any int and int[][] respectively.
EDIT: Another note too, depending on where your main method is you may need to make class Assignment5Solution a public class with:
public class Assignment5Solution {
It currently is package protected so it will only be able to be used if it is in the same package.
EDIT2:
If you want to use it as a nonstatic method you need to do something like this(change null and 0 to the real values):
Assignment5Solution test = new Assignment5Solution() {};
int numCourses = 0;
int [][] prereqs = null;
int[] reverseOrder = test.findOrder(numCourses, prereqs);
I'm having to make a program that allows a gerbil to go mining for four metals and the four metals have different levels of value. The gerbil can only carry 10 ounces at a time. The gerbil will prioritize carrying metals of higher value. I am just beginning classes, methods, and constructors, so the code I'm doing can't have anything too advanced. Any help? Here is what I have so far.
public class Gerbil {
private int totalRhodium;
private int totalPlatinum;
private int totalGold;
private int totalIron;
private int totals;
private int limit=10;
public Gerbil() {
}
public int printTotals() {
totals=totalRhodium+totalPlatinum+totalGold+totalIron;
return totals;
}
public void goMining(int rhodium, int platinum, int gold, int iron) {
System.out.println("Rhodium: "+rhodium);
System.out.println("Platinum: "+platinum);
System.out.println("Gold: "+gold);
System.out.println("Iron: "+iron);
}
}
You could try like this:
...
int totals = 0;
int totalsRhodium = 0;
int totalsPlatinum = 0;
int totalsGold = 0;
int totalsIron = 0;
int limit = 10;
public void goMining(int rhodium, int platinum, int gold, int iron) {
if(rhodium >= limit) {
this.totalsRhodium = limit;
return;
} else {
this.totalsRhodium = rhodium;
limit = limit - rhodium;
}
if(platinum >= limit) {
this.totalsPlatinum = limit;
return;
} else {
this.totalsPlatinum = platinum;
limit = limit - platinum;
}
//go on with the other metals
}
I want to call this method:
public int ArraySum(int[] a)
{
int sum = 0;
int Element;
for(Element = 0; Element < a.length; Element++)
{
sum = sum + a[Element];
}
return sum;
}
in this method (which is in a different class):
public int Mean()
{
return (something.ArraySum(a))/2;
}
I know that I probably need to create an object but I'm not sure exactly how.
Just an example:
public class C1
{
//all the fields and stuff
public int hello(int a)
{
//all the code
}
public static int hey(int a)
{
//all code
}
}
Note: One of the functions is static. Observe how we call them.
public class C2
{
//all fields and stuff
public void callerFunction()
{
C1 obj=new C1();
//created an object of class C1
obj.hello(5);
C1.hey(10);
//only class name is required while calling static methods.
}
}
You need to create an object of the class ArraySum method is present in. E.g. if it's present in Calculator class like below:
public class Calculator{
public int ArraySum(int[] a){
int sum = 0;
int Element;
for(Element = 0; Element < a.length; Element++)
{
sum = sum + a[Element];
}
return sum;
}
}
Then, what you need to do is (assuming that class doesn't define any non zero argument constructor),
Calculator calculator = new Calculator();
calculator.ArraySum(..);
I would like to write simple program which can offer me feature to print n even numbers starting from some firstNumber. Its number is totalNumber. I don't want to save them, just print them. This is my piece of code:
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
return new myNewIterator();
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
public myNewIterator() {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
totalNumbers--;
return true;
}
return false;
}
#Override
public Integer next() {
return tmp + 2;
}
}
}
And Main:
public class Main {
public static void main(String[] args) {
EvenNumbers en = new EvenNumbers(14, 4);
for (Integer n : en) {
System.out.println(n);
}
}
}
As may you can see, I don't get any output for this program.
Can someone explain me what I doing wrong?
Many thanks!
Why do you have so much code?
public class Main {
public static void main(String[] args) {
int start = 14;
int count = 4;
for (int n = start; n < start + 2 * count; n += 2) {
System.out.println(n);
}
}
}
#fafl answer is a better and concise answer.
To point out why this code was not working:
1. The problem is with your myNewIterator constructor. You were assigning the variable with itself. Also as default value of int is zero and your iteration condition if(totalNumbers > 0) will always fail.
public myNewIterator() {
/** these two lines have to be changed**/
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
/** end **/
this.tmp = firstNumber - 2;
}
You have to take these two values from constructor. Following is the corrected code. I have corrected the constructor name as well.
2. you must not decrement totalNumbers in hasNext() method because say there is a only one next element if I call hasNext() 100 times without calling next() it should still return true i.e. it has next element. So decrement should happen when next() is called.
3. tmp must be updated for every next() call.
These changes also are reflected in following code.
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
/***** changed *****/
return new myNewIterator(this.firstNumber,this.totalNumbers);
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
/***** changed *****/
public myNewIterator(int firstNo,int totalNo) {
/***** changed *****/
/**** edited these lines *******/
this.firstNumber = firstNo;
this.totalNumbers = totalNo;
/***** ****/
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
/***** changed *****/
//totalNumbers--; //commenting this line as repeated calls of this line makes this call unsafe
return true;
}
return false;
}
#Override
public Integer next() {
/***** changed *****/
totalNumbers--;
tmp = tmp + 2
return tmp;
}
}
}
How do I write a constructor to change ints to ints or longs or strings....I am making a Memory system and I have code for Memory and a Memory Element (MemEl) and my test code and I am trying to write these constructors: MemEl(int), MemEl(long), MemEl(String) I already have done it for shorts and bytes but I need some help with these. Thanks.
Here is my Memory code:
class Memory{
private MemEl[] memArray;
private int size;
public Memory(int s)
{size = s;
memArray = new MemEl[s];
for(int i = 0; i < s; i++)
memArray[i] = new MemEl();
}
public void write (int loc, int val)
{if (loc >=0 && loc < size)
memArray[loc].write(val);
else
System.out.println("Index Not in Domain");
}
public MemEl read (int loc)
{return memArray[loc];
}
public void dump()
{
for(int i = 0; i < size; i++)
if(i%1 == 0)
System.out.println(memArray[i].read());
else
System.out.print(memArray[i].read());
}
}
Here is my Memory Element Code:
class MemEl{
private int elements;
public Memory MemEl[];
{
elements = 0;
}
public void MemEl(byte b)
{
elements = b;
}
public void MemEl(short s)
{
elements = s;
}
public int read()
{
return elements;
}
public void write(int val)
{
elements = val;
}
}
Here is my Test code
class Test{
public static void main(String[] args)
{
int size = 100;
Memory mymem;
mymem = new Memory(size);
mymem.write(98,4444444);
mymem.write(96,1111111111);
MemEl elements;
elements = mymem.read(98);
System.out.println(mymem);
mymem.dump();
}
}
If you can afford to lose precision, then you can cast:
public MemEl(long longValue) {
elements = (int) longValue;
}
and parse:
public MemEL(String str) {
elements = Integer.parseInt(str);
}
elements is an int. byte and short can be cast implicitly (without you knowing) to int. long and String can't, hence you will not be able to add a constructor to the MemEl class