I'm working on a homework assignment right now. I am supposed to set up a deque which is easy enough, but I'm also supposed to delete from the front, have the array act like a deque.
My problem is that for whatever reason it's not working. Here's the method I created to delete from the front:
public Object deleteFromFront(Object e)
{
Object[] temp = new Object[capacity];
for(int i = 1; i < size() - 1; i++){
temp[i] = A[i+1];
}
for(int i = 0; i < size() - 1; i++)
{
A[i] = temp[i];
}
A = temp;
return A;
}
The thinking is that I create a temp array in which the other array will be moved into it starting at position 1. As such, it will ignore the first one, thus starting with the second one. However, whenever I do this, it doesn't seem to be deleting the first. Can anyone tell me what I'm missing? Thanks a lot!
Your solution doesn't seem right.
What's the use of Object e?
What is A? Is it an array of Object type? Is is declared in the method?
Related
I am trying to write a searching algorithm to check one node in a linked integer list vs another node in that same list.
I think there seems to be a problem with the IF statement (data is in the list):
LinkedList<Integer> listScore = new LinkedList<Integer>();
int temp = 0;
String temp2 = "";
boolean flag = true;
while (flag){
flag = false;
for (int j = 0; j < linebr; j++){
if (listScore(j) < listScore(j+1)){
System.out.println("Testing");
}
}
I did originally try listScore[j] but I think there is something wrong with the way I have written it. Any help or explanation as to why it doesent work would be Greatly appreciated!!
Instead of listscore(j) and listscore(j+1), what you need to get values inside LinkedLists is .get(). So you should be using listscore.get(j) and listscore.get(j+1).
Im trying to make every "ADJEKTIVER" strings in the storyList array into random strings from my adjectivesList array. When I'm trying to compile, I only get the error: cannot find symbol- variable. With .length as the variable/attribute. Been searching for a solution quite a while now
ArrayList<String> storyList = new ArrayList<String>();
storyList = reader.getWordsInFile(storyFilename);
ArrayList<String> adjectivesList = new ArrayList<String>();
adjectivesList = reader.getWordsInFile(adjectivesFilename);
for (int index =0; index < storyList.length; index++)
{
storyList[index] = storyList[index].replace("ADJEKTIV", adjectivesList[random.nextInt(adjectivesList)]);
}
writer.write(adjectivesList, outputFilename);
use storyList.size() method instead of storyList.length
for (int index =0; index < storyList.size(); index++)
Arralist or List doesnt have any property named "length". use size() method instead
Arrays have a public final int property called length, that holds the number of elements in the array, arrays can't change how many elements they have in Java.
Which brings me to ArrayList having a collection that can change the number of elements it has is useful, but it's not magic(I would've liked someone to tell me this). It has an Array of type E[] I will call this internal array arr.
When you push an element to an ArrarList
public boolean add(E e) {
E[] temp = new E[this.arr.length];
for (int i = 0; i < this.arr.length; i++)
temp[i] = this.arr[i];
this.arr = new E[this.arr.length + 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return true;
}
// Removing is easy too
public E remove(int index) { // I'm just doing the first of the overloaded methods, in api
E returnValue = this.arr[index];
E[] temp = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
if (i != index) temp[i] = this.arr[i];
this.arr = new E[this.arr.length - 1];
for (int i = 0; i < this.arr.length; i++)
this.arr[i] = (i == temp.length ? e : temp[i]);
temp = null; // free temp or let it fall out of scope
return returnValue;
}
The being able to change the length forces it to be accessed in a dynamic way in Java via a method called size in this case.
public int size() {
return this.arr.length;
}
Java exists both as a standard and as an implementation, the former might be implemented such that Strings are mutable so making String have a length method makes code more compatible between the implementations of the standard, as implementations(not necessarily those of Java) have been known to deviate, so making them more compatible makes sense for the Java devs.
As for why ArrayList uses size() as the method name, while String uses length(), and Array uses length, I don't know although in my opinion(warning opinions ahead) it's not unreasonable that accessing the lengths got implemented the way they did, and the Java devs felt locked in, because changing the spec would also required changing the code in question.
public int length() {
return this.arr.length;
}
All code shown is merely for demonstration purposes, and comes as is, and is without warranty of any kind.
I have a for loop looping through each element in an arrayList performing someMethod() on them, depending on the result of that method I either want to keep or remove that element from the list. for example:
int returnResult;
for (int i=0;i<4;i++){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
}
}
My question is; if i have say 5 elements in the list and on the second iteration through the loop (so when i=1), I remove that element, when I go through the 3rd iteration will arrayList.get(2) be referencing what was actually the 4th element? i.e. does it immediately reduce the stack size?
Yes, it does. In order to get around this, you can iterate through the array in reverse.
int returnResult;
for (int i=3;i>=0;i--){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
}
}
This pops them off from the end, and doesn't affect the elements left to go through.
Replace your code with this :
int returnResult, limit = 4;
for (int i=0; i < limit; i++){
returnResult = someMethod(arrayList.get(i));
if (returnResult == -1){
arrayList.remove(i);
limit--;
}
}
I'm in dire need of help with this project. I'm trying to implement a Bag class for a programming assignment, and I'm getting hung up on the addAll(), Union(), and equals(), methods.
Edit: According to the assignment, addAll() is supposed to add all of the the objects from the second array into the first. I'm no longer getting an error when I run it, but for some reason it will not add all of the elements from the second array, it will only add the first 2. Thanks guys, this one is working perfectly now!
Edit: For Union(), I'm supposed to create a third bag that will contain all the contents of the first 2 bags. I was getting an ArrayIndexOutOfBoundsException when running this method. I've updated the code following biddulph.r and it's also working great. Thanks again!
Edit: "First attempt" And for equals(), it's supposed to check the size of the bags to make sure they are equal in size, then check to see if they contain the same numbers. So as it's written now, my equals() method will compare sizes and return the boolean value for that, but I'm unsure of how to make it compare the actual values.
import java.util.Arrays;
import javax.swing.*;
public class bag {
int maxSize = 10; //Size of the arrays
int count = 0; //Number of items stored in the array
int[] a;
int[] b;
bag c;
bag d;
public bag() {
//for(int i = 0; i < maxSize; i++){
//a[i] = (int)(1+Math.random()*100);
//}
a = new int[maxSize];
}
public String bagString() {
return Arrays.toString(a);
}
public void add(int b) {
try {
a[count] = b;
count++;
} catch (ArrayIndexOutOfBoundsException n) {
JOptionPane.showMessageDialog(null, "Array is full, element will not be added");
}
}
public void removeRandom() {
int i = (int)(1 + Math.random() * (count - 1));
a[i] = a[count - 1];
a[count - 1] = 0;
count--;
}
public void remove(int b) {
for (int i = 0; i < maxSize; i++) {
if (contains(b)) {
a[i] = a[count - 1];
}
}
}
public boolean isEmpty() {
if (count == 0) return true;
else return false;
}
public boolean contains(int b) {
int tf = 0;
for (int i = 0; i < maxSize; i++) {
if (a[i] == b) tf = 1;
}
if (tf == 1) return true;
else return false;
}
public int size() {
return count;
}
public void addAll(bag c, bag d) {
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
public void union(bag c, bag d) {
bag bigger = new bag();
for (int i = 0; i < c.size(); i++) {
bigger.add(c.a[i]);
}
for (int i = 0; count < d.size() - 1; i++) {
bigger.add(d.a[i]);
}
System.out.println(bigger.bagString());
}
public boolean equals(bag c, bag d){
if(c.size() != d.size()){
return false;
}else{
for(int i = 0; i < c.union(c, d).size(); i++){
if(c.union(c, d).contains(c.a[i]) && c.union(c, d).contains(d.a[i])){
return true;
}
}
return false;
}
}
}
I really appreciate any help you guys can give me, thanks.
EDIT: Thanks to everyone for your help, you guys are life savers.
Your problem for addAll() is here
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
You shouldn't be adding elements until your c bag becomes bigger than d, you should be adding all of d's elements to c.
for (int i = 0; i < d.size(); i++) {
c.add(d.a[i]);
}
So the part of the assignment you are having issue with is:
public void addAll(bag c, bag d){
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
which you say is supposed to add all of the the objects from the second array into the first.
If you break that down and apply it to your addAll() method, it sounds like you are supposed to be adding all of the items in bag "d" into bag "c".
Your for loop is saying start i at 0, and add 1 to it until the size of c is less than or equal to d.
What it should be saying is start i at 0, and add 1 to it until you have gone through every item in d.
That would look like this:
for (int i = 0; i < d.size(); i++){
c.add(d.a[i]);
}
i is increased every time you go through the for loop, and i will stop increasing when you have got to the size of d (the second condition). At this point you will exit the for loop. You don't have to worry about the size of c.
In fact you can probably get rid of the if (a.length >= c.size() + d.size()) line as well.
I hope my explanation helps you understand why the changes have been made to the method.
I think you have a lot of problems with the design of the class that you should address first. If you are representing the bag as a static or dynamic array then you only need one array, not 2. You also don't need two bags inside each bag as attributes, that doesn't make any sense; all you should have left is the size of the bag or count and the array to hold all the elements (which are integers in your case). Also, avoid naming parameters for functions and attributes for the class the same way. Not doing so might confuse the compiler and will require code like self.attributeName to use attributes; otherwise, the compiler assumes you're talking about the parameter.
If you make these changes, the rest should be straight-forward from here. Since it's an assignment, you should make these changes and try again because you won't learn if we provide the answers for you; you'll see it will be much easier once you structure it correctly.
P.S. it's a convention to start a class name with a capital letter. Bag and not bag
addAll
There's a couple of problems with this function as written. First is that it's confusing to the caller. The code using this method would be something like this:
Bag bag1 = ...
Bag bag2 = ...
Bag bag3 = ...
bag1.addAll(bag2, bag3)
...or perhaps bag2.addAll(bag2, bag3). The function is intended to add elements from one bag in to another bag, so why does the caller have to specify three different bags? There's only two involved. You should either make the function static, so it can be called like Bag.addAll(bag1, bag2) or (better) make it totally clear who's getting elements added by making it take a single argument bag1.addAll(bag2).
Second problem is that the function isn't implemented correctly, but I think that's because you're getting confused because you've got three bags involved instead of two. To sketch out how it should be fixed:
Bag target = ...
Bag source = ...
if (target.a.length >= target.size() + source.size()) {
for (int i = 0; i < source.a.length; i++) {
target.add(source.a[i]);
}
}
Good variable naming is your friend.
union
You haven't specified what problem you're having with your implementation, so I'm not going to simply rewrite it for you. Edit your question with the problem, and I'll help.
However, this is an excellent example of a method that should be static (a Factory method, in fact). It should be able ot be called like: Bag biggerBag = Bag.union(bag1, bag2).
EDIT after his comment regarding the .union problem
The problem with .union is that you're looping through each bag using some else's size. It boils down to, if you want add each element from source in to target, you should be only counting elements from source, as so:
bag bigger = new bag();
for (int i = 0; i <= c.size(); i++) {
bigger.add(c.a[i]);
}
note that your method does not protect against the bigger bag not being big enough. You should have a check to make sure that it is BEFORE the loops, or even better just create a big enough bag.
equals
Again, you need to show that you've tried to write it, and then ask a question specifying what you need help with. Update your question and I'll help.
Your method:
public void addAll(bag c, bag d) {
if (a.length >= c.size() + d.size()) {
for (int i = 0; c.size() <= d.size(); i++) {
c.add(d.a[i]);
}
}
}
betrays your lack of understanding of Object Oriented programming.
Remember that the method addAll() is already acting on a bag, and so you should not need to specify 2 bags in the arguments.
Calling example:
mybag.addAll(yourBag);
would demonstrate a possible usage - it would add all contents of yourBag into myBag.
I'll give you this method for free (assuming that the array 'a' contains the contents of the bag - something I'm not sure about because your variable names aren't clear):
public void addAll(Bag otherBag) {
for (int i : otherBag.a) {
add(i);
}
}
The above method will copy all contents of otherBag into this bag.
Another thing I noticed - you also have a b[] instance variable - what's that for?
You also have 2 other bag instance variables. Not sure why.
I'm implementing a queue using a circular array, and I'm kind of stuck in the resize() method implementation (when the array is full).
Inside the enqueue() method I check if the size of the array equals it's length, and get if it's full. Now, instead of throwing an exception, I'm trying to resize the array.
The thing is, I have two cases to consider
front <= rear
rear < front
Which is the best way to copy the elements of the old array into the new, larger one?
I thought it using a for-loop, like:
newArray = new Array[oldArray.length*2];
if (front <= rear) {
for (int i = front; i < rear; i++) {
newArray[i] = oldArray[i];
}
} else {
for (int i = front; i < newArray.length; i++) {
newArray[i] = oldArray[i];
}
for (int j = rear; j < front; j++) {
// i'm using the variable i, the order is maintained
newArray[i] = oldArray[j];
i++;
}
}
Then oldArray = newArray, return newArray and the resize it's done
I'm not sure of the amount of for's used to do this and I'm afraid I lose values.
Can someone tell me if there is a better way to do this?
For copying arrays with more than a handful of elements, use System.arraycopy(), since it is usually implemented as native code, e.g. Sun's VM uses hand-coded assembler.
front > rear
Since the data is contiguous, it can remain in the same place in the new array.
System.arraycopy(oldArray, front, newArray, front, front-rear);
front <= rear
The data is non-contiguous, so copy both blocks to the start of the new array.
// copy [rear to end]
System.arraycopy(oldArray, rear, newArray, 0, oldArray.length-rear);
// copy [0 to front]
System.arraycopy(oldArray, 0, newArray, oldArray.length-rear, front);
front = oldArray.length-(rear-front);
rear = 0;
Thx a lot for your answers and different solutions! :)
Although using the System.arraycopy() method is the most easy and efficient solution, I had to avoid using it and implement a solution by myself.
So, if someone want to resize() a circular array in a queue implementation without System.arraycopy(), here is my final solution:
private void resize() {
E[] aux = (E[]) new Object[Q.length * 2]; // new array
int i = 0; // use this to control new array positions
int j = f; // use this to control old array positions
boolean rearReached = false;
while (!rearReached) {
rearReached = j % Q.length == r; // is true if we've reached the rear
aux[i] = Q[j % Q.length];
i++;
j++;
}
f = 0;
r = Q.length - 1;
Q = aux;
}
As you can see, I took advantage of the "circular" thing and mapped the positions of the old array to the new array using the % operator.
The resultant array will have the double of capacity and all the elements (keeping the original order, obviously) at the beginning of the new array.
I've tested it and it worked properly. Lemme know if there is any inconvenience with that code.
Regards
Think of the blocks of array elements you want to move and where they should go in the new array. Then and use System.arraycopy to do it. You should call arraycopy once if front < rear and twice if rear < front.
If your array is full, you either have front == rear - 1, or rear == 0 and front == length -1 (or the other way around, I don't know your nomenclature). In the second case you can copy your whole array in one step, in the (more general) first case you have two blocks (0 .. front and rear .. length-1) which are to copy.