Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Project 1 Java, C++

The document defines a generic array class for Java and C++ that implements common array methods like isEmpty(), lengthOfArray(), isEqual(), insertAt(), filter(), removeElement(), removeDuplicateElements(), printArray(), selectionSort(), search(), shuffleArray(), and getSliceOfArray(). The class uses generic types, supports basic operations on the array, and has complexity analyses provided for each method.

Uploaded by

sana fiaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Project 1 Java, C++

The document defines a generic array class for Java and C++ that implements common array methods like isEmpty(), lengthOfArray(), isEqual(), insertAt(), filter(), removeElement(), removeDuplicateElements(), printArray(), selectionSort(), search(), shuffleArray(), and getSliceOfArray(). The class uses generic types, supports basic operations on the array, and has complexity analyses provided for each method.

Uploaded by

sana fiaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Create a generic array class that defines all the methods for

array given in the data structure basics powerpoint


presentation
(Java)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication5;

import java.util.Random;

/**
*
* @author sehar
* @param <E>
*/
public class Array<E>{
private final Object[] obj_array;
public final int length;
//class constructer
public Array(int length){
obj_array=new Object [length]; //instantiates a new object array of specified length
this.length = length;
}
//generic class methods
public boolean isEmpty (){
return length == 0; //if length is zero it returns true otherwise false
}

Runtime
O(1)
public int LengthofArray(E arr[]){
int flag=0,i=0;
while(arr[i]!=null)
{
flag++;
i++;
}
return flag;
}

Runtime
O(1)

public boolean isEqual (E arr[] , E arr2[] ){


int c= 0;
if (arr.length== arr2.length) //if both array are equals than we check the elements of
array other
{
for (int i=0; i< arr.length; i++)
{
if (arr[i]== arr2[i]) //Checking each element
c=0;
else{
c=1;
break; //terminates the loop
}
}
return c==0;
}
else
return false;
}

Runtime
O(n)

public E[] insertAt (E arr[] , int pos, int n, E x){


E[] newarr = (E[]) new Object[n+1]; //creating new array with size n+1
for(int i=0; i<n+1; i++ )
{
if (i<pos-1) //if the iterator is before the required position it copies the
previous array to the new one
newarr[i]=arr[i];
else if (i== pos-1)
newarr[i]=x;
else

newarr[i]=arr[i-1];
}
return newarr;
}

Runtime
O(n+1)

public boolean filter (E a[], E value)


//filters the required value from the array
{
int c=0;
for (int i = 0; i <a.length; i++){
if (a[i]==value)
{
c=0;
break;

}
else
c=1;

}
return c==0;

Runtime
O(n)

public E[] removeTheElement(E arr[],int index)


{

// If the array is empty


// or the index is not in array range
// return the original array
if (arr == null
|| index < 0
|| index >= arr.length) {

return arr;
}

// Create another array of size one less


E[] anotherArray = (E[]) new Object[arr.length-1];

// Copy the elements except the index


// from original array to the other array
for (int i = 0, k = 0; i < arr.length; i++) {

// if the index is
// the removal element index
if (i == index) {
continue;
}

// if the index is not


// the removal element index
anotherArray[k++] = arr[i];
}

// return the resultant array


return anotherArray;
}

Runtime
O(n)

public int removeDuplicateElements(E arr[], int n){


if (n==0 || n==1){
return n;
}
E[] temp = (E[]) new Object[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

Runtime
O(n²)

public static < E > void printArray( E[] inputArray ) {


// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

Runtime
O(n)
public void selectionSort(E[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j] > arr[j+1])
{
E temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

Runtime
O(n²)

public boolean search(E arr[], E num) {


int cnt=0;int pos=0;
for(int i=0; i<arr.length; i++)
{
if(arr[i]==num)
{
cnt=1;
pos=i+1;
break;
}
}
if(cnt==0)
{
System.out.println("Element not found!!");
}
else
{
System.out.println("Element found at "+ pos);
}
return false;
}

Runtime
O(n)

public static void shuffleArray(int[] array)


{
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
if (index != i)
{
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}

Runtime
O(n)
// Function to get slice of a primitive array in Java
public E[] getSliceOfArray(E[] arr, int start, int end)
{

// Get the slice of the Array


E[] slice = (E[]) new Object[end - start];

// Copy elements of arr to slice


for (int i = 0; i < slice.length; i++) {
slice[i] = arr[start + i];
}

// return the slice


return slice;
}
}

Runtime
O(n)

(C++)

#include <vector>
#include <iostream>
#include <any>
using namespace std;
template<E>
class Array
{
public:
const std::vector<std::any> obj_array;
public:
const int length;
//class constructer
Array(int length) : obj_array(std::vector<std::any>(length)) / *
instantiates a new object array of specified length */
{
length(length);
}
//generic class methods
virtual bool isEmpty()
{
return length == 0; //if length is zero it returns true otherwise false
}
virtual int LengthofArray(std::vector<E> &arr)
{
int flag = 0, i = 0;
while (arr[i] != nullptr)
{
flag++;
i++;
}
return flag;
}
virtual bool isEqual(std::vector<E> &arr, std::vector<E> &arr2)
{
int c = 0;
if (arr.size() == arr2.size()) //if both array are equals than we check
the elements of array other
{
for (int i = 0; i < arr.size(); i++)
{
if (arr[i] == arr2[i]) //Checking each element
{
c = 0;
}
else
{
c = 1;
break; //terminates the loop
}
}
return c == 0;
}
else
{
return false;
}
}
virtual std::vector<E> insertAt(std::vector<E> &arr, int pos, int n, E x)
{
std::vector<E> newarr =
static_cast<std::vector<E>>(std::vector<std::any>(n + 1)); //creating new array
with size n+1
for (int i = 0; i < n + 1; i++)
{
if (i < pos - 1) //if the iterator is before the required position
it copies the previous array to the new one
{
newarr[i] = arr[i];
}
else if (i == pos - 1)
{
newarr[i] = x;
}
else
{

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


}
}
return newarr;
}
virtual bool filter(std::vector<E> &a, E value)
{
//filters the required value from the array
int c = 0;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == value)
{
c = 0;
break;

}
else
{
c = 1;
}

}
return c == 0;

}
virtual std::vector<E> removeTheElement(std::vector<E> &arr, int index)
{

// If the array is empty


// or the index is not in array range
// return the original array
if (arr.empty() || index < 0 || index >= arr.size())
{

return arr;
}

// Create another array of size one less


std::vector<E> anotherArray =
static_cast<std::vector<E>>(std::vector<std::any>(arr.size() - 1));

// Copy the elements except the index


// from original array to the other array
for (int i = 0, k = 0; i < arr.size(); i++)
{

// if the index is
// the removal element index
if (i == index)
{
continue;
}

// if the index is not


// the removal element index
anotherArray[k++] = arr[i];
}

// return the resultant array


return anotherArray;
}

virtual int removeDuplicateElements(std::vector<E> &arr, int n)


{
if (n == 0 || n == 1)
{
return n;
}
std::vector<E> temp =
static_cast<std::vector<E>>(std::vector<std::any>(n));
int j = 0;
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[n - 1];
// Changing original array
for (int i = 0; i < j; i++)
{
arr[i] = temp[i];
}
return j;
}

static void printArray(std::vector<E> &inputArray)


{
// Display array elements
for (auto element : inputArray)
{
printf(L"%s ", element);
}
std::wcout << std::endl;
}

virtual void selectionSort(std::vector<E> &arr)


{
int n = arr.size();
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
E temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
virtual bool search(std::vector<E> &arr, E num)
{
int cnt = 0;
int pos = 0;
for (int i = 0; i < arr.size(); i++)
{
if (arr[i] == num)
{
cnt = 1;
pos = i + 1;
break;
}
}
if (cnt == 0)
{
cout <<"Element not found!!" <<endl;
}
else
{
cout << "Element found at " << pos <<endl;
}
return false;
}
public:
static void shuffleArray(std::vector<int> &array);
// Function to get slice of a primitive array in Java
virtual std::vector<E*> getSliceOfArray(std::vector<E*> &arr, int start,
int end);
#include "snippet.h"

void <Array>::shuffleArray(std::vector<int> &array)


{
int index;
Random *random = new Random();
for (int i = array.size() - 1; i > 0; i--)
{
index = random->nextInt(i + 1);
if (index != i)
{
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}

delete random;
}

std::vector<E*> <Array>::getSliceOfArray(std::vector<E*> &arr, int start, int


end)
{

// Get the slice of the Array


std::vector<E*> slice =
static_cast<std::vector<E*>>(std::vector<std::any>(end - start));

// Copy elements of arr to slice


for (int i = 0; i < slice.size(); i++)
{
slice[i] = arr[start + i];
}

// return the slice


return slice;
}

Given an array A of n positive odd integers, each represented


with k = ⌈log n⌉+1 bits, write an O(n)-time method for finding
a k-bit integer not in A.
(C++)
#include<iostream>
#include<map>
#include<cmath>
using namespace std;
int main(){
int n,k;
cout<<"Enter the size of array"<<endl;
cin>>n;
int arr[n];
map<int,int>m1; //creating a map object
for(int i=0;i<n;i++){ //Input values of array from user
cout<<"enter odd element"<<endl;
cin>>arr[i];
arr[i]=log(arr[i])+1; //Taking [log n]+1 of each value
m1[arr[i]]++; //mapping the values with the given values
}
cout<<"enter k ";
cin>>k;
if(m1.count(k)){ //returns yes if the element with key K is present in the map container.
//It returns no if the element with key K is not present in the container
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}}

(Java)
import java.util.*;

public class JavaApplication6 {

/**
* @param args the command line arguments

*/

public static void main(String[] args) {

Scanner sc= new Scanner(System.in);

int n;

int k;

System.out.print("Enter the size of array");

System.out.print("\n");

n= sc.nextInt();

int[] arr = new int[n];

TreeMap<Integer,Integer> m1 = new TreeMap<Integer,Integer>(); //creating a map object

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

{ //Input values of array from user

System.out.print("enter odd element");

System.out.print("\n");

arr[i]= sc.nextInt();

arr[i] = (int) (Math.log(arr[i]) + 1); //Taking [log n]+1 of each value

m1.get(arr[i])++; //mapping the values with the given values

System.out.print("enter k ");

k = sc.nextInt();

if (m1.containsKey(k))

{ //returns yes if the element with key K is present in the map container.

//It returns no if the element with key K


is not present in the container

System.out.print("Yes");

System.out.print("\n");

else

{
System.out.print("No");

System.out.print("\n");

Runtime
O(n)

Given an array A of n arbitrary integers, write an O(n)-time


method for finding an integer that cannot be formed as the
sum of two integers in A
(C++)
#include <iostream>

using namespace std;

int getNum(int arr[] , int n){

//to find maximum number in the array and result will be 2*max+1 because maximum
achievable sum by adding two numbers in an array can be 2*max

//if max appear more than once. But at any cost, we can't make 2*max+1 using sum of two
numbers in an array

int maxNum = arr[0];

for(int = 0; i<n; i++) //single iteration so O(n) time algorithm

maxNum = max(maxNum, arr[i]);

}
return 2* maxNum + 1; //result will be 2 times max + 1

int main(){

int arr[]= {1, 2, 5, 7, 9};

int n = sizeof(arr)/ sizeof(arr[0]); // to find size of array

cout<< "Array: ";

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

cout<<arr[i]<< " ";

cout<<endl;

int result = getNum(arr, n);

cout<< "Number which can't be formed as sum of two numbers in array: "<<result <<endl;

(JAVA)
class Main{

static int getNum(int arr[], int n){

//to find maximum number in the array and result will be 2*max+1 because maximum achievable
sum by adding two numbers in an array can be 2*max

//if max appear more than once. But at any cost, we can't make 2*max+1 using sum of two
numbers in an array

int maxNum = arr[0];

for(int i= 0; i<n; i++) //single iteration so O(n) time algorithm

maxNum = Math.max(maxNum, arr[i]);

return 2* maxNum + 1; //result will be 2 times max + 1

}
public static void main(String[] args) {

int arr[]= {1, 2, 5, 7, 9};

int n= arr.length; //to find the size of array

System.out.print("Array: ");

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

System.out.print(arr[i]+ "");

System.out.println("");

int result;

result = getNum(arr, n); //get the result

System.out.print("Number which can't be formed as sum of two numbers in array: " + result);

Runtime
O(n²)

Given an unsorted array a of integers and an integer k, write a


recursive algorithm for rearranging the element in a so that all the
elements less than or equal to k come before any elements larger
than k,what is the running time of your algorithm
(Java)
package javaapplication1;

import java.util.*;
public class JavaApplication1 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int k;

int arr[] = { 64, 34, 25, 12, 22, 11, 90 };

System.out.print("Type k value:");

k = sc.nextInt();

arr = addX(arr.length, arr, k);

int n = arr.length;

bubbleSort(arr, n);

System.out.println("Sorted array: ");

printArray(arr, n);

static void printArray(int arr[], int size)

int i;

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

System.out.print(arr[i] + " ");

System.out.println();

static void bubbleSort(int arr[], int n)

int i, j, temp;

boolean swapped;

for (i = 0; i < n - 1; i++)

swapped = false;
for (j = 0; j < n - i - 1; j++)

if (arr[j] > arr[j + 1])

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = true;

if (swapped == false)

break;

public static int[] addX(int n, int arr[], int x)

int i;

// create a new array of size n+1

int newarr[] = new int[n + 1];

// insert the elements from

// the old array into the new array

// insert all elements till n

// then insert x at n+1

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

newarr[i] = arr[i];
newarr[n] = x;

return newarr;

(C++)

#include "snippet.h"

void JavaApplication1::main(std::vector<std::wstring> &args)


{
Scanner *sc = new Scanner(System::in);
int k;
std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
std::wcout << L"Type k value:";
k = sc->nextInt();
arr = addX(arr.size(), arr, k);
int n = arr.size();
bubbleSort(arr, n);
std::wcout << L"Sorted array: " << std::endl;
printArray(arr, n);

delete sc;
}

void JavaApplication1::printArray(std::vector<int> &arr, int size)


{
int i;
for (i = 0; i < size; i++)
{
std::wcout << arr[i] << L" ";
}
std::wcout << std::endl;
}

void JavaApplication1::bubbleSort(std::vector<int> &arr, int n)


{
int i, j, temp;
bool swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

if (swapped == false)
{
break;
}
}
}

std::vector<int> JavaApplication1::addX(int n, std::vector<int> &arr, int x)


{
int i;

// create a new array of size n+1


std::vector<int> newarr(n + 1);

// insert the elements from


// the old array into the new array
// insert all elements till n
// then insert x at n+1
for (i = 0; i < n; i++)
{
newarr[i] = arr[i];
}

newarr[n] = x;

return newarr;
}

Runtime
O(n²)

String Functions
(Java)
public class NewClass {

//length of string

public static int getLengthOfString(String str)

{
int i=0;

try{

for(i=0;;i++)

char charAt = str.charAt(i);

catch(Exception e)

return i;

Runtime
O(1)

//from upper to lower

public void stringlower(String st){

char str[]=st.toCharArray();

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

if(str[i]>='A' && str[i]<='Z')

str[i]=(char)((int)str[i]+32);

}
}

Runtime
O(n)

//from lower to upper

public void stringUpper(String st){

char str[]=st.toCharArray();

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

if(str[i]>='a' && str[i]<='z')

str[i]=(char)((int)str[i]-32);

Runtime
O(n)

//concatenate two strings

public String stringCat(String s1, String s2){

String str;

str = s1 + s2;

return str;

Runtime
O(1)
//copy source string to destination

public void stringcopy(String source, String dest){

char[] ch = new char[source.length()];

int n=ch.length;

char[] ch2 = new char[dest.length()];

ch2=new char[n];

int i = 0;

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

ch2[i]=ch[i];

ch2[i]='\0';

Runtime
O(n)

//comparing two strings

public boolean equals(String a, String b) {

if(a.length() != b.length()) {

return false;

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

if(a.charAt(i) != b.charAt(i)) {

return false;

return true;
}

Runtime
O(n)

(C++)
#include "snippet.h"
//Checking length of String
int NewClass::getLengthOfString(const std::wstring &str)
{
int i = 0;
try
{
for (i = 0;;i++)
{
wchar_t charAt = str[i];
}

}
catch (const std::runtime_error &e)
{

}
return i;

}
//From Upper to Lower

void NewClass::stringlower(const std::wstring &st)


{
std::vector<wchar_t> str = std::vector<wchar_t>(st.begin(), st.end());
for (int i = 0;i < str.size();i++)
{
if (str[i] >= L'A' && str[i] <= L'Z')
{
str[i] = static_cast<wchar_t>(static_cast<int>(str[i]) + 32);
}
}
}

//from lower to upper


void NewClass::stringUpper(const std::wstring &st)
{
std::vector<wchar_t> str = std::vector<wchar_t>(st.begin(), st.end());
for (int i = 0;i < str.size();i++)
{
if (str[i] >= L'a' && str[i] <= L'z')
{
str[i] = static_cast<wchar_t>(static_cast<int>(str[i]) - 32);
}
}
}
//concatenate two strings
std::wstring NewClass::stringCat(const std::wstring &s1, const std::wstring &s2)
{
std::wstring str;
str = s1 + s2;
return str;
}
//copy one string to another

#include "snippet.h"

Void NewClass::stringcopy(const std::wstring &source, const std::wstring &dest)


{
std::vector<wchar_t> ch(source.length());
int n = ch.size();
std::vector<wchar_t> ch2(dest.length());
ch2 = std::vector<wchar_t>(n);
int i = 0;
for (int i = 0;i < n;i++)
{
ch2[i] = ch[i];

}
ch2[i] = L'\0';

//comparing two strings


bool NewClass::equals(const std::wstring &a, const std::wstring &b)
{
if (a.length() != b.length())
{
return false;
}
for (int i = 0;i < a.length();i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}

You might also like