Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
arpansahu authored Apr 5, 2020
0 parents commit f9b89e1
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

template<size_t n>
int majorityElement(int (&A)[n])
{
unordered_map<int, int> map;
int max = 0;
int element ;
for (int i = 0; i < n; i++) {
map[A[i]]++;
if (max < map[A[i]]){max = map[A[i]];element = A[i];}
}
if(max > n / 2) cout << "Majority is present and its held by : " << element;
else cout <<" No majority";

}

// main function
int main()
{
int A[] = { 2, 8, 7, 2, 2, 5, 2, 3, 1, 2, 2 };

majorityElement(A);

return 0;
}
19 changes: 19 additions & 0 deletions Find pair with given sum in an array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <iostream>
#include <unordered_map>
using namespace std;
template <size_t n>
void findPair(int (&arr)[n], int sum){
unordered_map <int,int> map;
for (int i = 0; i < n; ++i) {
if(map.find(sum - arr[i]) != map.end()){ cout << "Pairs Found They are at index: " << map[sum-arr[i]] <<" and " << i <<" ( " << arr[map[sum-arr[i]]] <<" , " << arr[i] <<" )" <<"\n"; return;}

map[arr[i]] = i;
}
cout << "Not found";
}
int main(){
int arr[] = { 8, 7, 2, 5, 3, 1};
int sum = 10;
findPair(arr, sum);
return 0;
}
29 changes: 29 additions & 0 deletions Shuffle a given array of elements (Fisher–Yates shuffle).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <stdio.h>
#include <time.h>
#include <random>
void swap(int A[], int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}

template <size_t n>
void shuffle(int (&A)[n])
{
for (int i = n-1; i >= 1; i--) {
int j = rand() % i+1;
printf("%d ",j);
swap(A,i,j);
}
}

// main function
int main(void)
{
int A[] = { 1, 2, 3, 4, 5, 6 };
srand(time(NULL));
shuffle(A);
printf("\n");
for (int i = 0; i < (*(&A+1) - A); i++) printf("%d ", A[i]);
return 0;
}
26 changes: 26 additions & 0 deletions determine any sub array with sum 0.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <iostream>
#include <unordered_set>
using namespace std;

template<size_t n>
int findAnySubArrayWithSum0(int (&arr)[n])
{
unordered_set<int> sumSet;
int sum = 0;
for (int i = 0 ; i < n ; i++)
{
sum += arr[i];
if (sum == 0 || sumSet.find(sum) != sumSet.end()) return 1;
sumSet.insert(sum);
}
return 0;
}

// main function
int main()
{
int arr[] = { 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 };
if(findAnySubArrayWithSum0(arr)) cout << "Yes";
else cout << "No";
return 0;
}

0 comments on commit f9b89e1

Please sign in to comment.