Question

JAVA ProgrammingMagicSet. Write a class that represents a set. Recall that a set has the following properties it does not contain duplicates and order is not important. If you are unable to make a class that can use any type (generics), make your set handle whole numbers. You must implement your set using an array. The amount of storage used should grow and shrink as needed: it should be halved if the array is 25% full and doubled when full. Your set should support the following operations: a. b. c. d. e. Add a value Does the set contain a value Delete a value Union: return a new set containing all your values and another set toString Here is a UML diagram for a MagicSet that only handles whole numbers. program to test your class. Write a driver -set:intll +MagicSet() +MagicSet(other:MagicSet) +add(value:int):void +contains(target:int):Boolean +delete (value:int):Boolean +union(other:MagicSet):MagicSet +toStringl):String

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

class MagicSet

{

                int size;

                int[] arr;

               

                MagicSet()

                {

                                size = 0;

                                arr = new int[1];

                }

               

                MagicSet(MagicSet ob)

                {

                                this.size = ob.size;

                                arr = new int[ob.arr.length];

                               

                                int i;

                                for(i = 0; i < ob.arr.length; i++)

                                                this.arr[i] = ob.arr[i];

                }

               

                public boolean contains(int val)

                {

                                int i;

                                for(i = 0; i < size; i++)

                                                if(arr[i] == val)

                                                                return true;

                                return false;

                }

               

                public void add(int val)

                {

                                if(contains(val))

                                                System.out.println(val + " is already present in the Set");

                                else

                                {

                                                if(arr.length == size)

                                                {

                                                                // create a new temporary array

                                                                int[] new_arr = new int[2 * size];

                                                                int i;

                                                               

                                                                // copy element of arr to temporary array

                                                                for(i = 0; i < size; i++)

                                                                                new_arr[i] = arr[i];

                                                               

                                                                //add new value to array

                                                                new_arr[i] = val;

                                                               

                                                                // update array

                                                                arr = new_arr;

                                                }

                                                else

                                                                arr[size] = val;

                                               

                                                size++;

                                }

                }

               

                public int getIndex(int val)

                {

                                int i;

                                for(i = 0; i < size; i++)

                                                if(arr[i] == val)

                                                                return i;

                                return -1;

                }

               

                public boolean delete(int val)

                {

                                // get index of val

                                int index = getIndex(val);

                               

                                // if element is not present in the set

                                if(index == -1)

                                                return false;

                               

                                // if element to be deleted is the last element

                                if(index == size - 1)

                                {

                                                // decrease the size of the set

                                                size--;

                                                if(4 * size <= arr.length)

                                                                reduceSize();

                                                return true;

                                }

                               

                                int i;

                                // shift all elements after val one position left

                                for(i = index + 1; i < size; i++)

                                                arr[i - 1] = arr[i];

                               

                                // decrease size of set

                                size--;

                               

                                if(4 * size <= arr.length)

                                                reduceSize();

                               

                                return true;

                }

               

                public void reduceSize()

                {

                                int len = arr.length/2;

                                int[] new_arr = new int[len];

                                int i;

                               

                                // copy element of arr to temporary array

                                for(i = 0; i < size; i++)

                                                new_arr[i] = arr[i];

                               

                                // update array

                                arr = new_arr;

                }

               

                public MagicSet union(MagicSet ob)

                {

                                // create new MagicSet object

                                MagicSet ans = new MagicSet();

                               

                                ans.size = this.size + ob.size;

                               

                                ans.arr = new int[ans.size];

                               

                                int i;

                               

                                // copy elements of current object

                                for(i = 0; i < this.size; i++)

                                                ans.arr[i] = this.arr[i];

                               

                                // copy elements of object ob

                                for(i = 0; i < ob.size; i++)

                                                ans.arr[i + this.size] = ob.arr[i];

                               

                                return ans;

                }

               

                public String toString()

                {

                                String ans = "";

                                int i;

                               

                                ans += "Size of Set : " + size + "\nContents of set are ...\n";

                               

                                for(i = 0; i < size; i++)

                                                ans += String.valueOf(arr[i] + "\n");

                               

                                return ans;

                }

               

                public static void main(String[] args)

                {

                                MagicSet ob1 = new MagicSet();

                               

                                //add elements to ob1

                                ob1.add(1);

                                ob1.add(2);

                                ob1.add(5);

                                ob1.add(4);

                                ob1.add(21);

                                ob1.add(14);

                               

                                System.out.println(ob1);

                               

                                // try to add already present object

                                ob1.add(4);

                               

                                if(ob1.delete(21))

                                                System.out.println("\n21 deleted");

                                else

                                                System.out.println("\n21 not present in the Set of not able to delete it");

                               

                                ob1.delete(1);

                                ob1.delete(5);

                                ob1.delete(14);

                                ob1.delete(21);

                                ob1.delete(4);

                               

                                System.out.println("\nAfter deleting 1, 5, 14, 21 ...\n" + ob1);

                               

                               

                                MagicSet ob2 = new MagicSet();

                               

                                //add elements to ob1

                                ob2.add(124);

                                ob2.add(24);

                                ob2.add(52);

                                ob2.add(40);

                               

                                System.out.println("\nFor ob2 ...\n" + ob2);

                               

                                MagicSet ob3 = ob1.union(ob2);

                               

                                System.out.println("\nFor ob3(union of ob1 and ob2) ...\n" + ob3);

                }

}

Sample Output :

C:AUsers\userDesktop javac MagicSet.java C:AUsers\userDesktop java MagicSet Size of Set : 6 Contents of set are 4 21 14 4 is

Add a comment
Know the answer?
Add Answer to:
JAVA Programming MagicSet. Write a class that represents a set. Recall that a set has the...
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
  • Java programming The purpose of this problem is to practice using a generic Urn class. NOTE:...

    Java programming The purpose of this problem is to practice using a generic Urn class. NOTE: Refer to the code for the ArrayStack class from Chapter 12. Use that code as a starting point to create the Urn class, modifying it to remove the methods in the ArrayStack class (push, pop, etc) then add the methods described below. Also change the variable names to reflect the new class. For example the array name should NOT be stack, instead it should...

  • Goals: Write your own class. Instantiate an object of your class. Interact with the object's public...

    Goals: Write your own class. Instantiate an object of your class. Interact with the object's public interface. Requirements: Design a class that has an array of floating-point numbers. The constructor should accept an integer argument and dynamically allocate the array to hold that many numbers. The destructor should free the memory held by the array. In addition, there should be member functions to perform the following operations: Store a number in any element of the array - accepts an integer...

  • JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

    JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class. Print out the results after testing each of the methods in both of the classes and solving a simple problem with them. Task 1 – ArrayList Class Create an ArrayList class. This is a class that uses an internal array, but manipulates the array so that the array can be dynamically changed. This class should contain a default and overloaded constructor, where the default...

  • In Java programming language. For this assignment, you must write a class Rectangle and a tester...

    In Java programming language. For this assignment, you must write a class Rectangle and a tester RectangleTest. The Rectangle class should have only the following public methods (you can add other non-public methods): Write a constructor that creates a rectangle using the x, y coordinates of its lower left corner, its width and its height in that order. Creating a rectangle with non-positive width or height should not be allowed, although x and y are allowed to be negative. Write...

  • Following the instruction This is c++ programming Lab Tasks: 1. Define a dynamic array class in...

    Following the instruction This is c++ programming Lab Tasks: 1. Define a dynamic array class in DynamicArray .h and DynamicArray.cpp files, according to the following UML class diagram: DynamicArray - int arrySize; - int currentSize; int* arrayPtr; + DynamicArray(int size) // Explicit constructor, which you define- allocate space in dynamic memory for an integer array of the given size. + DynamicArray) // Explicit destructor, which you define-de allocate dynamic memory. + additem(int item): bool // Set the value of the...

  • Write a program in C++ that uses a class template to create a set of items....

    Write a program in C++ that uses a class template to create a set of items. . . The Problem Write program that uses a class template to create a set of items. The program should: 1. add items to the set (there shouldn't be any duplicates) Example: if your codes is adding three integers, 10, 5, 10, then your program will add only two values 10 and 5 Hint: Use vectors and vector functions to store the set of...

  • Java Code Help! Code this: Calculate statistics. Write a class called Statistics that can calculate a...

    Java Code Help! Code this: Calculate statistics. Write a class called Statistics that can calculate a number of properties about an array of doubles. There should be separate static methods to calculate the min, the max, the mean, the median, the standard deviation (make sure to make use of your mean method to implement this), and the mode. For the mode, you can assume that the data set is not multimodal. This class should not have a main method. Write...

  • Please help me with this code. Thank you Implement the following Java class: Vehicle Class should...

    Please help me with this code. Thank you Implement the following Java class: Vehicle Class should contain next instance variables: Integer numberOfWheels; Double engineCapacity; Boolean isElectric, String manufacturer; Array of integers productionYears; Supply your class with: Default constructor (which sets all variables to their respective default values) Constructor which accepts all the variables All the appropriate getters and setters (you may skip comments for this methods. Also, make sure that for engineCapacity setter method you check first if the vehicle...

  • Java programming 1. (Triangle class) Design a new Triangle class that extends the abstract GeometricObject class....

    Java programming 1. (Triangle class) Design a new Triangle class that extends the abstract GeometricObject class. Draw the UML diagram for the classes Triangle and GeometricObject and then implement the Triangle class. Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input....

  • Write code in Java programming language. The ShoppingCart class will be composed with an array of...

    Write code in Java programming language. The ShoppingCart class will be composed with an array of Item objects. You do not need to implement the Item class for this question, only use it. Item has a getPrice() method that returns a float and a one-argument constructor that takes a float that specifies the price. The ShoppingCart class should have: Constructors: A no-argument and a single argument that takes an array of Items. Fields: • Items: an array of Item objects...

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
ADVERTISEMENT