Question

Can you help with the merge method? This method should create and return an ArrayBagcontaining one...

Can you help with the merge method? This method should create and return an ArrayBagcontaining one occurrence of any item that is found in either the called object or the parameter other. For full credit, the resulting bag should not include any duplicates. Give the new ArrayBag a maximum size that is the sum of the two bag’s maximum sizes.

import java.util.*;

/**

* An implementation of a bag data structure using an array.

*/

public class ArrayBag {

/**

   * The array used to store the items in the bag.

   */

private Object[] items;

  

/**

   * The number of items in the bag.

   */

private int numItems;

  

public static final int DEFAULT_MAX_SIZE = 50;

  

/**

   * Constructor with no parameters - creates a new, empty ArrayBag with

   * the default maximum size.

   */

public ArrayBag() {

this.items = new Object[DEFAULT_MAX_SIZE];

this.numItems = 0;

}

public int capacity() {

//return the max number of items the ArrayBag is able to hold

return items.length;

}

public boolean isEmpty() {

//should return true if the arraybag is empty, and false otherwise

return numItems == 0;

}

public boolean addAll(Object[] newItems) {

//This method should attempt to add to the called ArrayBag

//all of the items found in the array newItems that is passed as a

//parameter, and it should return a

//boolean value indicating success or failure.

//int n stores how many items are stored

int n = newItems.length;

int remain_space = this.items.length - this.numItems;

//if n > than remainspace we return false

if(n>remain_space) {

return false;

}

//add all the items in array to newItems into item[] and return true

for(int i = 0;i<newItems.length;i++) {

this.items[this.numItems] = newItems[i];

this.numItems++;

}

return true;

}

  

/**

   * A constructor that creates a new, empty ArrayBag with the specified

   * maximum size.

   */

public ArrayBag(int maxSize) {

if (maxSize <= 0) {

throw new IllegalArgumentException("maxSize must be > 0");

}

this.items = new Object[maxSize];

this.numItems = 0;

}

public ArrayBag merge(ArrayBag other) {

//This method should create and return an ArrayBag

//containing one occurrence of any item that is found in

//either the called object or the parameter other.

int n1 = numItems();

int n2 = numItems();

boolean duplicate = false;

//delcare object items

ArrayBag result = new ArrayBag(n1+n2);

if(n1<n2)

{

for(int i=0;i<n1;i++)

{

for(int j=0;j<n1;j++)

{

if(items[i] != items[j])

{

continue;

}

else

duplicate=true;

}

if(duplicate!=true)

{

  

result.add(items[i]);

}

}

  

for(int i=n1;i<n2;i++)

{

result.add(items[i]);

}

}

return result;

}

  

/**

   * numItems - accessor method that returns the number of items

   * in this ArrayBag.

   */

public int numItems() {

return this.numItems;

}

  

/**

   * add - adds the specified item to this ArrayBag. Returns true if there

   * is room to add it, and false otherwise.

   * Throws an IllegalArgumentException if the item is null.

   */

public boolean add(Object item) {

if (item == null) {

throw new IllegalArgumentException("item must be non-null");

} else if (this.numItems == this.items.length) {

return false; // no more room!

} else {

this.items[this.numItems] = item;

this.numItems++;

return true;

}

}

  

/**

   * remove - removes one occurrence of the specified item (if any)

   * from this ArrayBag. Returns true on success and false if the

   * specified item (i.e., an object equal to item) is not in this ArrayBag.

   */

public boolean remove(Object item) {

for (int i = 0; i < this.numItems; i++) {

if (this.items[i].equals(item)) {

// Shift the remaining items left by one.

for (int j = i; j < this.numItems - 1; j++) {

this.items[j] = this.items[j + 1];

}

this.items[this.numItems - 1] = null;

  

this.numItems--;

return true;

}

}

  

return false; // item not found

}

  

/**

   * contains - returns true if the specified item is in the Bag, and

   * false otherwise.

   */

public boolean contains(Object item) {

for (int i = 0; i < this.numItems; i++) {

if (this.items[i].equals(item)) {

return true;

}

}

  

return false;

}

  

/**

   * grab - returns a reference to a randomly chosen item in this ArrayBag.

   */

public Object grab() {

if (this.numItems == 0) {

throw new IllegalStateException("the bag is empty");

}

  

int whichOne = (int)(Math.random() * this.numItems);

return this.items[whichOne];

}

  

/**

   * toArray - return an array containing the current contents of the bag

   */

public Object[] toArray() {

Object[] copy = new Object[this.numItems];

  

for (int i = 0; i < this.numItems; i++) {

copy[i] = this.items[i];

}

  

return copy;

}

  

/**

   * toString - converts this ArrayBag into a string that can be printed.

   * Overrides the version of this method inherited from the Object class.

   */

public String toString() {

String str = "{";

  

for (int i = 0; i < this.numItems; i++) {

str = str + this.items[i];

if (i != this.numItems - 1) {

str += ", ";

}

}

  

str = str + "}";

return str;

}

  

/* Test the ArrayBag implementation. */

public static void main(String[] args) {

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

public ArrayBag merge(ArrayBag other) {

//This method should create and return an ArrayBag

//containing one occurrence of any item that is found in

//either the called object or the parameter other.

int n1 = this.numItems();

int n2 = other.numItems();

boolean duplicate = false;

//declare object items

ArrayBag result = new ArrayBag(n1+n2);

Object duplicates[] = new Object[n1 + n2];

int k = 0;

for(int i=0;i<n1;i++)

{

for(int j=0;j<n2;j++)

{

if(items[i] == other.items[j])

{

duplicates[k ++] = items[i];

}

}

}

for(int i=0; i<n1; i++)

{

result.add(items[i]);

}

for (int i=0; i<n2; i++) {

for (int j=0; j<k; j++) {

if (other.items[i] == duplicates[k]) {

duplicate = true;

break;

}

}

if (!duplicate) {

result.add(other.items[i]);

}

}

return result;

}

Add a comment
Know the answer?
Add Answer to:
Can you help with the merge method? This method should create and return an ArrayBagcontaining one...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In a file named LLBag.java, write a class called LLBag that implements the Bag interface using...

    In a file named LLBag.java, write a class called LLBag that implements the Bag interface using a linked list instead of an array. You may use a linked list with or without a dummy head node. Bag interface code: /* * Bag.java * * Computer Science 112, Boston University */ /* * An interface for a Bag ADT. */ public interface Bag { /*    * adds the specified item to the Bag. Returns true on success    * and...

  • Complete an Array-Based implementation of the ADT List including a main method and show that the...

    Complete an Array-Based implementation of the ADT List including a main method and show that the ADT List works. Draw a class diagram of the ADT List __________________________________________ public interface IntegerListInterface{ public boolean isEmpty(); //Determines whether a list is empty. //Precondition: None. //Postcondition: Returns true if the list is empty, //otherwise returns false. //Throws: None. public int size(); // Determines the length of a list. // Precondition: None. // Postcondition: Returns the number of items in this IntegerList. //Throws: None....

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur...

    instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur less than N times . The method returns the number of copies removed. For example, if B = {Bob, Joe, Bob, Ned, Bob, Ned, Kim}, then calling bagScaler(B, 3) removes Joe, Ned, and Kim making B = {Bob, Bob, Bob}, and returns 4 because it removed 2 copies of Ned, one of Joe, and one of Kim. Note: There's no iterator, but there is...

  • This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and...

    This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and unorderedArrayList templates that are attached. Create a header file for your unorderedSet template and add it to the project. An implementation file will not be needed since the the new class will be a template. Override the definitions of insertAt, insertEnd, and replaceAt in the unorderedSet template definition. Implement the template member functions so that all they do is verify that the...

  • Write a method for the Queue class in the queue.java program (Listing 4.4) that displays the...

    Write a method for the Queue class in the queue.java program (Listing 4.4) that displays the contents of the queue. Note that this does not mean simply displaying the contents of the underlying array. You should show the queue contents from the first item inserted to the last, without indicating to the viewer whether the sequence is broken by wrapping around the end of the array. Be careful that one item and no items display properly, no matter where front...

  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • To the HighArray class in the highArray.java, add a method called getMax() that returns the value...

    To the HighArray class in the highArray.java, add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty. Add some code in main() to exercise this method. You can assume all the keys are positive numbers. // highArray.java class HighArray { private long[] a; private int nElems;    public HighArray(int max)    { a = new long[max];    nElems = 0; } public boolean find(long searchKey) { int...

  • I am unsure how to add the following methods onto this code?? please help - rowValuesIncrease(int[][]...

    I am unsure how to add the following methods onto this code?? please help - rowValuesIncrease(int[][] t) A method that returns true if from left to right in any row, the integers are increasing, otherwise false. - columnValuesIncrease(int[][] t) A method that returns true if from top to bottom in any column, the integers are increasing, otherwise false. - isSetOf1toN(int[][] t) A method that returns true if the set of integers used is {1, 2, . . . , n}...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT