Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cpp] Challenge 2 (Unreviewed) #408

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions challenge_2/cpp/rbrt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The code accept an array of any length and find the values that appear only once in the array. The complexity of the code is linear with the length of the array.
In order to obtain this result we generate an array where we stored how many time the values in the input array appear. In this way it is necessary to scan the list only once and update the values in the counters array. Once the reading of the input list is over we look for the element that appear only once, i.e. the one that has the counter == 1.
68 changes: 68 additions & 0 deletions challenge_2/cpp/rbrt/src/[C++]Challenge2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <iostream>


using namespace std;

int find_max(int x[],int n); //This function read an array and give as output the maximum element in the array

int main()
{
int n;

//we accept as input a value representing the length of the array
//and we create an array of the given size


cout<< "Please insert the array length >> ";
cin>>n;
int *x=new int[n+1];

cout<< "Please insert an array >> ";

for(int i=0;i<n;i++){
cin>>x[i];
}


//we generate an array from 1 to the maximum value present in the input array.
//Every time that a value occurs in the input array we increment it in ctrl
//To know which element occur once is sufficient to find the value in ctrl==1

int *ctrl=new int[find_max(x,n)+1];

for(int i=0;i<n;i++){
if(ctrl[x[i]]<=1)
{

ctrl[x[i]]++;
}
}
for(int i=0;i<1000;i++){
if(ctrl[i]==1)
{
cout<<"The only element occurring once is:"<<endl;
cout<<i<<endl;
}

}


return 0;
}


int find_max(int x[],int n){

int max=x[0];
int i=1;
while(i<n){
if(max<x[i])
{
max=x[i];
}
i++;
}
return(max);


};