Finding the smallest positive number - c++

Question: Smallest Positive missing number
What is wrong with this code?
class Solution
{
public:
//Function to find the smallest positive number missing from the array.
int missingNumber(int arr[], int n)
{
// Your code here
sort(arr,arr+n);
int index=1;
int a;
for(int i=0;i<n;i++){
if(arr[i]>0){
if(arr[i]!=index){
a=index;
break;
}
else{
index++;
}
}
}
return index;
}
};

In every iteration your i is increasing, so this condition which you have written in your for loop:
arr[i]!=index
Here, let's say if the input array has duplicate elements, then for 2 consecutive values of i you will get the same value in arr[i]. In the first comparison, this condition will hold false, so you go to the else part and increment the index value. In the next iteration, your condition arr[i]!=index is always going to be true, as arr[i] is still the same but the index is increased. Thus your program will break from the for loop and the index value is getting returned. That is where it's failing.
So, it will always fail whenever you have duplicate positive elements in your input array. Except for the case when the largest item in the array is the only duplicate in input.

Here's one hint:
for(int i=0;i<n;i++){
if(arr[i]>0){
if(arr[i]!=index){
a=index;
break;
}
else{
index++;
}
}
}
imagine your sorted array is [-10, -5, 0, 1, 2, 3, 4, 5]
When i==3. arr[3] is equal 1, which is the first number you want to evaluate against index. But index will be equal to 3, not 1 as you might have intended.
And as others have pointed out - duplicate numbers in the array are not handled either.
Second hint:
What if I told you... that there was a way to solve this problem without having to sort the input array at all? What if you had an allocated an array of bools of length N to work with....

You should only increase index if arr[i] == index or else you'll get the wrong result for arrays with duplicates, like {1,2,3,4,5,5,6,7}.
int missingNumber(int arr[], int n) {
std::sort(arr,arr + n);
int index=1;
int a;
for(int i=0; i < n; i++) {
if(arr[i] > 0) {
if(arr[i] == index) { // equal, step
++index;
} else if(arr[i] > index) { // greater, we found the missing one
a=index;
break;
} // else, arr[i] == index - 1, don't step
}
}
return index;
}
You are missing a great opportunity to use the sorted array though. Since you're only interested in positive numbers, you can use std::upper_bound to find the first positive number. This search is done very efficiently and it also means that you don't have to check if(arr[i] > 0) in every iteration of your loop.
Example:
int missingNumber(int arr[], int n) {
int* end = arr + n;
std::sort(arr, end);
int* it = std::upper_bound(arr, end, 0); // find the first number greater than 0
int expected = 1;
while(it != end && *it <= expected) {
if(*it == expected) ++expected;
++it;
}
return expected;
}
Alternatively, std::partition the array to put the positve numbers first in the array even before you sort it. That means that you'll not waste time sorting non-positive numbers.
int missingNumber(int arr[], int n) {
int* end = arr + n;
end = std::partition(arr, end, [](int x){ return x > 0; });
std::sort(arr, end);
int expected = 1;
for(int* it = arr; it != end && *it <= expected; ++it) {
if(*it == expected) ++expected;
}
return expected;
}

You can try using a counting array and then walk the array until you come to an empty space.
int main() {
int N;
cin >> N;
int num; // set to zero b/c zero is out lowest possible number
vector<int> numbers;
while (cin >> num) {
numbers.push_back(num);
}
//create a counting array to add a 1 to all the positions that exist
int * cA = new int[10000] {0};
for (int i = 0; i < N; i++) {
if (numbers[i] >= 0) {
cA[numbers[i]]++;
}
}
for (int i = 1; i < 10000; i++) {
if (cA[i] == 0) {
num = i;
break;
}
}
cout << num;
delete []cA;
return 0;
}

How Code Works : first get element count and add all items into Vector by Loop,with second loop going to 1000 i check from 1 to 1000 if any of 1,2,3,4,... is not in the vector i print missing,i do this with bool variable res,if any of loop counter starting from 1 to 1000 is in the vector res variable is set to True otherwise False.be careful in each run of For Loop from 1 to 1000 you should set res=False
#include <iostream>
#include <vector>
using namespace std;
//Programmer : Salar Ashgi
int main()
{
vector<int> v;
int k=0;
cout<<"Enter array count ?\n";
cin>>k;
int n;
for(int i=0;i<k;i++)
{
cout<<"Enter num "<<i+1<<" : ";
cin>>n;
v.push_back(n);
}
bool res=false;
for(int i=1;i<=1000;i++)
{
res=false;
for(int j=0;j<k;j++)
{
if(v[j]==i)
{
res=true;
break;
}
}
if(!res)
{
cout<<i<<" is missing !";
break;
}
}
}

Related

my code seems perfect but showing wrong output. can someone help me what wrong am i doing here?

i have to return the max len of consecutive seq present in an array.
consider the example:-
N = 7
a[] = {2,6,1,9,4,5,3}
my code should return 6 but its giving 1. don't know how?
int findLongestConseqSubseq(int arr[], int N)
{
//Your code here
unordered_map<int,int> mp;
int ans=0;
for(int i=0;i<N;i++){
if(mp.count(arr[i])>0){
continue;
}
int len1=mp[arr[i]-1];
int len2=mp[arr[i]+1];
int ns=len1+len2+1;
ans=max(ans,ns);
mp[arr[i]-len1]=ns;
mp[arr[i]+len2]=ns;
// ans=max(ans,ns);
}
return ans;
}
There are two problems with your implementation.
The first issue is the code:
if(mp.count(arr[i])>0){
continue;
}
this code is not sufficient to ensure that repeated numbers do not make it into the rest of your loop (to see why this is, consider what happens with neither len1 or len2 are zero).
You can replace it with something like:
if(!mp.insert(pair<int,int>(arr[i], 1)).second) {
continue;
}
This will skip the rest of the loop if an entry for arr[i] exists, but also ensures that an entry will exist after the if expression is evaluated.
The second issue is with the code:
int len1=mp[arr[i]-1];
int len2=mp[arr[i]+1];
the subscript operator for maps in C++ has a side-effect of creating an entry if one does not exist. This is problematic for your algorithm because you do not want this to happen. If it did it would cause the previous piece of code to skip numbers it shouldn't. The solution is to use find but since the code for this is a little ugly (IMHO) it's probably neater to write a helper function:
inline int findOrDefault(const unordered_map<int, int>& map, int key, int defaultValue) {
auto find = map.find(key);
return (find == map.end()) ? defaultValue : find->second;
}
and use this to update your code to:
int len1=findOrDefault(mp, arr[i]-1, 0);
int len2=findOrDefault(mp, arr[i]+1, 0);
Putting this all together you end up with:
inline int findOrDefault(const unordered_map<int, int>& map, int key, int defaultValue) {
auto find = map.find(key);
return (find == map.end()) ? defaultValue : find->second;
}
int findLongestConseqSubseq(int arr[], int N)
{
unordered_map<int,int> mp;
int ans=0;
for(int i=0;i<N;i++){
if(!mp.insert(pair<int,int>(arr[i], 1)).second) {
continue;
}
int len1=findOrDefault(mp, arr[i]-1, 0);
int len2=findOrDefault(mp, arr[i]+1, 0);
int ns=len1+len2+1;
ans=max(ans,ns);
mp[arr[i]-len1]=ns;
mp[arr[i]+len2]=ns;
}
return ans;
}
Ok had a moment to look at this again and I came up with this. First we sort the array to make things easier. Then we can go through the numbers with one pass, counting each time the next consecutive number is greater by one. If the next number is not one greater after sorting, then we reset and start counting again, storing the highest streak count in max.
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
cout << "Get Longest Consecutive Streak: " << endl;
int intArray[] = { 9, 1, 2, 3, 4, 6, 8, 11, 12, 13, 14, 15 ,16 };
int arrayLength = size(intArray);
sort(intArray, intArray + arrayLength); //Sort Array passing in array twice plus amount of indexes in array
cout << "Sorted Array looks like this:" << endl; //Outputting sorted array to check
for (int i = 0; i < arrayLength; i++) {
cout << intArray[i] << " ";
}
cout << endl;
int count = 1;
int max = 1;
/*
* Loop through array, if the next number is one greater than current then add to count
* If it is not, reset the count.
* Store highest count value found passing through.
* */
for (int i = 0; i < arrayLength -1; i++) {
if (intArray[i + 1] == intArray[i] + 1) { //checking next value - is it equal to this one + 1?
count++;
}
else { //else if it is not, store the value if it is higher that what is currently there, then reset
if (max < count) {
max = count;
}
count = 1;
}
}
//Edge case: check again one more time if the current count (when finishing) is greater than any previous
if (max < count) {
max = count;
}
cout << "Longest Consecutive Streak:" << endl;
cout << max << endl;
return 0;
}

Maximum of all subarrays of size k

PROBLEM: Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K.
Why doesn't the following test case pass for the code below:-
Input: 5 4 1 2 3 4 5 Its Correct output is:
4 5
And my Code's output is: 4 5 5
int find_max(queue<int> q){
int max = 0;
while (!q.empty())
{
if (q.front() > max)
max = q.front();
q.pop();
}
return max;
}
vector<int> max_of_subarrays(int *arr, int n, int k){
// your code here
vector<int> res;
queue<int> q;
vector<int> temp;
int i = 0, j = 0;
//for cases where n = k
if(k == n){
sort(arr, arr+n);
temp.push_back(arr[n-1]);
return temp;
}
while(j < n)
{
q.push(arr[j]);
if ((j - i + 1) < k)
{
j++;
}
else if((j - i + 1) == k)
{
int x = find_max(q);
res.push_back(x);
//removing first entered element from queue
q.pop();
//pushing the next element to the queue
q.push(arr[i]);
i++;
j++;
}
}
//for last window
int x = find_max(q);
res.push_back(x);
return res;
}
Can someone tell what's going wrong here?
Yes, we can help.
The line q.push(arr[i]); is wrong. Index i will not be the last element. So, rather index j+1 should be used. But this will be pushed anyway in the next loop run.
So, you do not need this line at all. Delete it!
And in your while loop, you find already all results. So, you can simply delete the last 2 lines
int x = find_max(q);
res.push_back(x);
Then your function will work.
But for real C++ it is too complicated.
You could also use the following approach with a `````std::deque````:
auto maxOfContiguousSubArray(std::vector<int>& data, size_t subArraySize) {
// Here we will store the result
std::vector<int> result{};
// And this will hold our subarray. We use a deque, because we will have then have required iterators
std::deque<int> subArray{};
// Special case: Number of elements is less or equal the subarray size
if (data.size() <= subArraySize) {
// Get the one max element
result.push_back(*std::max_element(data.begin(), data.end()));
}
// Go over all numbers in data
else for (size_t index{}; index < data.size(); index++) {
// Store value in sub array
subArray.push_back(data[index]);
// If there are enough values in subarray, then
if (index >= subArraySize-1 ) {
// Get the max value
result.push_back(*std::max_element(subArray.begin(), subArray.end()));
// Remove the first value
subArray.pop_front();
}
}
return result;
}
int main() {
size_t n{}, k{};
// Read number of elements and size of subarray
if (std::cin >> n >> k) {
// Here we will store our numbers
std::vector<int> data{};
// copy n numbers from std::cin into data
std::copy_n(std::istream_iterator<int>(std::cin), n, std::back_inserter(data));
// Calculate the max values
auto max = maxOfContiguousSubArray2(data, k);
// Show the user output
std::copy(max.begin(), max.end(), std::ostream_iterator<int>(std::cout, " "));
}
return 0;
}
But basically, you do not need a subarray at all. You can simply build a sliding door with iterators or with indices.
Then the function would look like that:
auto maxOfContiguousSubArray2(std::vector<int>& data, size_t subArraySize) {
// Here we will store the result
std::vector<int> result{};
// Special case: Number of elements is less or equal the subarray size
subArraySize = std::min(data.size(), subArraySize);
// Find the max element of the window
for (auto first{ data.begin() }, last{ data.begin() + subArraySize-1 }; last != data.end(); ++first, ++last)
result.push_back(*std::max_element(first, last));
return result;
}
Problem - Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K.
This is how "Maximum of all subarrays of size k" problem is implemented in Java
class Solution
{
static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)
{
int i = 0,j = 0;
ArrayList <Integer> ans = new ArrayList <Integer>();
Deque<Integer> q = new LinkedList<Integer>();
while(j<n){
while(q.isEmpty() == false && q.peekLast() < arr[j])
q.removeLast();
q.addLast(arr[j]);
if(j-i+1 < k)
j++;
else if(j-i+1 == k){
ans.add(q.peekFirst());
if(arr[i] == q.peekFirst())
q.removeFirst();
i++;
j++;
}
}
return ans;
}
}

Repeating elements in vector

I am a C++ student. And I need to solve this problem: "Write a program that receives a number and an array of the size of the given number. The program must find all the duplicates of the given numbers, push-back them to a vector of repeating elements, and print the vector". The requirements are I'm only allowed to use the vector library and every repeating element of the array must be pushed to the vector only once, e.g. my array is "1, 2, 1, 2, 3, 4...", the vector must be "1 ,2".
Here's what I've done so far. My code works, but I'm unable to make it add the same duplicate to the vector of repeating elements only once.
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
int* arr = new int[n];
std::vector<int> repeatedElements;
for(int i = 0; i < n; ++i) {
std::cin >> arr[i];
}
for(int i = 0; i < n; ++i) {
bool foundInRepeated = false;
for(int j = 0; j < repeatedElements.size(); ++j) {
if(arr[i] == repeatedElements[j]) {
foundInRepeated = true;
break;
}
}
if(foundInRepeated) {
continue;
} else {
for(int i = 0; i < n; ++i) {
int count = 1;
for(int j = i + 1; j < n; ++j) {
if(arr[i] == arr[j]) {
++count;
}
}
if(count > 1) {
repeatedElements.push_back(arr[i]);
}
}
}
}
for(int i = 0; i < repeatedElements.size(); ++i) {
std::cout << repeatedElements[i] << " ";
}
std::cout << std::endl;
}
Consider what you're doing here:
if(foundInRepeated) {
continue;
} else {
for(int i = 0; i < n; ++i) { // why?
If the element at some index i (from the outer loop) is not found in repeatedElements, you're again iterating through the entire array, and adding elements that are repeated. But you already have an i that you're interested in, and hasn't been added to the repeatedElements. You only need to iterate through j in the else branch.
Removing the line marked why? (and the closing brace), will solve the problem. Here's a demo.
It's always good to follow a plan. Divide the bigger problem into a sequence of smaller problems is a good start. While this often does not yield an optimal solution, at least it yields a solution, which is more or less straightforward. And which subsequently can be optimized, if need be.
How to find out, if a number in the sequence has duplicates?
We could brute force this:
is_duplicate i = arr[i+1..arr.size() - 1] contains arr[i]
and then write ourselves a helper function like
bool range_contains(std::vector<int>::const_iterator first,
std::vector<int>::const_iterator last, int value) {
// ...
}
and use it in a simple
for (auto iter = arr.cbegin(); iter != arr.cend(); ++iter) {
if (range_contains(iter+1, arr.cend(), *iter) && !duplicates.contains(*iter)) {
duplicates.push_back(*iter);
}
}
But this would be - if I am not mistaken - some O(N^2) solution.
As we know, sorting is O(N log(N)) and if we sort our array first, we will
have all duplicates right next to each other. Then, we can iterate over the sorted array once (O(N)) and we are still cheaper than O(N^2). (O(N log(N)) + O(N) is still O(N log(N))).
1 2 1 2 3 4 => sort => 1 1 2 2 3 4
Eventually, while using what we have at our disposal, this could yield to a program like this:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using IntVec = std::vector<int>;
int main(int argc, const char *argv[]) {
IntVec arr; // aka: input array
IntVec duplicates;
size_t n = 0;
std::cin >> n;
// Read n integers from std::cin
std::generate_n(std::back_inserter(arr), n,
[](){
return *(std::istream_iterator<int>(std::cin));
});
// sort the array (in ascending order).
std::sort(arr.begin(), arr.end()); // O(N*logN)
auto current = arr.cbegin();
while(current != arr.cend()) {
// std::adjacent_find() finds the next location in arr, where 2 neighbors have the same value.
current = std::adjacent_find(current,arr.cend());
if( current != arr.cend()) {
duplicates.push_back(*current);
// skip all duplicates here
for( ; current != (arr.cend() - 1) && (*current == *(current+1)); current++) {
}
}
}
// print the duplicates to std::cout
std::copy(duplicates.cbegin(), duplicates.cend(),
std::ostream_iterator<int>(std::cout, " "));
return 0;
}

Equal elements in an unsorted array

I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other
bool pair(const int array[])
{
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
}
Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?
edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.
I was not trying to compile the code, for the record.
It will do neither:
i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.
If you really cant sort the array (which would be so easy with std::sort) then you can do this:
const int NumCards = 9; // If this is a constant, this definition should occur somewhere.
bool hasPair(const int array[], const int arraySize) {
int possibleCards[NumCards] = {0}; // Initialize an array to represent the cards. Set
// the array elements to 0.
// Iterate over all of the cards in your hand.
for (int i = 0; i < arraySize; i++) {
int myCurrentCard = array[i]; // Get the current card number.
// Increment it in the array.
possibleCards[myCurrentCard] = possibleCards[myCurrentCard] + 1;
// Or the equivalent to the above in a single line.
possibleCards[array[i]]++; // Increment the card so that you
// count how many of each card is in your hand.
}
for (int i = 0; i < NumCards; ++i) {
// If you want to check for a pair or above.
if (possibleCards[i] >= 2) { return true; }
// If you want to check for exactly a pair.
if (possibleCards[i] == 2) { return true; }
}
return false;
}
This algorithm is actually called the Bucket Sort and is really still sorting the array, its just not doing it in place.
do you know the meaning of return keyword? return means reaching the end of function, so in your code if two adjacent values are equal it immediately exits the function; if you want to continue checking for other equality possibilities then don't use return but you can store indexes of equal values in an array
#include <iostream>
using namespace std;
int* CheckForPairs(int[], int, int&);
int main()
{
int array[ ]= {2, 5, 5, 7, 7};
int nPairsFound = 0;
int* ptrPairs = CheckForPairs(array, 5, nPairsFound);
for(int i(0); i < nPairsFound; i++)
{
cout << ptrPairs[i] << endl;
}
if(ptrPairs)
{
delete[] ptrPairs;
ptrPairs = NULL;
}
return 0;
}
int* CheckForPairs(int array[] , int size, int& nPairsFound)
{
int *temp = NULL;
nPairsFound = 0;
int j = 0;
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
nPairsFound++;
}
temp = new int[nPairsFound];
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
{
temp[j] = i;
j++;
}
}
return temp;
}
You could use a std::unordered_set for a O(n) solution:
#include <unordered_set>
using namespace std;
bool hasMatchingElements(const int array[], int arraySize) {
unordered_set<int> seen;
for (int i = 0; i < arraySize; i++) {
int t = array[i];
if (seen.count(t)) {
return true;
} else {
seen.insert(t);
}
}
return false;
}
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
This loop will only compare two adjacent values so the loop will return false for array[] = {2,3,2,4,5}.
You need a nested for loop:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int unsortedArray[] = {2,3,2,4,5};
int size = 5;
for(int i=0;i<size-1;i++)
{ for(int j=i+1;j<size;j++)
{ if(unsortedArray[i]==unsortedArray[j])
{ printf("matching cards found\n");
return 0;
}
}
}
printf("matching cards not found\n");
return 0;
}
----EDIT------
Like Ben said, I should mention the function above will only find the first instance of 2 matching cards but it can't count how many cards match or if there are different cards matching. You could do something like below to count all the number of matching cards in the unsortedArray and save those values into a separate array. It's messier than the implementation above:
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#defin NUM_CARDS 52;
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,i,j;
cin>>N;
int unsortedArray[N];
for(int i=0;i<N;i++)
cin>>unsortedArray[i];
int count[NUM_CARDS]={0};
int cnt = 0;
for( i=0;i<N-1;i++)
{
for( j=i+1;j<N;j++)
{ if(unsortedArray[i]==-1)
break;
if(unsortedArray[i]==unsortedArray[j])
{
unsortedArray[j]=-1;
cnt++;
}
}
if(unsortedArray[i]!=-1)
{
count[unsortedArray[i]]=cnt; //in case you need to store the number of each cards to
// determine the poker hand.
if(cnt==1)
cout<<" 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else if(cnt>=2)
cout<<" more than 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else
cout<<" no matching cards of "<<unsortedArray[i]<<" was found"<<endl;
cnt = 0;
}
}

How do I delete a particular element in an integer array given an if condition?

I'm trying to delete all elements of an array that match a particular case.
for example..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
what i tried:
if (ar[i]==0)
{
x++;
}
b=N-x;
cout<<b<<endl;
this works only if i want to delete a single element every time and i can't figure out how to delete in my required case.
Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences.
Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?
edit(someone requested that i paste all of my code):
int N;
cin>>N;
int ar[N];
int i=0;
while (i<N) {
cin>>ar[i];
i++;
}//array was created and we looped through the array, inputting each element.
int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;
i=0; //now we need to subtract every other element from the array from this selected element.
while (i<N) {
if (a>ar[i]) { //we selected the smallest element.
a=ar[i];
}
i=0;
while (i<N) {
ar[i]=ar[i]-a;
i++;
//this is applied to every single element.
}
if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
{
x++;
}
b=N-x;
cout<<b<<endl;
i++;
}
return 0; }
the entire question is found here:
Cut-the-sticks
You could use the std::remove function.
I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.
To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
Hope that can help.
If you have no space bound try something like that,
lets array is A and number is number.
create a new array B
traverse full A and add element A[i] to B[j] only if A[i] != number
assign B to A
Now A have no number element and valid size is j.
Check this:
#define N 5
int main()
{
int ar[N] = {0,1,2,1,0};
int tar[N];
int keyEle = 0;
int newN = 0;
for(int i=0;i<N;i++){
if (ar[i] != keyEle) {
tar[newN] = ar[i];
newN++;
}
}
cout<<"Elements after deleteing key element 0: ";
for(int i=0;i<newN;i++){
ar[i] = tar[i];
cout << ar[i]<<"\t" ;
}
}
Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.
untested example (with c++11 lambda):
#include <algorithm>
#include <vector>
// ...
std::vector<int> arr;
// populate array somehow
arr.erase(
std::remove_if(arr.begin(), arr.end()
,[](int x){ return (x == 0); } )
, arr.end());
Solution to Cut the sticks problem:
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {
// Calculate length of smallest stick.
int min_length = INT_MAX;
for (size_t i = 0; i < arr.size(); i++)
{
if (min_length > arr[i])
min_length = arr[i];
}
// source_i: Index of stick in existing vector.
// target_i: Index of same stick in new vector.
size_t target_i = 0;
for (size_t source_i = 0; source_i < arr.size(); source_i++)
{
arr[source_i] -= min_length;
if (arr[source_i] > 0)
arr[target_i++] = arr[source_i];
}
// Remove superfluous elements from the vector.
arr.resize(target_i);
}
int main() {
// Read the input.
int n;
cin >> n;
vector<int> arr(n);
for (int arr_i = 0; arr_i < n; arr_i++) {
cin >> arr[arr_i];
}
// Loop until vector is non-empty.
do {
cout << arr.size() << endl;
cut(arr);
} while (!arr.empty());
return 0;
}
With a single loop:
if(condition)
{
for(loop through array)
{
if(array[i] == 0)
{
array[i] = array[i+1]; // Check if array[i+1] is not 0
print (array[i]);
}
else
{
print (array[i]);
}
}
}