Thursday, September 10, 2020

#183 Array elements are stored in contiguous locations

Array elements are stored in contiguous locations - Computer Science

ChemistryExplain daily providing Q&A content “#183 Array elements are stored in contiguous locations" in Computer science, Ba computer science, Berkeley computer science, Computer science associate degree jobs

ChemistryExplain “#183 Array elements are stored in contiguous locations" in Computer science, Ba computer science, Berkeley computer science, Computer science associate degree jobs
Get the Free Online Chemistry Q&A Questions And Answers with explain. To crack any examinations and Interview tests these Chemistry Questions And Answers are very useful. Here we have uploaded the Free Online Chemistry Questions. Here we are also given the all chemistry topic.

 ChemistryExplain team has covered all Topics related to inorganic, organic, physical chemistry, and others So, Prepare these Chemistry Questions and Answers with Explanation Pdf.

For More Chegg Questions

Free Chegg Question

Q1) Put (T) in front of the correct statement and (F) in front of the incorrect one.

We need to shift the elements when adding new one in unsorted arrays.

Array elements are stored in contiguous locations in computer memory.

Array size cannot be changed after it is created.

When declaring an array in Java, the size can be variable, int n=100; int x[]=new int [n];

The index of array in Java can be of type long.

Q2) What is the output of the following code segment:

int m[]- {3,2};

int y[]- (4,8,9,1);

y=x;

y[@]-100;

System.out.println(x[@]);

System.out.println(y[@]); 

Q3) How to copy an array to another one in Java?

Ex 1: Create a class and call it " ArrayMethods", and create each one of the following methods and test it in the main

1. Method equal (int al ], int b[ 1) which receives two integer arrays and returns true if they have the same elements in the same positions, otherwise it returns false;

2. Method sameElements(int al 7 int b[ 1) which receives two arrays of integers and returns true if the two arrays has the same elements regardless of their positions, for example if a=(2,5,6,1) and b=[1,5,2,6), the method will return true.

3. Method removeDuplicate(int x[]) which receives any array of integers, and returns an array that contains the same elements of x without duplicate, for example if x=(2,1,7,2,1) the method will return (2,1,7)

Ex2: We will create a class similar to ArrayList, we will call it mylist.

1. Create a generic class MyList that has an array of generic type, create private int variable (count) that indicates how many elements currently in the array.

2. Add no-parameter constructor that creates the array with 10 elements as the default size.

3. Add parameter constructor that creates the array with size that input as a parameter.

4. Add method size() that returns how many elements currently in the list.

5. Add method isEmpty that returns true when the list is empty, otherwise it returns true.

6. Add method add( e) (void) that adds the element e at the end of the array if it is not null. If the array is full create a new array with double size of the old one, copy the elements to the new one, and make the reference points to the new one.

7. Method clear(): void method that removes all elements in the list.

8. Method get(int i): it return the element at position i if there is an element, otherwise throws an exception.

9. Method display (void) that prints the elements currently in the list. A

10. Create Test class with main method, and create two objects of MyList, each one initially contains 3 elements: one of type Integer and the other one of type Character. Test the methods above.
Add the following methods :

11. Method set(int i, E e): void method that replaces element at position i with e if there is an element at i, otherwise it throws an exception.

12. Method contains (E e): it returns true if the element in the list, otherwise it returns false.

13. Method indexOf(E e): it returns the index of the element e in the list, otherwise it returns -1.

14. Method to Array(): it returns an array of all elements in the list.

15. Method remove( int i): it removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). It returns the removed element. If the index is out of range, it throws an exception.

Assignment

To the class MyList, add the following methods

  • add(int i, E e) which inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). if the index is out of range, throw an exception.
  • remove(E e): it removes the first occurrence of the specified element from this list, if it is present and returns true. If the list does not contain the element, it is unchanged, and returns false.

For More Chemistry Notes and Helpful Content Subscribe Our YouTube Chanel - Chemistry Explain  

Free Chegg Answer

Program code:

import java.util.*;
import java.lang.reflect.Array;

class ArrayMethods{

   // method to check if the input arrays are equal or not (equal in every aspect)
   boolean equal(int a[],int b[]){
       int aLen = a.length,bLen = b.length;
       if(aLen!=bLen)return false;
       for(int i=0;i<aLen;i++){
           if(a[i]!=b[i])return false;
       }
       return true;
   }

   // method to check if input arrays contain same elements or not
   boolean sameElements(int a[],int b[]){
       Arrays.sort(a);
       Arrays.sort(b);
       return equal(a,b);  
   }

   // method to remove duplicate elements from the input array
   Integer[] removeDuplicates(int x[]){
       Set<Integer> set1 = new LinkedHashSet<Integer>();
       int xLen = x.length;
       for(int i=0;i<xLen;i++){
           set1.add(x[i]);
       }
       Integer result[] = new Integer[set1.size()];
       set1.toArray(result);  
       return result;
   }
}

// A generic class similar to ArrayList
class myList<E>{

   // keeps count of the number of elements added to the list
   private int count;

   // generic array to store elements of the list
   private E[] a;

   // resize function useful to resize the generic array
   void resize(int size){
       E[] temp = (E[]) Array.newInstance(a.getClass().getComponentType(),
                                       2*size);
           System.arraycopy(a, 0, temp, 0, size);
           a = temp;
   }

   // no parameter constructor
   myList(){  
       count = 0;
       a = (E[]) new Object[10];
   }

   // parameterised constructor
   myList(int num){
       count = 0;
       a = (E[]) new Object[num];
   }

   // returns the number of elements added to the list
   int size(){
       return count;
   }

   // returns true if the list is empty else returns false
   boolean isEmpty(){
       if(count == 0)return true;
       return false;
   }

   // adds an element e to the list
   void add(E e){

       // if capacity reached, use resize function to double the capacity
       if(count == a.length){
           resize(a.length);
       }
       a[count] = (E)e;      
       count++;  
   }

   // remove all the elements from the list
   void clear(){
       count = 0;
   }

   // get the element at index i in the list
   E get(int i){
       if(i>=count){
           throw new IndexOutOfBoundsException("Index " + i + " is out of bounds!");
       }else{
           return a[i];
       }
   }

   // display the contents of the list
   void display(){
       if(count == 0){
           System.out.println("The list is empty :(");
           return;
       }
       for(int i=0;i<count;i++){
           System.out.print(a[i].toString()+" ");
       }
       System.out.println("");  
   }

   // set the index i of the list to the element e
   void set(int i,E e){
       if(i>=count){
           throw new IndexOutOfBoundsException("Index " + i + " is not yet set!");
       }else{
           a[i] = (E)e;
       }
   }

   // check if the list contains element e
   boolean contains(E e){
       for(int i=0;i<count;i++){
           if(a[i] == e)return true;
       }
       return false;
   }

   // returns the index of e in the list if it is found else returns -1
   int indexOf(E e){
       for(int i=0;i<count;i++){
           if(a[i] == e)return i;
       }
       return -1;
   }

   // retuns an array equivalent of the list of elements
   E[] toArray(){
       E[] result = (E[]) Array.newInstance(a.getClass().getComponentType(), count);
           System.arraycopy(a, 0, result, 0, count);
       return result;
   }


   // removes the element at index i and shifts the remaining elemnts by one position to the left
   void remove(int i){
       if(i>=count){
           throw new IndexOutOfBoundsException("Index " + i + " is out of range!");
       }else{
           E[] temp = (E[]) Array.newInstance(a.getClass().getComponentType(), a.length);
           int aItr = 0,j=0;
               while(aItr<temp.length){
               if(aItr == i){
                   // do nothing
               }else{
                   temp[j] = a[aItr];
                   j++;
               }
               aItr++;
           }
           a = temp;
           count--;
       }
   }

   

    // Assignment functions (EDITS MADE)
   void add(int i,E e){
       if(i>=count){
           throw new IndexOutOfBoundsException("Index " + i + " is out of range!");
       }else{
           boolean sizeDoubled = false;
           if(count == a.length){
               resize(a.length);
               sizeDoubled = true;
           }
           for(int j=i+1;j<a.length;j++){
               a[j] = a[j-1];
           }
           a[i] = e;
           if(sizeDoubled) a[count] = a[count-1];
           count++;
       }
   }

    // Could not use the name remove as there is already a function with this name and same number of parameters

   boolean removeEl(E e){
       for(int i=0;i<count;i++){
           if(a[i] == e){
               remove(i);
               return true;
           }
       }
       return false;
   }

}

public class chegg{
   public static void main(String[] args){

       // EX 1
       System.out.println("");
       System.out.println("EX 1");
       // Checking if the arrays a[] = {1,2,3} and b[] = {1,2,3} are equal using the ArrayMethods class and its method named equal
       int a[] = {1,2,3};
       int b[] = {1,2,3};
       ArrayMethods helper = new ArrayMethods();
       System.out.println("Arrays a[] and b[] are equal: "+helper.equal(a,b));  
  
       // Checking if the arrays x[] = {2,5,6,1} and y[] = {1,5,2,6} have same elements using the ArrayMethods class and its method named sameElements
       int x[] = {2,5,6,1};
       int y[] ={1,5,2,6};
       System.out.println("Arrays x[] and y[] have same elements: "+helper.sameElements(a,b));  
  
       // Removing duplicates using the ArrayMethods class and its method named removeDuplicates
       int z[] = {2,1,7,2,1};
       System.out.println("Removing duplicates from z[] = {2,1,7,2,1}, we get: "+Arrays.toString(helper.removeDuplicates(z)));


       // EX 2   
       System.out.println("");
       System.out.println("EX 2");
       myList<Integer> list1 = new myList(3);          
       myList<Character> list2 = new myList(3);

       // When no elements have been added, the following should output true
       System.out.print("Is list empty? ");
       System.out.println(list1.isEmpty());

       // Add 3 elements to the list, completely utilizing its capacity
       list1.add(1);
       list1.add(2);
       list1.add(3);

       // Display the contents of the list
       System.out.print("Contents of the list: ");
       list1.display();

       // Display the size of the list
       System.out.print("Size of the list: ");
       System.out.println(list1.size());      


       // Find the index of element 2
       System.out.print("The index of element 2 is: ");
       System.out.println(list1.indexOf(2));

      
       // Find the element at index 0
       System.out.print("The element at index 0 is: ");
       System.out.println(list1.get(0));

       // Set the 3rd element in the list to be 5
       list1.set(2,5);

       // Display the contents of the list after the update
       System.out.print("After updating the 3rd element: ");
       list1.display();

       // Remove the second element in the list
       list1.remove(1);

       // Display the contents of the list after the removal of the second element
       System.out.print("After the removal of the second element: ");      
       list1.display();

      // Assignment part

    

       // Insert value 3 at index 1
       list1.add(1,3);      

       // Display the contents of the list after inserting the element with value 3 at the second position
       System.out.print("After inserting the element with value 3 at the second position: ");
       list1.display();

      
       // Remove the above added element i.e. 3
       list1.removeEl(3);      

       // Display the contents of the list after removing the above added element i.e. 3
       System.out.print("After removing the above added element i.e. 3: ");
       list1.display();


   }
}

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home