Checking and replacing a duplicate in a single for loop - c++

So I have set up my code to be this (note I have my user input for the array and display of the results in another function and a beginner)
int main( )
{
using namespace std;
int a[8];
populateArray(a, 8);
cout<<"The array is: ";
displayArray(a, 8);
cout<<"\nThis array becomes: "<<sameElement(a, 8);
int sameElement(int a[], int size)
{
using namespace std;
for(int i = 0; i < size; i ++)
{
if( a[i] == a[i +1])
{
a[i + 1] = 0;
return i;
}
else
{
return a[i];
}
}
}
Been trying to see if a user puts a duplicate number(that works fine and great). That same array that the user input I want to replace that duplicate to a zero. Sadly I get either a single 0, 1, or 2 and it replaces the entire array. not sure how to return it back to my main as it also says that I have nothing returning from my function despite invoking it in my function and trying to find the right way to return my function. I have declared my function on top and they both match with the parameter as well. So still don't see why I keep getting an issue of returning my function to main?
Example:
The array: 1 2 2 3 4 5 5 7
Array becomes 1 0 0 3 4 0 0 7

I suppose you want to replace duplicate entries of an array in sameElement function. You're getting single integer because sameElement function returns single integer.
Instead of returning value in for loop, let the function run through. Also note that a[i+1] will go over limit of array a, so you have to change ending condition to size - 1.
void sameElement(int a[], int size)
{
for(int i = 0; i < size - 1; i++)
{
if( a[i] == a[i +1])
{
a[i] = 0;
if(i + 1 == size - 1)
{
a[i + 1] = 0;
}
}
}
}
Because the function no longer returns value, you must display it on its own.
cout << "\nThis array becomes: ";
sameElement(a, 8);
displayArray(a, 8);
Lastly, I don't know if this is intentional but sameElement function will only find duplicate entries if they are next to each other: it won't turn 1 2 1 2 1 2 1 2 to zeroes.

Related

Does not iterate in recursion

I have made a code to solve a problem.
This is the link of problem: https://brilliant.org/practice/bijections-overview/?p=2
My opinion is use recursion. I have 3 elements to sum up 5, I iterate single element from 0 to 5 and so on.
This is my code:
#include<bits/stdc++.h>
using namespace std;
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
for(int i = 0; i <= sum ; i++){
return 1 + count_sum_5(sum - i, n - 1);
}
}
int main()
{
int sum = 5;
int count_ele = 3;
cout << count_sum_5(sum, count_ele);
}
Its output is 3, I think it only runs on i = 0 but does not run on i = 1, 2, 3, 4, 5. Could you help me?
Your function will return 1 if n is 1. Otherwise it will enter the for cycle, which will return the value of the first iteration. You call your function by passing 5 and 3, respectively.
First call: It returns 1 + count_sum_5(5, 2)
Second call: It returns 1 + count_sum_5(5, 1)
Third call: It returns 1
So, the second call will evaluate to 1 + 1 = 2 and then the second call will evaluate to 1 + 2 = 3. I'm not sure what your intention is, but the for cycle is not needed for your recursion. Your function is equivalent to
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
return 1 + count_sum_5(sum, n - 1);
}
I'm not sure whether you are satisfied with this. If not, then please let me know what you intend to achieve, sample inputs and outputs would help. If you provide further information, then I will edit my answer accordingly.
return evaluates 1 + count_sum_5(sum - i, n - 1) and then immediately exits the whole function, on the first iteration of the loop. It's not possible to return from a function multiple times.
I don't know what exactly are you trying to solve using that. But For loop will run only one time for i=0, because as soon as it evaluates the 1+count_sum(sum-i, n-1), It will return it.
However, you can do the following changes:
#include<bits/stdc++.h>
using namespace std;
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
int temp = 0;
for(int i = 0; i <= sum ; i++){
temp += (1 + count_sum_5(sum - i, n - 1));
}
return temp;
}
int main()
{
int sum = 5
int count_ele = 3;
cout << count_sum_5(sum, count_ele);
}

Changing function argument to global variable causes unexpected results

I'm solving a backtracking problem. I have to construct a permutation of length n in such a way that the sum of each adjacent elements are prime. The permutation is circular, the last element is adjacent to first element. Note that all valid permutations should start with 1.
void recurse(int i, int prev, int n, vector<int> prime_ring) {
if (i == n) {
prime_ring.insert(prime_ring.begin(), 1);
if (!is_prime[prime_ring.back() + 1])
return;
for (auto data : prime_ring)
cout << data << " ";
cout << "\n";
prime_ring.clear();
return;
}
for (int next = 2; next <= n; next++) {
if (!seen[next] && is_prime[prev + next]) {
prime_ring.push_back(next);
seen[next] = true;
recurse(i + 1, next, n, prime_ring);
seen[next] = false;
prime_ring.pop_back();
}
}
}
The above code generates the wanted permutations correctly. For example for n = 4. Permutations should be
1 2 3 4
1 4 3 2
void recurse(int i, int prev, int n) {
if (i == n) {
prime_ring.insert(prime_ring.begin(), 1);
if (!is_prime[prime_ring.back() + 1])
return;
for (auto data : prime_ring)
cout << data << " ";
cout << "\n";
prime_ring.clear();
return;
}
for (int next = 2; next <= n; next++) {
if (!seen[next] && is_prime[prev + next]) {
prime_ring.push_back(next);
seen[next] = true;
recurse(i + 1, next, n);
seen[next] = false;
prime_ring.pop_back();
}
}
}
Changing prime_ring to a global vector, results in runtime error. This problem happened to me many times, I failed to realise what's wrong. I'm not aware of the difference between global vector vs function argument vector.
I'm not aware of the difference between global vector vs function argument vector.
The difference is that when you pass a vector as a parameter, the vector is copied. On the other hand when you use a global variable, there is only one `vector.
The solution here is to not use a global variable since you have a working function.
Suppose you are on the line
recurse(i + 1, next, n);
where i == n - 1
Suppose when you go into the recurse function, is_prime[prime_ring.back() + 1] is true.
Then you call prime_ring.clear();, and returns.
Afterwards, you call prime_ring.pop_back();
What happens if you try to pop_back() from an empty vector? Well, bad things can happen (namely, Undefined Behaviour)

how to fix this programme

Given an array A, find the highest unique element in array A. Unique element means that element should present only once in the array.
Input:
First line of input contains N, size of array A. Next line contains N
space separated elements of array A.
Output:
Print highest unique number of array A. If there is no any such
element present in array then print -1.
Constraints:
1 ≤ N ≤ 106 0 ≤ Ai ≤ 109
SAMPLE INPUT
5 9 8 8 9 5
SAMPLE OUTPUT
5
Explanation
In array A: 9 occur two times. 8 occur two times. 5 occur once hence the answer is 5.
Can you explain what is wrong with this code?
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[n], i, max = -99;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
cout << max;
}
}
for (i = 0; i < n; i++) {
if (max == a[i]) {
break;
} else {
// cout<<"-1";
}
max =
}
return 0;
}
There's a few problems here (right now it won't even compile at max =). But the algorithmic problem is this: the second for loop finds the maximum before rejecting duplicate entries. The reverse is needed. First reject duplicates (say, by setting them to -99), then find the max of what is left over.

How to fill a 2D array with Every Possible Combination? C++ Logic

I can't figure out the logic behind this one... here's what I have so far:
#include <iostream>
using namespace std;
int thearray[4][4];
int NbPos = 4;
int main() {
int i2;
int q2;
for(int i = 1; i < 4; i++) {
for(int q = 1; q < 4; q++) {
for(int c = 0; c < NbPos; c++) {
thearray[i][q] = c;
}
}
}
}
This is filling the array up to the end is still:
3 3 3
3 3 3
3 3 3
but it's doing so without hitting anywhere near every possible combination.
Ideally once it gets to:
0 0 0
0 0 0
0 0 3
the next step SHOULD be:
0 0 0
0 0 0
0 1 0
so it hits a TON of combinations. Any ideas on how to make it hit them all? I'm stumped on the logic!
with the way you're iterating over this, a 1-dimensional array would make the looping simpler. you can still mentally treat it to have rows and columns, however they are just layed out end-to-end in the code.
you could try something like this; however if you want it in a 2D format specifically that challenge is left to you ;)
#include <iostream>
using namespace std;
#define rows 4
#define columns 4
int main() {
int thearray[rows * columns] = {0};
int NbPos = 4;
int lastPos = rows * columns - 1;
while (true) {
thearray[lastPos]++;
int pos = lastPos;
while (thearray[pos] == NbPos and pos >= 1) {
thearray[pos - 1]++;
thearray[pos] = 0;
pos--;
}
bool finished = true;
for (int i = 0; i < rows * columns; i++) {
if (thearray[i] != NbPos - 1) {
finished = false;
}
}
if (finished) {
break;
}
}
for (int i = 0; i < rows * columns; i++) {
std::cout << thearray[i] << " ";
if (i % rows == rows - 1) {
cout << endl; // makes it look like a 2D array
}
}
}
It makes sense to have the final form as all 3s , since you loop every element of the array and you assign it at the end with 3 .
So the next element will only take into account the combination with the final value of the previous element (which will be 3).
Thinking in math terms, your complexity is N^3 so to speak (actually is N^2 * 4 , but since your N is 3 ...).
Your approach is wrong, since you want to find permutations, which are defined by a factorial function , not a polinomial function.
The necessary complexity for the output doesn't match the complexity of your algorithm (your algorithm is incredbily fast for the amount of output needed).
What you are looking for is backtracking (backtacking will match the complexity needed for your output).
The recursion function should be something like this (thinking on a 1D array, with 9 elements):
RecursiveGeneratePermutations(int* curArray, int curIdx)
{
if (curIDX==9)
{
for (int i=0; i<9;i++)
{
// write the array
}
} else {
curArray[curIdx]=0;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=1;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=2;
RecursiveGeneratePermutations(curIdx+1);
curArray[curIdx]=3;
RecursiveGeneratePermutations(curIdx+1);
}
}
Now you only need to call the function for the index 0 :
RecursiveGeneratePermutations(arrayPtr,0);
Then wait...allot :).

bug in c++ program count no of 1's in vector

A question was asked to me during an online interview.
They provided a piece of code and we have to find out a possible bug in the code.
The code is provided below as it is.
The function is provided with a non empty zero indexed vector of integers (which contains only 1 and 0).
The function will return the start position of longest sequence of 1's.
for example if the input values {0,0,0,1,1,1,1,1,0,0,1,1,1,0,1,1} it will return 3 because the longest sequence of 1's is from position 3 to 7 total five consecutive 1's.
if the input values are {0,0,1} then it will return 2 because there is only one 1 and length of longest sequence of 1 is one.
If there are no 1's then it will return -1.
The input vector can be changed so we can't change the signature of the vector to const.
I tested this function with variable no of inputs and I found out that it is working fine.
I am not able to find out any bug in the code. But the instruction says that there is a bug in the code and we can change maximum 2 lines of code to solve the bug.
int solution(vector<int>& A) {
int n = A.size();
int i = n - 1;
int result = -1;
int k = 0;
int maximal = 0;
while (i > 0) {
if (A[i] == 1) {
k = k + 1;
if (k >= maximal) {
maximal = k;
result = i;
}
} else {
k = 0;
}
i = i - 1;
}
if (A[i] == 1 && k + 1 > maximal)
result = 0;
return result;
}
To fix UB for empty case, I add check for !A.empty(),
and I profit of that to replace i by 0 (at that point i == 0)
and to replace the check with maximal value to have a coherent result for tie:
if (!A.empty() && A[0] == 1 && k + 1 >= maximal)
And as I may change an other line, I would fix the prototype as A is not modified.
int solution(const std::vector<int>& A) {
problem specifications are that
1.vector is immutable and
2.Input vector is not empty
I tried same problem in Java but different approach to see what is missing because i cant find any bug in above code.
package javaapplication7;
/**
*
* #author Owner
*/
public class JavaApplication7 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] A={0,1,0,1,1,1,1};
System.out.println(solution(A));
}
static int solution(int A[]){
int i=0,count=0,max=0,pos=-1;
while(i<=A.length-1)
{
if(A[i]==1)
{
count++;
i=i+1;
}
else
{
i=i+1;
count=0;
}
if(count>max)
{
pos=i-count;
max=count;
}
}
if(count==0)
return pos;
else
return pos;
}
}
the given code will favor a sequence closer to the left side if two sequences are of equal length. that doesn't happen for the checking of index 0
if (A[i] == 1 && k + 1 > maximal)
should be
if (A[i] == 1 && k + 1 >= maximal)