I am implementing a StackArray and this is the first time I have done it. The program is supposed to push 5 elements onto the stack, The output I am looking for is [a,b,c,d,e], then it will pop the head of the list and print it again until the list is empty. However, my output is [a,b,c,d]. It completely ignores the last element. I believe my push and pop methods need to be modified just a bit.
import java.util.NoSuchElementException;
public class StackArray //implements Stack interface
{
private Object[] item; // The array where elements are stored
private int top = 0; // The index of the first empty location in the stack
private int size = 2; // The current number of item locations in the stack
private Object[] temp = new Object[size];
/**
Constructs an empty stack.
*/
public StackArray()
{
item = new Object[size];
}
public void push(Object element)
{
if (top == item.length)
{
size = item.length * 2;
Object[] newItem = new Object[size];
for (int i = 0; i < item.length; i++)
{
newItem[i] = item[i];
}
item = newItem;
}
item[top++] = element;
}
public Object pop()
{
if (isEmpty())
{
throw new NoSuchElementException();
}
return item[--top];
}
public boolean isEmpty()
{
return top == 0;
}
public String toString()
{
if (top == 0) { return "[]"; }
String temp = "[" + item[0];
int i = 1;
while (i < top)
{
temp = temp + ", " + item[i];
i = i + 1;
}
temp = temp + "]";
return temp;
}
}
Here is my runner program:
public class StackArrayRunner
{
public static void main(String[] args)
{
StackArray sa = new StackArray();
sa.push("a");
sa.push("b");
sa.push("c");
sa.push("d");
sa.push("e");
System.out.println(sa);
System.out.println(sa.pop());
System.out.println(sa);
System.out.println(sa.pop());
System.out.println(sa);
System.out.println(sa.pop());
System.out.println(sa);
System.out.println(sa.pop());
System.out.println(sa);
System.out.println(sa.pop());
System.out.println(sa);
System.out.println(sa.pop());
}
}
The output should be:
[a,b,c,d,e]
e
[a,b,c,d]
d
[a,b,c]
c
[a,b]
b
[a]
a
Thank you!
Ok, quick question about exceptions. My output is right now but it throws the No such element exception at the end. Is this normal? Is that supposed to happen. Here is the new output:
[a, b, c, d, e]
e
[a, b, c, d]
d
[a, b, c]
c
[a, b]
b
[a]
a
[]
Exception in thread "main" java.util.NoSuchElementException
at StackArray.pop(StackArray.java:35)
at StackArrayRunner.main(StackArrayRunner.java:22)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You're getting exactly what you should expect: you're pushing five elements on, and making six pop() calls!
The first five pop an element off and return it (correctly); the last one prints the empty stack out ([]), then tries to pop(), and that gives you your problem. It'll throw a NoSuchElementException, because that's what your code does when you try to pop from an empty stack.
This looks like the basis for a good unit test to me :)
Yes that is expected, you are throwing an exception when the stack is empty, which it is after you pop A.
So, I'm very new to Java, I have a summer college course and we're on functions or methods and I'm having a bit of trouble understanding them.
There is a question on a lab I'm having a little trouble with:
"Write a method called MaxOfThree that accepts three integer
parameters and returns the largest of the three."
This is what I have so far but I'm not sure whats wrong. I added the print statement at the end because I wasn't getting a return value when I ran it but now I'm getting errors and it's not compiling. If you could help me understand methods a bit more I'd greatly appreciate it. For instance how the parameters work and calling it and if what's included in the function call is correct and how that works. I just get so confused when I read through the material and was hoping for an explanation in more layman's terms. Thanks for any help, here is what I have so far.
public class Test {
public static void main(String[] args) {
int a = 2, b = 3, c = 4;
int maxValue = max3(a, b, c);
}
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
System.out.println(max);
}
}
Here are the errors I'm receiving just in case...
Test.java:16: error: unreachable statement
System.out.println(max);
^
Test.java:17: error: missing return statement
}
^
2 errors
You can't have a statement after the return statement, or to be more exact - a statement imediatelly after a return statement (such as your println) can never be executed, and is therefore an error.
The println should be before the return statement.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
I suggest You to change those if statements into one simple for loop with simple int[] vector. This solution is much more elegant and flexible. Additionally, You initialized and not used anywhere int maxValue = max3(a, b, c); in Your code.
public class Demo {
public static void main(String args[]) {
int[] numbers = new int[] {2, 3, 4};
System.out.println(maxValue(numbers));
}
public static int maxValue(int[] n) {
int max = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] > max) {
max = n[i];
}
}
return max;
}
}
But let's bow for a moment on the problem of methods implementation in Java.
At the begining of Your journey through the vastness of the Java realm You should get familiar with two types of methods: 1) void methods, and 2) return methods. The first ones are responsible for doing something without returning any value. We can for example use them for setting values of the fields of our application, initializing GUI, or other operations. The use of the void method can look like this:
/* method declaration */
void setValue(int value) {
someField = value;
}
/* method invocation */
setValue(5);
After invocation of setValue(5) the value of the someField object will be 5. However, you have to remember about type compatibility, so in this case someField can not be e.g of String type.
Second method type mentioned above, i.e return method is very useful, when you expect the method to give You an output, e.g in result of some operations conducted on the data You've given to Your method. But of course it's not necessary, to provide for the return method an input. Anyway, the use of return method can look like this:
/* method returns text You've given to it */
String getText(String text) {
return text;
}
/* method returns result of addition of three given int's */
int calculate(int a, int b, int c) {
return a + b + c;
}
/* method return a random number */
int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
You can easily see, that there is plenty of space for improvisation. Basicaly and in summary, void methods can work with given objects, for example can set values and conduct other operations, but thay don't return any STRAIGHT results You can work with. Return methods, from the other hand, provide You physical results, which You can use in further operations, or even in other methods, for example:
import java.util.Random;
public class Demo {
private static int someValue;
public static void main(String args[]) {
setValue(calculate(
createRandomNumber(),
createRandomNumber(),
createRandomNumber()));
System.out.println(someValue);
}
public static void setValue(int value) {
someValue = value;
}
public static int calculate(int a, int b, int c) {
return a + b + c;
}
public static int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
}
The problem is that the compiler detects that execution will never reach the System.out.println line, so it refuses to compile. The line return max; effectively ends the method, so nothing more will run after that.
You should move return max; to below the System.out.println line.
Swap your last 2 lines (return and System).
It should be like this, return max statement should be the last line in your method if you want to print something, because return statement goes back or invoke the line that called him,so your print statement is not reach.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
You need to put
System.out.println(max);
before:
return max;
the reason is your return unconditionally ends the function and therefore the compiler won't reach the println causing a compile error.
You have a System.out.println() statement after the return. return ends the method and so the System.out.println() will never happen because the method will have ended. That's why you are getting errors. Put the System.out.println() before the return:
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
As already been said, after you return something, the method will end. So your output in the last line of the method will not be executed, so remove it.
You can print the returned value of the method when you write the following outside of the method:
System.out.println("highest value:" + max3(a,b,c));
So now, the 3 values are given to the method which can do something with them now. After it did the calculations, the method returns a value, which can now be printed to the console for example.
The issue with the code you provided is that you're trying to print to the console, after you use your return statement. This causes your program to never reach that line: System.out.println(max);
I am trying to make a url from a different combinations of string separated by comma so that I can use those url to execute them and get the data back.
I have simplified something like this, I have a HashSet that will contain all my strings, not A,B,C in real. I just modified it here to make it simple.
Set<String> data = new HashSet<String>();
h.add("A");
h.add("B");
h.add("C");
for (int i = 1; i < 1000; i++) {
String pattern = generateString(data);
String url = "http://localhost:8080/service/USERID=101556000/"+pattern;
System.out.println(url);
}
/**
* Below is the method to generate Strings.
/
private String generateString(HashSet<String> data) {
//not sure what logic I am supposed to use here?
}
So the output should be something like this-
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/C,A
--
And other combinations
The above output can be in any random order as well. But it should be all the possible combinations. And if all the possible combinations are finished then start again.
Any suggestion how can I achieve the above problem definition?
What you're asking is not trivial.
Let's look at 2 strings, A and B.
Here are all of the permutations.
A
B
AB
BA
Ok, let's look at 3 strings, A, B, and C.
Here are all the permutations.
A
B
C
AB
AC
BA
BC
CA
CB
ABC
ACB
BAC
BCA
CAB
CBA
Do you see a pattern yet?
First, you have to find all of the single string permutations. Then the two string permutations. Then the three string permutations. And so on, up to the number of strings.
Then, within a set of permutations (like the two string set), you have to find all of the possible permutations.
You can do this with java loops. You can also use recursion.
Given what is k-arrangement (http://en.wikibooks.org/wiki/Probability/Combinatorics), you are looking for the k-arrangement where k varies from 1 to D, where D is the size of the data collections.
This means to compute - my first post I can't post image so look at equation located at :
In order to do it, you can make k varies, and the for each k may n varies (i.e. deal only with a sub array or data to enumerate the k-permutations). These k-permutations can be found by walking the array to the right and to the left using recursion.
Here is a quick bootstrap that proves to enumerate whart is required :
public class EnumUrl {
private Set<String> enumeration = null;
private List<String> data = null;
private final String baseUrl = "http://localhost:8080/service/USERID=101556000/";
public EnumUrl(List<String> d) {
data = d;
enumeration = new HashSet<String>(); // choose HashSet : handle duplicates in the enumeration process
}
public Set<String> getEnumeration() {
return enumeration;
}
public static void main(String[] args) {
List<String> data = new ArrayList<String>();
data.add("A");
data.add("B");
data.add("C");
EnumUrl enumerator = new EnumUrl(data);
for (int k = 0; k < data.size(); k++) {
// start from any letter in the set
for (int i = 0; i < data.size(); i++) {
// enumerate possible url combining what's on the right of indice i
enumerator.enumeratePossibleUrlsToRight(data.get(i), i);
// enumerate possible url combining what's on the left of indice i
enumerator.enumeratePossibleUrlsToLeft(data.get(i), i);
}
// make a circular permutation of -1 before the new iteration over the newly combined data
enumerator.circularPermutationOfData();
}
// display to syso
displayUrlEnumeration(enumerator);
}
private void circularPermutationOfData() {
String datum = data.get(0);
for (int i = 1; i < data.size(); i++) {
data.set(i - 1, data.get(i));
}
data.set(data.size() - 1, datum);
}
private static void displayUrlEnumeration(EnumUrl enumerator) {
for (String url : enumerator.getEnumeration()) {
System.out.println(url);
}
}
private void enumeratePossibleUrlsToRight(String prefix, int startAt) {
enumeration.add(baseUrl + prefix);
if (startAt < data.size() - 1) {
startAt++;
for (int i = startAt; i < data.size(); i++) {
int x = i;
enumeratePossibleUrlsToRight(prefix + "," + data.get(x), x);
}
}
}
private void enumeratePossibleUrlsToLeft(String prefix, int startAt) {
enumeration.add(baseUrl + prefix);
if (startAt > 0) {
startAt--;
for (int i = startAt; i >= 0; i--) {
int x = i;
enumeratePossibleUrlsToLeft(prefix + "," + data.get(x), x);
}
}
}
}
The program outputs for {A,B,C} :
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/B,A,C
http://localhost:8080/service/USERID=101556000/B,C,A
http://localhost:8080/service/USERID=101556000/B,A
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/C,B,A
http://localhost:8080/service/USERID=101556000/A,C,B
http://localhost:8080/service/USERID=101556000/A,C
http://localhost:8080/service/USERID=101556000/A,B
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/C,B
http://localhost:8080/service/USERID=101556000/C,A
http://localhost:8080/service/USERID=101556000/C,A,B
And for {A,B,C,D} :
http://localhost:8080/service/USERID=101556000/B,A,D,C
http://localhost:8080/service/USERID=101556000/C,D
http://localhost:8080/service/USERID=101556000/A,D,C,B
http://localhost:8080/service/USERID=101556000/A,C,D
http://localhost:8080/service/USERID=101556000/D
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/A,C,B
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/A,B,C,D
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/D,C,B,A
http://localhost:8080/service/USERID=101556000/C,B,A,D
http://localhost:8080/service/USERID=101556000/A,B,D
http://localhost:8080/service/USERID=101556000/D,B
http://localhost:8080/service/USERID=101556000/D,C
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/D,C,A
http://localhost:8080/service/USERID=101556000/D,C,B
http://localhost:8080/service/USERID=101556000/C,D,A
http://localhost:8080/service/USERID=101556000/C,D,B
http://localhost:8080/service/USERID=101556000/D,A
http://localhost:8080/service/USERID=101556000/A,D,C
http://localhost:8080/service/USERID=101556000/A,D,B
http://localhost:8080/service/USERID=101556000/C,B,D
http://localhost:8080/service/USERID=101556000/B,A,D
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/B,A,C
http://localhost:8080/service/USERID=101556000/B,C,A
http://localhost:8080/service/USERID=101556000/B,A
http://localhost:8080/service/USERID=101556000/B,C,D
http://localhost:8080/service/USERID=101556000/C,B,A
http://localhost:8080/service/USERID=101556000/A,D
http://localhost:8080/service/USERID=101556000/D,A,B
http://localhost:8080/service/USERID=101556000/A,C
http://localhost:8080/service/USERID=101556000/D,A,C
http://localhost:8080/service/USERID=101556000/B,C,D,A
http://localhost:8080/service/USERID=101556000/A,B
http://localhost:8080/service/USERID=101556000/B,D
http://localhost:8080/service/USERID=101556000/C,D,A,B
http://localhost:8080/service/USERID=101556000/D,A,B,C
http://localhost:8080/service/USERID=101556000/D,B,A
http://localhost:8080/service/USERID=101556000/D,B,C
http://localhost:8080/service/USERID=101556000/B,D,A
http://localhost:8080/service/USERID=101556000/C,B
http://localhost:8080/service/USERID=101556000/C,A,D
http://localhost:8080/service/USERID=101556000/C,A
http://localhost:8080/service/USERID=101556000/B,D,C
http://localhost:8080/service/USERID=101556000/C,A,B
Which is not the exhaustive enumeration. Basically we should have:
(my first post I can't post image to look at equation located in my reply, I don't have the reputation to post 2 links ... #omg)
That makes 64 combinaisons, distributed as follows:
4 combinaisons of 1 element (k=1)
12 combinaisons of 12 element (k=2)
24 combinaisons of 24 element (k=3)
24 combinaisons of 24 element (k=4)
You can see that my program is OK for k=1, k=2, and k=3. But there are not 24 combinaisons for k=4. In order to complete the program, you will need to iterate also on other type of shuffling the data than circular permutation. Actually when k=4, circular permutation does not generate for instance ADBC as input data (hence DBCA cannot be generated by my implementation for instance). In this case, you will want to enumerate all possible data input array with n elements in all possible order. This is a special case of k-permutation, where k=n, and therefore leads to finding the n! permutation. We can achieve this by calling the EnumUrl method for each of the n! possible permutation.
For this, you should update EnumUrl enumerator = new EnumUrl(data); accordingly, but I guess I am letting some work for you to make :-)
HTH
A short version working for arbitrary set size, with generics, using guava, and the method for permutation given here.
Basically the idea is the following :
Generate the powerset, discard empty set
For each set of the powerset, generate all permutations
public class QuickEnumeration {
Set<T> objects;
public QuickEnumeration(Set<T> objects) {
this.objects = objects;
}
public List<List<T>> generateEnumeration() {
List<List<T>> result = new ArrayList<List<T>>();
// Compute the powerset
Set<Set<T>> powerset = Sets.powerSet(objects);
for (Set<T> set : powerset) {
// Discard empty set
if (set.size() > 0) {
// Arraylist faster for swapping
ArrayList<T> start = new ArrayList<T>(set);
permute(start, 0, result);
}
}
return result;
}
private void permute(ArrayList<T> arr, int k, List<List<T>> result) {
for (int i = k; i < arr.size(); i++) {
java.util.Collections.swap(arr, i, k);
permute(arr, k + 1, result);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() - 1) {
result.add((List<T>) arr.clone());
}
}
public static void main(String[] args) {
Set<String> testSet = new HashSet<>();
testSet.add("A");
testSet.add("B");
testSet.add("C");
QuickEnumeration<String> enumerate = new QuickEnumeration<>(testSet);
System.out.println(enumerate.generateEnumeration());
}
}
Testing with "A","B","C" gives :
[[A], [B], [A, B], [B, A], [C], [A, C], [C, A], [B, C], [C, B], [A, B, C], [A, C, B], [B, A, C], [B, C, A], [C, B, A], [C, A, B]]
I am not entirely sure what you really want, so I ended up writing this piece of code for you. Hope it gets you started!
public static void doThis() {
String url1="http://www.example.com";
String string1="A";
String url2="http://www.foo.com";
String string2="B";
String url3="http://www.bar.com";
String string3="C";
Map<String, String> abbrMap = new HashMap<String, String>();
abbrMap.put(string1, url1);
abbrMap.put(string2, url2);
abbrMap.put(string3, url3);
String string = string1+string2+string3;
for(Map.Entry<String, String> m : abbrMap.entrySet()) {
arrange(string, m.getValue());
}
}
private static void arrange(String str, String url) {
if (str.length()==0) return;
StringBuffer sbuf = new StringBuffer();
for (int j=0; j<str.length(); j++) {
for(int i=j; i<str.length(); i++) {
char c = str.charAt(i);
sbuf.append(c);
System.out.println(url+"/"+sbuf.toString());
sbuf.append(",");
}
sbuf.setLength(0);
}
}
Output:
http://www.example.com/A
http://www.example.com/A,B
http://www.example.com/A,B,C
http://www.example.com/B
http://www.example.com/B,C
http://www.example.com/C
http://www.foo.com/A
http://www.foo.com/A,B
http://www.foo.com/A,B,C
http://www.foo.com/B
http://www.foo.com/B,C
http://www.foo.com/C
http://www.bar.com/A
http://www.bar.com/A,B
http://www.bar.com/A,B,C
http://www.bar.com/B
http://www.bar.com/B,C
http://www.bar.com/C
Does anyone know the Donald B. Johnson's algorithm, which enumerates all the elementary circuits (cycles) in a directed graph?
I have the paper he had published in 1975, but I cannot understand the pseudocode.
My goal is to implement this algorithm in Java.
Some questions I have, for example, is what is the matrix Ak it refers to. In the pseudocode, it mentions that
Ak:=adjacency structure of strong component K with least
vertex in subgraph of G induced by {s,s+1,....n};
Does that mean I have to implement another algorithm that finds the Ak matrix?
Another question is what the following means?
begin logical f;
Does also the line "logical procedure CIRCUIT (integer value v);" mean that the circuit procedure returns a logical variable? In the pseudocode also has the line "CIRCUIT := f;". What does this mean?
It would be great if someone could translate this 1970's pseudocode to a more modern type of pseudocode so I can understand it
In case you are interested to help but you cannot find the paper please email me at pitelk#hotmail.com and I will send you the paper.
The pseudo-code is reminiscent of Algol, Pascal or Ada.
Does that mean I have to implement another algorithm that finds the Ak matrix?
Ak appears to be a list of arrays of input values having the specified properties. It may be related to the corresponding adjacency matrix, but it's not clear to me. I'm guessing something like this:
int[][] a = new int[k][n];
int[][] b = new int[k][n];
boolean[] blocked = new boolean[n];
int s;
What does logical f mean?
This declares a local variable representing a true or false value, similar to Java's boolean.
logical procedure CIRCUIT (integer value v);
This declares a subprogram named CIRCUIT having a single integer parameter v that is passed by value. The subprogram returns a logical result of true or false, and CIRCUIT := f assigns f as the result. In Java,
boolean circuit(int v) {
boolean f;
...
f = false;
...
return f;
}
The keywords begin and end delimit a block scope that may be nested, so CIRCUIT is nested in the main block and UNBLOCK is nested inside of CIRCUIT. := is assignment; ¬ is not; ∈ is element; ∅ is empty; ≠ is !=; stack and unstack suggest push and pop.
It's only a start, but I hope it helps.
Addendum: On reflection, A and B must be isomorphic.
Here's a very literal outline. I don't know enough about A, B & V to choose a better data structure than arrays.
import java.util.Stack;
public final class CircuitFinding {
static int k, n;
int[][] a = new int[k][n];
int[][] b = new int[k][n];
boolean[] blocked = new boolean[n];
int[] v = new int[k];
int s = 1;
Stack<Integer> stack = new Stack<Integer>();
private void unblock(int u) {
blocked[u] = false;
for (int w : b[u]) {
//delete w from B(u)
if (blocked[w]) {
unblock(w);
}
}
}
private boolean circuit(int v) {
boolean f = false;
stack.push(v);
blocked[v] = true;
L1:
for (int w : a[v]) {
if (w == s) {
//output circuit composed of stack followed by s;
f = true;
} else if (!blocked[w]) {
if (circuit(w)) {
f = true;
}
}
}
L2:
if (f) {
unblock(v);
} else {
for (int w : a[v]) {
//if (v∉B(w)) put v on B(w);
}
}
v = stack.pop();
return f;
}
public void main() {
while (s < n) {
//A:= adjacency structure of strong component K with least
//vertex in subgraph of G induced by {s, s+ 1, n};
if (a[k] != null) {
//s := least vertex in V;
for (int i : v) {
blocked[i] = false;
b[i] = null;
}
L3:
circuit(s);
s++;
} else {
s = n;
}
}
}
}
You can find a Java implementation of this algorithm on github: https://github.com/1123/johnson. It uses the Jung2 java graph library.