Duplicating elements in a stack? - java

So I have a method to take a stack of Integers, and return the stack with all of the elements duplicated, and in the same order. My problem is with the method i currently have, Im getting an infinite loop problem on all cases except when the Stack is empty. What can i do to complete the duplication without a looping problem?
public void stutter(Stack<Integer> Integ)
{
Integer first;
for(int i = 0; i < Integ.size(); i++)
{
first = Integ.pop();
Integ.push(first);
Integ.push(first);
}
}

Each time you push another integer, you increase the original size of your stack, pushing your "i" limit forward.
You should return a new Stack, preferably using (pre java8):
public Stack<Integer> stutter(Stack<Integer> from) {
Stack<Integer> stk = new Stack<>();
for(Integer i: from) {
stk.push(i);
stk.push(i);
}
return stk;
}

ofc, its an inifinite loop. You increase the Integ.size() inside of the loop by Integ.push().
Try something like that. Save the size inside a var befor starting to push new elements into it.
int size = Integ.size();
for(int i = 0; i < size; i++){
first = Integ.pop();
Integ.push(first);
Integ.push(first);
}

Just create new stack with duplicates (and replace old if needed).

Related

How to remove elements from an ArrayList?

ArrayList<Rolling> copy = new ArrayList<Rolling>();
for (int i = 0; i < sequence.size(); i++) {
copy.add(sequence.get(i));
}
ListIterator<Rolling> listIterator = copy.listIterator();
// Remove each element one by one
for (int j = 0; j < copy.size(); j++) {
listIterator.next();
if (copy.contains()) {
listIterator.remove();
}
}
public static void main(String[] args) {
remove(sequenceOfDice(4), 4);
}
}
short summary: I have a class called Rolling and I wanna thru this method copy its elements and then remove the value of n from the new list and return the rest but I am not geting far since i got a couple of errors.
The error I get is:The method contains(Object) in the type ArrayList is not applicable for the arguments ()
the method "copy.contains()" should have a parameter(argument).
that means,you should write like this "copy.contains(x)"
what's more, i think you are a new learner.because your code have many errors or sames strange.
your comment is "// Remove each element one by one"
but you said "then remove the value of n from the new list", is this conflict?
please paste all the code and compile it successfully on your laptop.
By the way, in a for loop, we usually use iterator to remove element because remove element will cause modcount change,try below code:
while(listIterator.hasNext()){
Rolling next = listIterator.next();
if (copy.contains(next)) {
listIterator.remove();
}
}

Sorting a randomized array in Java

I am trying to make an app for sorting a randomized array
I made some code and I can not see what is wrong with it that it returns wrong values
Notes: I am trying to learn programming. So don't suggest whole different ways of solving the problem. I just want to see what is wrong with this code so I can get better.
What RandomArrayCreator.create() returns is just an array of numbers in randomized order.
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j]) j=k;
}
siralanmish[i]=siyahi[j];
siyahi[j]=siyahi.length+1;
}
System.out.println(siralanmish[i]);
}
}
}
I know you did not want suggestions but I'm going to offer one anyway.
Hopefully this will help guide you along the way, but still allow you to come up with your own solution.
Sort smallest to biggest.
did I have swap an element?
while I swapped an element
assume I did not swap an element
for element i in the array
is i > i+1?
if yes
swap the elements
I did swap an element
else
do nothing
Given that you mentioned you wanted to learn how to improve your current program, here are minimalist changes that will have your code produce a sorted array.
A few notes on the changes:
1.
if (siyahi[k]<siyahi[j]) j=k;
This I assume is for trying to swap the values at each indexes. Instead you are assigning the value of k to j which will cause problems with the entire for loop. I replaced this with the following:
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
This creates a temporary variable to store one of the values so that you can swap the value at each index without losing one of your values.
2.
siralanmish[i]=siyahi[j];
This was replaced with:
siralanmish[j]=siyahi[j];
This allows you to directly copy the values from the same index from the source array to the target array.
3.
siyahi[j]=siyahi.length+1;
This code will just fill up your array with the value of length+1 for your original array and you will lose your other values.
Your code with the fixes are below:
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
}
siralanmish[j]=siyahi[j];
}
System.out.println(siralanmish[i]);
}
}

Is there anything wrong in these two methods that copy & returns an array

Is there anything wrong in these two methods that copy & returns an array?
This is how i called it :
o2[i].addArr(o1.getArr());
And at the end the result is that o2[i].getArr(); is empty. I don't know why but this is my code if you could help me
NOTE: The class Array i wrote it here Array while it's another class name in my code. just to make it clear for you
public Array[] getArr(){ //first method
int count=0;
for(int i=0;i<10;i++){
if(Arrlist[i]!=null)
count++;}
Array[] arr=new Array[count];
for(int i=0;i<count;i++)
arr[i]=Arrlist[i];
return arr;}
public void addArr(Array[]arr){ //second method
for(int i=0;i<arr.length;i++)
Arrlist[i]=arr[i];
}
Yes. In getArr, you're going to overrun the length of the array you're creating if you have any null entries in the array you're copying.
In the loop where you're actually copying, you need separate variables for the index into arr and the index into Arrlist, because you need to skip nulls.
E.g., along these lines (untested):
int i, j;
j = 0;
for (i = 0; i < Arrlist.length; ++i) {
if (Arrlist[i] != null) {
arr[j++] = Arrlist[i];
}
}
addArr is okay if (and it's a big "if") Arrlist is allocated and it's the same size as arr. (You could replace it with System.arraycopy.) Note that the name is misleading, though; you're overwriting Arrlist, not adding to it. And again, those are some pretty big "if"s.

Why do I get a "duplicate local variable" error?

I have a loop in which I calculate a value and add it it a list. So, I do something like that:
x = getValue()
values.add(x)
while (true) {
x = getValue();
values.add(x)
}
I found out that this approach does not work since I add the same instance to the list. In more details, in every cycle of the loop I re-assign a new value to the x and doing so I change values of all elements that were already added to the list (so in the end I get a list of identical elements).
To solve this problem I did the following:
x = getValue();
Integer[] valueToAdd = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
while (true) {
x = getValue();
y = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
values.add(valueToAdd)
}
In this way I wanted to create a new instance every time want to add a value to the list. But it does not work since I get a duplicate local variable error.
It is also strange to me that I do not have this error if I declare the same variable many times in the loop. The problem appears only if I first declare a new variable outside the loop and then also in the loop.
Is there a way in Java to re-use the same name for different instances?
ADDED
I need to clarify some issues. I did not show all the code. I have the break command in the loop (when a new value cannot be generate, I exit the loop). x and value have Integer[] type.
ADDED 2
Since it was mentioned that the problem can be in the getValue() I need to in more details here. Actually I do not have getValue() in my code (I used getValue() here to make my example shorter). In my code I had:
Integer[] x = new x[n];
while (true) {
for (int i=0; i<n; i++) {
x[i] = y[i];
}
values.add(x)
}
And it did not work since in my values list I had identical elements (and I know that in the loop on every cycle x had a new value).
ADDED 3
Why all elements of my list seems to be the same?
Your problem is not what you think it is. For example take a look at this simple program:
String x = null;
List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i ++) {
x = String.valueOf(i);
l.add(x);
}
System.out.println(l);
It prints the numbers from 0 to 9. This is because java is pass-by-value (check here). You are not passing the reference to x, you are passing the value of x (in the add method).
So the problem lies in the getValue() method, which returns the same object.
Update: Now the question makes more sense. You are working with the same object x everytime, and just changing its state. In order to put different values just move the declaration inside the loop:
while (true) {
Integer[] x = new x[n];
...
}
If you need it outside the loop, well, simply use another variable there. It does not have to be named x. Since you won't be using it inside the loop anyway.

Populating stack causes error

I'm populating a stack instance variable with elements of the array el, but in the line below it's giving me an error although I specified that it's a stack of Integers.
Error:
Incompatible types - found java.util.Stack but expected java.lang.Integer...
Code:
import java.util.Stack;
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
el[i] = stack; /** THIS LINE*/
}
}
}
To add an item to the top of the stack, use the push method.
Example:
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i]);
}
}
This will push elements from the el array into the stack.
I think you want to add elements of el into stack . You were trying to assign stack object to el[i] which is not possible. Its obvious that you got error.
So your code should be like following :
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i];
}
}
}
I'm not a Java developer but I'm guessing if you want to put a value on the stack you'll need something like:
stack.push(el[i]);
The reason for your error is your trying to assign the i-th Element in an Integer array, to be a Stack. This is failing because it can't cast a Stack to an integer.
Use Stack.push() method.
stack.push(el[i]);
To use a stack, you want to push() your item on top of it, and pop() it from the stack when you're ready to use it again. In your case, it seems more appropriate to inherit the stack, than to wrap it.
import java.util.Stack;
public class SortedStack extends Stack<Integer>
{
public SortedStack(Integer[] el) // Why "Sorted"? You're not sorting here...
{
for(int i = 0; i < el.length; i++)
{
this.push(el[i]); /** THE ERROR IS THIS LINE */
}
}
}
Doing this, you can use your SortedStack just like any regular stack, with the addition of adding a whole range of elements in the constructor. You might also want to implement a PushRange() method, that can be called after the object is instantiated.

Categories