I am trying to write a method public static void removeDownTo (StackX stack, long n): It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty.
I've tried to section off the problem by popping off the top half of the stack by reaching the n value. But the stack isn't sorted so it causes some problems.
public class StackX {
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
//--------------------------------------------------------------
public void push(long j) // put item on top of stack
{
if (!isFull())
stackArray[++top] = j; // increment top, insert item
else
System.out.println("Can't insert, stack is full");
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
if(!isEmpty())
return stackArray[top--]; // access item, decrement top
else
System.out.print("Error: Stack is empty. Returning -1");
return -1;
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
if (isEmpty()){
System.out.print("stack is empty");
}
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
//--------------------
public boolean isFull() // true if stack is full
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
public void removeDownTo (StackX stack, long n){
for(int i = 0; stackArray[i] < n; i++){
stack.pop();
}
for(int j = 0; stackArray[j] <= maxSize; j++){
System.out.println(stackArray[j]);
}
}
}
public class StackApp {
public static void main(String[] args) {
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);
while( !theStack.isEmpty()){ // until it's empty,
theStack.removeDownTo(theStack, 40);
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
} // end main()
} // end class StackApp
I would expect to see 60 80 but instead I get 60 20.
Since you are quite new to programming, your instructor has given you a task that is quite simple to solve. You should stick closely to its words. These words give you the main clues.
You are supposed to define this method:
public static void removeDownTo (StackX stack, long n)
Here, the word static is important. It means that the method should NOT go into the StackX class. (The instructions should mention this somewhere.) If your task had been to add the method to the StackX class, it would have looked like this:
public void removeDownTo (long n)
The difference between these two methods is that the latter has access to all the implementation details of the StackX class, which are the variables maxSize, stackArray and top.
But your task was different, your method should be static, and this means that it doesn't have access to these implementation details. All you can do is call the methods that are marked as public. There are 5 of them, they all start with a lowercase letter. Using only these 5 methods, you are supposed to solve this puzzle, as you wrote:
It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty.
By listing the 5 methods above, you can see that a stack allows only very few operations. Think of a large stack of books. You cannot just take one book from the middle, the only thing you can do is to look at the top of the stack. That's the nature of a stack.
You tried:
I've tried to section off the problem by popping off the top half of the stack by reaching the n value. But the stack isn't sorted so it causes some problems.
This task is much simpler than you think. It is not about sorting at all. Follow the words in the instructions more closely. In the end, your removeDownTo method should be 5 lines long, from the beginning to the end. That means inside the braces, there are only 3 lines of code that you need to write.
As title says I need to do the following. But I somehow am getting the wrong answer, perhaps something with the loops is wrong?
And here's what I have coded so far, but it seems to be giving me the wrong results. Any ideas, help, tips, fixes?
import java.util.ArrayList;
public class pro1
{
private String lettersLeft;
private ArrayList<String> subsets;
public pro1(String input)
{
lettersLeft = input;
subsets = new ArrayList<String>();
}
public void createSubsets()
{
if(lettersLeft.length() == 1)
{
subsets.add(lettersLeft);
}
else
{
String removed = lettersLeft.substring(0,1);
lettersLeft = lettersLeft.substring(1);
createSubsets();
for (int i = 0; i <= lettersLeft.length(); i++)
{
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
public void showSubsets()
{
System.out.print(subsets);
}
}
My test class is here:
public class pro1
{
public static void main(String[] args)
{
pro1s = new pro1("abba");
s.createSubsets();
s.showSubsets();
}
}
Try
int numSubsets = (int)java.lang.Math.pow(2,toSubset.length());
for (int i=1;i<numSubsets;i++) {
String subset = "";
for (int j=0;j<toSubset.length();j++) {
if ((i&(1<<j))>0) {
subset = subset+toSubset.substring(j,j+1);
}
}
if (!subsets.contains(subset)) {
subsets.add(subset);
}
}
where toSubset is the string that you wish to subset (String toSubset="abba" in your example) and subsets is the ArrayList to contain the results.
To do this we actually iterate over the power set (the set of all subsets), which has size 2^A where A is the size of the original set (in this case the length of your string).
Each subset can be uniquely identified with a number from 0 to 2^A-1 where the value of the jth bit (0 indexed) indicates if that element is present or not with a 1 indicating presence and 0 indicating absence. Note that the number 0 represents the binary string 00...0 which corresponds to the empty set. Thus we start counting at 1 (your example did not show the empty set as a desired subset).
For each value we build a subset string by looking at each bit position and determining if it is a 1 or 0 using bitwise arithmetic. 1<<j is the integer with a 1 in the jth binary place and i&(i<<j) is the integer with 1's only in the places both integers have a 1 (thus is either 0 or 1 based on if i has a 1 in the jth binary digit). If i has a 1 in the jth binary digit, we append the jth element of the string.
Finally, as you asked for unique subsets, we check if we have already used that subset, if not, we add it to the ArrayList.
It is easy to get your head all turned around when working with recursion. Generally, I suspect your problem is that one of the strings you are storing on the way down the recursion rabbit hole for use on the way back up is a class member variable and that your recursive method is a method of that same class. Try making lettersLeft a local variable in the createSubsets() method. Something like:
public class Problem1
{
private String originalInput;
private ArrayList<String> subsets;
public Problem1(String input)
{
originalInput = input;
subsets = new ArrayList<String>();
}
// This is overloading, not recursion.
public void createSubsets()
{
createSubsets(originalInput);
}
public void createSubsets(String in)
{
if(in.length() == 1)
{
// this is the stopping condition, the bottom of the rabbit hole
subsets.add(in);
}
else
{
String removed = in.substring(0,1);
String lettersLeft = in.substring(1);
// this is the recursive call, and you know the input is getting
// smaller and smaller heading toward the stopping condition
createSubsets(lettersLeft);
// this is the "actual work" which doesn't get performed
// until after the above recursive call returns
for (int i = 0; i <= lettersLeft.length(); i++)
{
// possible "index out of bounds" here if subsets is
// smaller than lettersLeft
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
Something to remember when you are walking through your code trying to think through how it will run... You have structured your recursive method such that the execution pointer goes all the way down the recursion rabbit hole before doing any "real work", just pulling letters off of the input and pushing them onto the stack. All the "real work" is being done coming back out of the rabbit hole while letters are popping off of the stack. Therefore, the first 'a' in your subsets list is actually the last 'a' in your input string 'abba'. I.E. The first letter that is added to your subsets list is because lettersLeft.length() == 1. (in.length() == 1 in my example). Also, the debugger is your friend. Step-debugging is a great way to validate that your code is actually doing what you expect it to be doing at every step along the way.
YES, this is a homework project.
That being said, I'm looking to learn from my mistakes rather than just have someone do it for me.
My project is a word frequency list - I accept a text file (or website URL) and count the:
- Number of unique words, and
- How many times they appear.
All methods are provided for me except for one: the insert(E word) method, where the argument is a generic type word.
The word is stored in a Node (Linked List project) that also has a 'count' value, which is the value representing the number of times the word appears in the text being read.
What this method has to do is the following:
If the argument is already in the list, increment the count of that element. I have done this part
If the argument is not found in the list, append it to the list. I also have done this part.
sort the list by descending count value. i.e. highest -> lowest count
3.5. If two elements have the same count value, they are sorted by the dictionary order of their word.
I am VERY unfamiliar with Linked Lists, so as such I am running into a lot of NullPointerExceptions. This is my current insert method:
public void insert(E word){
if(word.equals("")){
return;
}
if(first == null){//if list is null (no elements)
/*Node item = new Node(word);
first = item;*/
first = new Node(word);
}
else{//first != null
Node itemToAdd = new Node(word);
boolean inList = false;
for(Node x = first; x != null; x=x.next){
if (x.key.equals(word)){// if word is found in list
x.count++;//incr
inList = true;//found in list
break;//get out of for
}//end IF
if(x.next == null && inList == false){//if end of list && not found
x.next = itemToAdd;//add to end of list
break;
}//end IF
}//end FOR
//EVERYTHING ABOVE THIS LINE WORKS.
if (!isSorted()){
countSort();
}
}//end ELSE
}//end method
My isSorted() method:
public boolean isSorted(){
for(Node copy = first; copy.next != null; copy = copy.next){
if (copy.count < copy.next.count){
return false;
}
}
return true;
}
and last but not least, the part where I'm struggling, the sort method:
public void countSort(){
for (Node x = first, p = x.next; p != null; x=x.next, p=p.next){
// x will start at the first Node, P will always be 1 node ahead of X.
if(x == first && (x.count < p.count)){
Node oldfirst = first;
x.next = p.next;
first = p;
first.next = oldfirst;
break;
}
if (x.count < p.count){
//copy.next == x.
Node oldfirst = first;
oldfirst.next = first.next;
x.next = p.next;
first = p;
first.next = oldfirst;
break;
}
if (x.count == p.count){
if(x.toString().charAt(0) < p.toString().charAt(0)){
//[x]->[p]->[q]
Node oldfirst = first;
x.next = p.next;
first = p;
first.next = oldfirst;
break;
}
}
}
}
Here is the output of my insert method when called by the classes/methods given to me:
Elapsed time:0.084
(the,60)
(of,49)
(a,39)
(is,46)
(to,36)
(and,31)
(can,9)
(in,19)
(more,7)
(thing,7)
(violent,3)
(things,3)
(from,9)
(collected,1)
(quotes,1)
(albert,1)
(einstein,2)
(any,2)
(intelligent,1)
(fool,1)
(make,1)
(bigger,1)
(complex,1)
(it,11)
(takes,1)
(touch,1)
(genius,1)
(lot,1)
(courage,1)
(move,1)
(opposite,1)
(direction,1)
(imagination,1)
(important,5)
(than,3)
(knowledge,3)
(gravitation,1)
(not,17)
(responsible,1)
(for,14)
(people,2)
(falling,1)
(love,2)
(i,13)
(want,1)
(know,3)
(god,4)
(s,8)
(thoughts,2)
(rest,2)
(are,11)
(details,2)
(hardest,1)
(world,7)
(understand,3)
(income,1)
(tax,1)
(reality,3)
(merely,1)
(an,7)
(illusion,2)
(albeit,1)
(very,3)
(persistent,2)
(one,12)
(only,7)
(real,1)
(valuable,1)
(intuition,1)
(person,1)
(starts,1)
(live,2)
(when,3)
(he,11)
(outside,1)
(himself,4)
(am,1)
(convinced,1)
(that,14)
(does,5)
(play,2)
(dice,1)
(subtle,1)
(but,8)
(malicious,1)
(weakness,2)
(attitude,1)
(becomes,1)
(character,1)
(never,3)
(think,1)
(future,2)
(comes,1)
(soon,1)
(enough,1)
(eternal,1)
(mystery,1)
(its,4)
(comprehensibility,1)
(sometimes,1)
My initial idea has been to try and loop the if(!isSorted()){ countSort();} part to just repeatedly run until it's sorted, but I seem to run into an infinite loop when doing that. I've tried following my professor's lecture notes, but unfortunately he posted the previous lecture's notes twice so I'm at a loss.
I'm not sure if it's worth mentioning, but they provided me an iterator with methods hasNext() and next() - how can I use this as well? I can't imagine they'd provide it if it were useless.
Where am I going wrong?
You are close. First the function to compare the items is not complete, so isSorted() could yield wrong results (if the count is the same but the words are in wrong order). This is also used to sort, so it's best to extract a method for the comparison:
// returns a value < 0 if a < b, a value > 0 if a > b and 0 if a == b
public int compare(Node a, Node b) {
if (a.count == b.count)
return a.word.compareTo(b.word);
// case-insensitive: a.word.toLoweCase().compareTo(b.word.toLowerCase())
} else {
return a.count - b.count;
}
}
Or simplified which is enough in your case:
public boolean correctOrder(Node a, Node b) {
if (a.count > b.count)
return true;
else if (a.count < b.count)
return false;
else
return a.word.compareTo(b.word) <= 0;
}
For the sort you seem to have chosen bubble sort, but you are missing the outer part:
boolean change;
do {
change = false;
Node oldX = null;
// your for:
for (Node x = first; x.next != null; x = x.next) {
if (!correctOrder(x, x.next)) {
// swap x and x.next, if oldX == null then x == first
change = true;
}
oldX = x;
}
} while (change);
We could use the help of Java native library implementation or more efficient sort algorithms, but judging from the exercise the performance of the sort algorithm is of no concern yet, first need to grasp basic concepts.
With looking your codes, it sounds like to me that two things can be done:
Firstly, you can make use of Comparable class method. So, I assume you wrote the class Node, thus you may want to inherit from Comparable class. When you inherited from that class, java will automatically provide you the compareTo method, and all you need to do is to specify in that method that "I want to compare according to your counts and I want it to be in ascending order."
**Edit(1):By the way, I forgot the mention before but after you impelement your compareTo method, you can use Collections.sort(LinkedList list), and it will be done.
The second solution came to mind is that you can sort your list during the countSort() operation with the technique of adding all to an another list with sorting and after add all them back to the real list. The sorting technique I'm trying to say is, keep going towards to the end of the list until you find a Node in the list that has a count smaller than currently adding Node's counts. Hope that doesn't confuse your head, but by this way you can achieve more clear method and less complicated view. To be clear I want to repeat the procedure:
Look the next
If (next is null), add it //You are at the end.
else{
if (count is smaller than current count), add it there
else, keep moving to the next Node. //while can be used for that.
}
I'm stuck on how to write a delete method for a menu (object orientation) program I am writing. The menu gives the user the option to delete the last name entered on the program. I'm completely stuck on this part! Would be greatly appreciated if you guys/gals could show me a simple delete method!
Many Thanks!
This is my code so far for Adding a Name:
public static int addOne(String theArray[], int location, String theName, int noofvalues)
{
int step;
if(noofvalues == 0)
{
theArray[0] = theName;
noofvalues++;
}
else
{
for(step = noofvalues - 1; step >= location; step--)
{
theArray[step + 1] = theArray[step];
}
theArray[location] = theName;
noofvalues++;
}
return noofvalues;
}
Since it looks like homework, I won't provide any code at all (otherwise, I would solve the homework and you won't learn anything), only ideas an possibly an algorithm to do it.
Store the last name inserted by the user in a variable. Let's say, this variable is lastInsertedName.
Go through all the elements in your array and search this String in it. When you find lastInsertedName in the array, store the index in a variable, let's say indexFound and stop the loop.
If indexFound is greater or equals than 0:
Move all the elements starting at indexFound in the array one position back.
Decrease the variable that acts as the size of your array.
Use List:
public static int addOne(List names, int location, String theName, int noofvalues)
{
names.add(location, theName);
return names.size();
}
public static void deleteOne(List names, int location){
names.remove(location);
}
Here is a question about Stack on StackOverflow.
My question might seem very very vague but if you check my program which I have written then you might understand what I am trying to ask.
I have implemented the stack myself. I present the user with 3 choices. Push, Pop and View the stack. When view(display) method is called then bunch of 0s show instead of nothing. We know the stack contains nothing unless we put something on it. But since my implemented stack is stack of integers using array, the display method when called shows bunch of 0s(the default values of integers in the array). How do I show nothing instead of 0s. I know I can add ASCII for whitespace character but I think it would still violate the rule of stack(Stack should be empty when there is not element, not even code for whitespace).
Here is my program:
import java.util.Scanner;
public class StackClass
{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
int choice=0;
int push;
Stack stack=new Stack();
do
{
System.out.println("Please select a stack operation:\n1. Press 1 for adding to stack\n2. Press 2 for removing elements from stack\n3. View the stack");
choice=input.nextInt();
switch(choice)
{
case 1:
System.out.println("Please enter the number that you want to store to stack");
push=input.nextInt();
stack.push(push);
case 2:
stack.pop();
case 3:
stack.display();
}
}
while((choice==1)||(choice==2)||(choice==3));
}
}
class Stack
{
private int size;
private int[] stackPlaces=new int[15];
private int stackIndex;
Stack()
{
this.size=0;
this.stackIndex=0;
}
public void push(int push)
{
if(size<15)
{
stackPlaces[stackIndex]=push;
size++;
stackIndex++;
}
else
{
System.out.println("The stack is already full. Pop some elements and then try again");
}
}
public void pop()
{
if(size==0)
{
System.out.println("The stack is already empty");
}
else
{
stackPlaces[stackIndex]=0;
size--;
stackIndex--;
}
}
public void display()
{
System.out.println("The stack contains:");
for(int i=0;i<stackPlaces.length-1;i++)
{
System.out.println(stackPlaces[i]);
}
}
}
In display(), simply change your loop to use size for the loop condition, so that you display the logical number of elements:
for (int i=0;i < size; i++)
{
System.out.println(stackPlaces[i]);
}
Note that your existing loop was only showing 14 of the 15 values, too...
You initialize an array of int-s, of size 15. The int datatype defaults to 0 (as opposed to its wrapper class Integer which defaults to null), so what you are really doing is creating an int array with 15 0's. So, when you loop through the array and print its content, you will get, well, 15 0's.
The solution is, as implied by others, exchange the loop limitation to the size of the stack (the number of elements actually added), rather than the size of the array.
instead of for(int i=0;i<stackPlaces.length-1;i++), do for(int i=0;i<stackIndex;i++)