How to make a function that remove duplicates from an passed array - c++

It's my first year learning the C++ language. I want to make a function that removes duplicates from a passed array. I tried to doing it with many different kinds of logic, but sadly I have failed on all of them. I hope someone can help me.
Here is my code:
using namespace std;
#include <iostream>
void RemoveDuplicates(int * array,int n,int *&arrayb)
{
int x=0;
int y=0;
for (int i=0;i<n;i++)
{
y++;
if (array[x]!=array[y])
{
arrayb[x]=array[x];
x++;
y++;
}
else
{
arrayb[x]=array[x];
x++;
y++;
break;
}
}
}
int main()
{
int n;
cin >> n;
int * array = new int [n];
int * arrayb = new int [n];
int i=0;
for (i=0;i<n;i++)
{
cin>>array[i];
}
RemoveDuplicates(array,n,arrayb);
for (int i=0;i<n;i++)
{
cout << arrayb[i] <<" ";
}
system("pause");
}

My two cents on this, I had this piece of code in my repo
void remove_duplicates(int arr[], int &a_size) {
for (int i = 0; i < a_size; i++) {
for (int j = i + 1; j < a_size;j++) {
if (arr[i] == arr[j]) {
for (int k = j; k < a_size; k++) {
arr[k] = arr[k + 1];
}
a_size--;
j--;
}
}
}
}

Related

I want to print the following pattern

1
3 2
6 5 4
10 9 8 7
I want to print the following pattern. I have tried very hard but couldn't make the code for it. I have tried everything which came up to my mind.
#include<iostream>
using namespace std;
int main() {
int i, j, n;
cin >> n;
int k = 0;
for (i = 1;i <= n; i++) {
for (j = 1; j <= i; j++) {
k++;
printf("%d ", k);
}
printf("\n");
}
}
the other code which i tried is this.
#include<iostream>
using namespace std;
int main() {
int i, j, n;
cin >> n;
int k = 0;
for (i = 1; i <= n; i++) {
for (j = i; j >= 1; j--) {
k++;
printf("%d ",j);
}
printf("\n");
}
}
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int previousRow = 0;
for(int row = 1; row <= 4; row++)
{
int rowTracker = row;
for(int col = 0; col < row; col++)
{
cout<<rowTracker - col + previousRow<<" ";
}
previousRow += row;
cout<<endl;
}
return 0;
}
#include<iostream>
void printPattern(unsigned numlevels)
{
unsigned last_num = 1;
for(unsigned i = 0; i < numlevels; ++i)
{
unsigned next_num = i + last_num;
for(unsigned j = next_num; j >= last_num; --j)
{
std::cout << j << ' ';
}
std::cout << '\n';
last_num = next_num + 1;
}
}
int main()
{
unsigned n;
std::cin >> n;
printPattern(n);
return 0;
}
You may also use a stack to implement this. Here is a working answer:
#include <iostream>
#include <stack>
using namespace std;
int main() {
int i, j, n;
stack<int> st;
cin >> n;
int k = 0;
for(i = 1;i <= n; i++) {
for(j = 1; j <= i; j++) {
k++;
st.push(k);
}
while(!st.empty()){
printf("%d ", st.top());
st.pop();
}
printf("\n");
}
}
Hope it helps!
Before reading the code blow, you should really try to do it yourself. This problem is obviously for practice and to develop the programming muscle. Just getting the answer is not going to help.
The issue with your code is that for each row, the range you want to print is not being determined correctly. You should first find the range and then print the numbers. Ther can be multiple approaches to it. Below is one of them.
for(i=1;i<=n;i++){
int max = i*(i+1)/2;
int min = i*(i-1)/2 + 1;
for(j=max;j>=min;j--){
printf("%d ",j);
}
printf("\n");
}
Here is a simple method
int main(int argc, char* argv[])
{
int n = 4; // suppose print 4 lines
for (int i = 1; i <= n; ++i)
{
int i0 = (i + 1) * i / 2; // first number of line i
for (int j = 0; j < i; j++)
cout << i0 - j << " ";
cout << endl;
}
return 0;
}
thanx everyone for your responses. I was able to do it on my own. Below is what I did. if there is any correction let me know
#include<iostream>
using namespace std;
int main(){
int i,j,n,temp;
cin>>n;
int k=0;
for(i=1;i<=n;i++){
k=k+i,temp=k;
for(j=1;j<=i;j++){
cout<<temp<<+" ";
temp--;
}
cout<<("\n");
}
}

How to correctly use pointers in code

For the following code, how can I find [A^-1] using pointers(equation for [A^-1]= 1/ det (A)? I am not sure whether pointers are used in the arithmetic or if they are used to call a value. Explaining what a pointer would be nice as I'm not exactly sure what they even do. I have most of the code written, except for this one part, so any help is much appreciated. Thanks in advance.
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <bits/stdc++.h>
#define N 3
using namespace std;
template<class T>
void display(T A[N][N])
{
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << A[i][j] << "\t\t";
cout << endl;
}
}
template<class T>
void display(T A[N])
{
for (int i=0; i<N; i++)
{
cout << A[i]<< "\n";
}
}
void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = A[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinant(int A[N][N], int n)
{
int D = 0;
if (n == 1)
return A[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(A, temp, 0, f, n);
D += sign * A[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return D;
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
getCofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
bool inverse(int A[N][N]){
int det = determinant(A, N);
if (det == 0){
cout << "Singular matrix, can't find its inverse";
return false;
}
return true;
}
void computeInverse(int A[N][N], float inverse[N][N]){
int det = determinant(A, N);
int adj[N][N];
adjoint(A, adj);
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
inverse[i][j] = adj[i][j]/float(det);
cout<<"\nThe Inverse of the Matrix A is:"<<endl;
display(inverse);
}
int main()
{
system("cls");
int A[N][N] = {{-1, 4, -2}, {-3, -2, +1}, {+2, -5, +3}};
char X[N];
int B[N];
float inv[N][N];
cout<<"\nEnter a 3*3 Matrix A"<<endl;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin>>A[i][j];
}
}
cout<<"\nEnter variables x, y, z for Matrix X"<<endl;
for(int i=0;i<N;i++){
cin>>X[i];
}
if (X[0] == 'x' && X[1] == 'y' && X[2] == 'z')
cout<<"\nMatrix X is Valid"<<endl;
else{
cout<<"\nMatrix X is Invalid"<<endl;
return -1;
}
cout<<"\nEnter values for Matrix B"<<endl;
for(int i=0; i<N; i++)
cin>>B[i];
cout<<"\nMatrix A is:------->\n";
display(A);
cout<<"\nMatrix X is:------->\n";
display(X);
cout<<"\nMatrix B is:------->\n";
display(B);
bool isInverseExist = inverse(A);
if (isInverseExist)
computeInverse(A, inv);
return 0;
}
Okay, Here is a simple pointer example using a char array. This can work with other data types as well. Don't remember where I read it; Think of a pointer as an empty bottle.
lets break this down in English first then I'll share a simple example that can be compiled. Imagine that you have 10 m&m's sitting in front of you on a table.
These m&m's represent a character array that we will call char mm[10]; Assume that this array is filled with chars that represent the color of all 10 of the m&m's
Now, we don't want to leave our candy's on the table all day so we will store all ten of the m&m's in a special jar specifically made for the m&m's. this jar will be called char* mm_ptr;
So now we are left with a table of m&m's and a jar sitting next to the pile. The next step is to fill the jar with the m&m's and you do it like this: mm_ptr = mm;
You now have a "jar full of m&m's". This allows you to access the m&m's directly from the jar!
Here is a Working example of of putting m&m's into a jar:
#include <iostream>
//using namespace std;
int main(){//The main function is our table
char mm[10]; //Our pile of m&m's
for(int i=0; i<10; i++){
if(i < 5){
mm[i] = 'b'; //Lets say that half of the m&m's are blue
}else{
mm[i] = 'r'; //and that the other half is red
}
}
char* mm_ptr; //This is our bottle that we will
//use to store our m&m's
mm_ptr = mm; //this is us storing the m&m's in the jar!
for(int i=0; i<10; i++){//Lets dump those candies back onto the table!
std::cout<<mm_ptr[i]<<std::endl;
}
return 0;
}
A correctly initialized pointer will work almost exactly like a normal array

Selection Sort in c++

i'm trying to understand selection sort from this video:
https://www.youtube.com/watch?v=79AB11J5BqU
this is my current code :
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
Am i doing the selection sort just like the video?
or am i instead doing buble sort ?
Thanks
In selection sort you find a minimal (or maximal) element and put it to top (bottom), then repeat it again for the rest of list.
It would be a selection sort, but you don't need to do swap every number you compare to find the smallest one. Store smallest number index in each internal loop and do one swap at the end of it.
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}

Sorting Matrix with qsort function C++

Hello guys I need to know what should I pass to qsort function to make this work?
Everything else must stay as it is except arguments of qsort function.
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
void printMatrix(int **matrix, int n){
for(int i = 0; i<n; i++){
for(int j =0 ; j < n; j++)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
}
void initMatrix(int **matrix, int n){
for(int i = 0; i<n; i++){
for(int j =0 ; j < n; j++){
matrix[i][j] = rand()%10;
}
}
}
int compar(const void *a, const void *b){
int ia = *((int*)a);
int ib = *((int*)b);
return ia-ib;
}
void deleteMatrix(int **matrix){
delete [] matrix;
}
int main()
{
cout<<"How many rows and cols?"<<endl;
int n;
cin>>n;
int **matrix;
matrix = new int* [n];
for(int j = 0; j < n; j++)
matrix[j] = new int[n];
initMatrix(matrix,n);
printMatrix(matrix,n);
cout<<"Sorted matrix:"<<endl;
qsort(matrix,n*n,sizeof(int),compar); //<-----------
printMatrix(matrix,n);
deleteMatrix(matrix);
return 0;
}
P.S
There must be ** pointer on matrix.
Thanks in advance!
You would probably be better off flattening the matrix to 1 dimension and using a step variable to determine where each row would start. Then sorting is easy.
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
void printMatrix(int *matrix, int matrixsize, int rowsize) {
for (int i = 0; i < matrixsize; i+= rowsize)
{
for (int j = 0; j < rowsize; j++)
{
cout << matrix[i + j] << " ";
}
cout << endl;
}
}
void initMatrix(int *matrix, int n)
{
for (int i = 0; i < n; i++)
{
matrix[i] = rand() % 10;
}
}
void deleteMatrix(int *matrix) {
delete[] matrix;
}
int main()
{
cout << "How many rows and cols?" << endl;
int row;
cin >> row;
int matrixSize = row*row;
int *matrix = new int[matrixSize];
initMatrix(matrix, matrixSize);
printMatrix(matrix, matrixSize, row);
cout << "Sorted matrix:" << endl;
sort(matrix,matrix + matrixSize); //<-----------
printMatrix(matrix, matrixSize, row);
deleteMatrix(matrix);
return 0;
}

Using a function to remove duplicates from an array in C++

I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
void rmDup(int array[], int& size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
while (cin >> input)
{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}
rmDup(values, currentSize);
for (int k = 0; k < currentSize; k++)
{
cout << values[k];
}
return 0;
}
Thank you.
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
size--;
}
}
}
If array[0] and array[1] are equal, array[0-1] = array[0], meaning that array[-1] = array[0]. You are not supposed to access array[-1].
I wouldn't make it even possible to create duplicates:
int main()
{
const int CAPACITY = 100;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
std::set<int> myInts;
int input;
while (std::cin >> input && input != 'q' && myInts.size() <= CAPACITY) //note: 113 stops the loop, too!
myInts.insert(input);
std::cout << "Count: " << myInts.size();
}
And do yourself a favour and don't use raw arrays. Check out the STL.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
vector<int> vec = {1,1,2,3,3,4,4,5,6,6};
auto it = vec.begin();
while(it != vec.end())
{
it = adjacent_find(vec.begin(),vec.end());
if(it != vec.end())
vec.erase(it);
continue;
}
for_each(vec.begin(),vec.end(),[](const int elem){cout << elem;});
return 0;
}
This code compiles with C++11.
#include<iostream>
#include<stdio.h>
using namespace std;
int arr[10];
int n;
void RemoveDuplicates(int arr[]);
void Print(int arr[]);
int main()
{
cout<<"enter size of an array"<<endl;
cin>>n;
cout<<"enter array elements:-"<<endl;
for(int i=0;i<n ;i++)
{
cin>>arr[i];
}
RemoveDuplicates(arr);
Print(arr);
}
void RemoveDuplicates(int arr[])
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
n--;
}
else
j++;
}
}
}
void Print(int arr[])
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}