Piece of code doesn't give the answer I need. Suggested edits? - c++

This code is supposed to check the input array for five consecutive '1's if found, it is supposed to add a '0' at the end as a parity bit for a simple parity bit checker.
This is the code.
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
int n, a[30], b[5] = {1, 1, 1, 1, 1}, temp = 0, count = 0;
cout << "Enter the size of input bits :";
cin >> n;
cout << endl;
cout << "Enter the input bits :";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = n; i >= 0; i--) {
if (i >= 4) {
temp = i;
for (int j = 0; j < 5; j++) {
if (a[temp] == b[j]) {
temp++;
count++;
}
}
}
}
if (count == 4) {
n = n + 1;
a[n] = 0;
}
cout << endl << endl;
for (int i = 0; i < n; i++) {
cout << a[i];
}
getch();
return 0;
}

Here is a simple logic of what you want to achieve.. let's say input array is a, it's length is n:
int counter = 0;
for(int i=0; i<n; i++) {
if(a[i] == 1)
counter++;
else
counter = 0; //need to start looking for 1's again because consecutive stream is broken
if(counter == 5) {
a[i+1] = 0; //found 5 consecutive 1's so next bit will be 0
i++; //don't need to check the next bit which is already 0
counter = 0; //resetting counter
}
}
The above code will change the array [2,3,1,1,1,1,1,3,4,5] to -> [2,3,1,1,1,1,1,0,4,5]
If you want to insert 0 at the end of the array then simply change a[i+1] = 0 to a[n+1] = 0 and remove i++;
You also need to make sure that n is not greater than the size of array.

I'll go line by line from the beginning:
change for(int i=n; i>=0; i--) to for (int i = n-1; i >= 0; i--) (n-sized array in C++ has cells in the range of [0, n-1])
change if(i>=4) to if (n >= 5)
place temp++ after if(a[temp]==b[j]){}, not inside of it.
add
if (count == 5) break;
else count = 0;
just after for(int j = 0; j < 5; j++) loop
change
if(count==4)
{
n=n+1;
a[n]=0;
}
to
if(count == 5){
a[n] = 0;
n = n+1;
}
Once again! n-sized array holds n elements on positions 0 to n-1
Of course sequence makes a difference above!
You can also write it as if (count == 5) a[n++] = 0;
And that would be all.

Related

How do I find the number with the most divisors in an array?

I have to input numbers into an array and at the end get the number that has the most divisors, or if there are more numbers with the same amount, print out the first one.
Example: 4 numbers, 6 12 48 108. 108 has the most divisors, so this one needs to show up. if there were numbers after 108 with the same amount of divisors, 108 would have still been the only one to show up.
#include <iostream>
using namespace std;
int main()
{
int n = 0, d, largestCnt = 0;
int cntA=0, cntB=0;
cout << "How many elements?\n";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
for(int i=0; i<n; i++){
for(d=2; d<v[i]/2; d++)
if(v[i]%d==0)
cntA++;
for(d=2; d<v[i+1]/2; d++)
if(v[i+1]%d==0)
cntB++;
if(cntA > largestCnt)
largestCnt = cntA;
if(cntB > largestCnt)
largestCnt = cntB;
}
cout << largestCnt;
return 0;
}
this is the most I've done the past 2 hours, and I can't get past it
EDIT:
#include <iostream>
using namespace std;
int main()
{
int n = 0, d;
int mostDivisors=0, number_with_most_divisors=0;
int currentDivisors = 0;
cout << "How many elements?\n";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
number_with_most_divisors = v[0];
for(d=2; d<=v[0]/2; d++){
if(v[0]%d == 0)
mostDivisors++;
}
for(int i=1; i<n; i++){
for(d=2; d<=v[i]/2; d++)
if(v[i]%d == 0)
currentDivisors++;
if(currentDivisors > mostDivisors){
mostDivisors = currentDivisors;
number_with_most_divisors = v[i];
}
}
cout << number_with_most_divisors;
return 0;
}
Here is the algorithm of what you have to do:
Count the number of divisors of the first element in array. Save this value in mostDivisors. Set number_with_most_divisors as the first element in the array.
Start from the second element in array (position 1) and for each element, count how many divisors it has, save it in currentDivisors. If currentDivisors > mostDivisors then set mostDivisors to be equal to currentDivisors and update number_with_most_divisors to be the current element in the array.
The result is number_with_most_divisors at the end of the loop.
UPDATE
You are forgetting to initialize currentDivisors for each element after the first loop:
for(int i=1; i<n; i++){
currentDivisors = 0; // You forgot to put this line!
for(d=2; d<=v[i]/2; d++)
if(v[i]%d == 0)
currentDivisors++;
if(currentDivisors > mostDivisors){
mostDivisors = currentDivisors;
number_with_most_divisors = v[i];
}
// function to count the divisors
int countDivisors(int n)
{
int cnt = 0;
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal,
// count only one
if (n / i == i)
cnt++;
else // Otherwise count both
cnt = cnt + 2;
}
}
return cnt;
}
You can loop to enter the numbers into an array
#include <iostream>
int main() {
int n = 0, max_divs = 0, count = 0, max_divs_index = 0;
std::cin >> n;
int *v = new int[n];
for (int i = 0; i < n; ++i) std::cin >> v[i];
for (int i = 0; i < n; ++i) {
count = 0; // resetting count to 0 in each iteration
for (int j = 2; j < v[i]/2; ++j)
if (v[i] % j == 0) count++; // checking if the number is divisible by numbers between 1 and number itself/2 (1 and num/2 exclusive)
if (count > max_divs) { // checking if current count is greater than the maximum divisors
max_divs = count; // updating maximum divisors
max_divs_index = i; // updating the index of array element with maximum divisors
}
}
std::cout << v[max_divs_index];
delete[] v;
return 0;
}

Need To Print Repeated Numbers Just Once / C++

Can't use libraries and other methods.
As you can see my program finds the repeated numbers and print it but I need to print the numbers just once.
As example if entered:
7 1 1 2 1 2 2 9
It should print
1 2
In case there is no any repeated number:
7 1 2 3 4 5 6 7
There should not be any output!
Also note, that the first number is the length of array:
#include <iostream>
int main()
{
unsigned size;
std::cin >> size;
int* myArray = new int[size];
for (int i = 0; i < size; i++) {
std::cin >> myArray[i];
}
for (int i = 0; i < size; i++) {
bool found = false;
for (int j = 0; j < i && !found; j++) {
found = (myArray[i] == myArray[j]);
}
if (!found) {
std::cout << myArray[i] << " ";
}
}
delete []myArray;
}
The easiest approach would probably be to use a set, but I'm not sure if that's allowed under the "can't use other libraries" rule.
Using just arrays, for each item you could iterate over all the items before it, and only print it if it wasn't found there:
for (int i = 0; i < size; i++) {
bool found = false;
for (int j = 0; j < i && !found; j++) {
found = (myArray[i] == myArray[j]);
}
if (!found) {
cout << myArray[i] << " ";
}
}
The first occurrence of a repeated number has no occurrences before it and at least one after it.
This is reasonably easy to detect:
for (int i = 0; i < size; i++) {
bool before = false;
for (int j = 0; j < i && !before; j++) {
before = myArray[i] == myArray[j];
}
if (!before) {
bool after = false;
for (int j = i + 1; j < size && !after; j++) {
after = myArray[i] == myArray[j];
}
if (after)
{
cout << myArray[i] << " ";
}
}
}
Instead of two bools as the other user suggested I would use the counter basically doing the same thing but with one variable. The trick is to check if you have already had the number you are checking right now before so that you wouldn't print it again.
And then to check the rest of the list for duplicates.
#include <iostream>
int main()
{
unsigned size;
std::cin >> size;
int* myArray = new int[size];
for (int i = 0; i < size; i++) {
std::cin >> myArray[i];
}
for (int i = 0; i < size; i++) {
int count = 0;
//check if the number has already been found earlier
for (int j = 0; j < i && !count; j++) {
if(myArray[i] == myArray[j]) count++;
}
//check the rest of the array for the repeated number
if (!count) {
for (int j = i; j < size; j++) {
if(myArray[i] == myArray[j]) count++;
}
}
//print if repeated
if (count > 1) {
std::cout << myArray[i] << " ";
}
}
delete []myArray;
}

How to check if 3 elements of array have the same value

I am trying to write a program which checks if 3 (or more) elements of an array are the same.
I have written a code which works almost perfectly, but it gets stuck when there are 3 pairs of equal elements and I'm not sure how to fix it.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, a[10],skirt=0;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
cout<<skirt<<endl;
if(skirt>=3)
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
}
When I input
6
3 3 2 2 1 1 i
get "TAIP" but I need to get "NE".
You can use the following algorithm: first sort the array. Then iterate each adjacent pair. If they are equal, then increment counter, if not then reset counter to 1. If counter is 3, return true. If loop does not return true, then return false.
Add the following condition in the outer for loop
for(int i = 0; i < n - 2 && skirt != 3; i++)
^^^^^^^^^^^^^^^^^^^^^^^
{
skirt = 1;
^^^^^^^^^
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
Of course before the loop you should check whether n is not less than 3. For example
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
}
Here is a demonstrative program
#include <iostream>
using namespace std;
int main()
{
int a[] = { 6, 3, 3, 2, 2, 1, 1 };
int n = 7;
int skirt = 0;
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if ( a[i] == a[j] )
{
skirt++;
}
}
}
}
cout << skirt << endl;
if ( skirt == 3 )
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
return 0;
}
Its output is
1
NE
because the array does not have 3 equal elements.
Reset skirt to 0 every time you increase i if it is less than 3, or break out the loop otherwise.
Another way to do this is using a std::map, which keeps a count of the number of times a given value occurs in your array. You would stop looking as soon as you have a number that has three occurrences.
Here's a 'minimalist' code version:
#include <iostream>
#include <map>
using std::cin; // Many folks (especially here on SO) don't like using the all-embracing
using std::cout; // ... statement, "using namespace std;". So, these 3 lines only 'use'
using std::endl; // ... what you actually need to!
int main() {
int n, a[10], skirt = 0;
std::map<int, int> gots;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n && skirt < 3; i++) {
skirt = 1;
if (gots.find(a[i]) != gots.end()) skirt = gots[a[i]] + 1;
gots.insert_or_assign(a[i], skirt);
}
cout << (skirt >= 3 ? "TAIP" : "NE") << endl;
return 0;
}
I'm not saying this is any better (or worse) than the other answers - just another way of approaching the problem, and making use of what the Standard Library has to offer. Also, with this approach, you could easily modify the code to count how many numbers occur three or more times, or any number of time.
Feel free to ask for further clarification and/or explanation.

How do I put any value X after all the minimums in an array?

If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}

My C++ code goes into infinite loop when array size increases

I am trying to solve the problem at: Cut the Sticks.
My code works fine when the array size <=3 but goes bonkers then the size increases to >=6
#include<iostream>
using namespace std;
int minElement(int a[]){
int min = a[0];
int k;
for (k=1; k < 6; k++){
if (a[k] < min and a[k] > 0)
min = a[k];
}
return min;
}
int main(){
int a[6];
for (int i=0; i<6; i++){
cin >> a[i];
}
int minElem, flag;
while (true){
flag = 0;
minElem = minElement(a);
for (int i = 0; i < 6; i++){
a[i] = a[i] - minElem;
}
for (int j = 0; j < 6; j++){
if (a[j] > 0){
cout<<a[j]<<endl;
flag++;
}
}
if (flag == 0)
break;
};
return 0;
}
The problem is arising in the minElement function, it seems. On print min after assignment, it shows min as empty. Similarly, inside the loop in the function, I am getting blanks for all mins. What could be the issue?
EDIT
Please try the code here: http://cpp.sh/2ti6 with the input as [5,4,4,2,2,8]. It doesn't reach zero, the code starts failing before the first iteration, when the minimum element is called as Nothing is returned from the minElement functionn
Problem is there because of this line in the code
int min = a[0];
you need to check that array element is non-zero
int minElement(int a[]){
int min = 0;
int i=0;
while(i<6) // check the array element is non -zero
{
if(a[i]>0){
min = a[i];
break;
}
i++;
}
//int min = a[0];
int k;
for (k=1; k < 6; k++){
if (a[k] < min && a[k] > 0)
min = a[k];
}
return min;
}
The problem lies in your minElement function.
In the case that a[0] happens to be zero, you'll never assign another value to min and will return zero. Out of the function you will subtract zero to the values and enter the infinite loop.
In the case that a[0] is a negative number, you'll end up subtracting a negative value (and so increase the values instead). Then a[0] will become zero and your program loops.
Initializing min with a[0] is not enough, you have to look for a valid minimum value. You could, for example, initialize it with a very large value (not a very good solution) or search the array for the first valid min value.
EDIT:
I added some prints to your code:
...
while (true){
flag = 0;
minElem = minElement(a);
std::cout << "Min: " << minElem << std::endl;
for (int i = 0; i < 6; i++){
a[i] = a[i] - minElem;
}
std::cout << "Values:";
for (int j = 0; j < 6; j++){
std::cout << " " << a[j];
if (a[j] > 0){
//cout << " " << a[j];
flag++;
}
}
std::cout << std::endl;
if (flag == 0)
break;
getchar();
}
...
Here's the output:
5 4 4 2 2 8
Min: 2
Values: 3 2 2 0 0 6
Min: 2
Values: 1 0 0 -2 -2 4
Min: 1
Values: 0 -1 -1 -3 -3 3
Min: 0
Values: 0 -1 -1 -3 -3 3
(...) Loop forever
I hope that helps you understand now what the problem is.
int minElement(int a[]); change this to int minElement(int a[], int size)
2.
int a[6];
for (int i=0; i<6; i++){
cin >> a[i];
}
change this to
int arr_size=0;
cout << "Enter the array size ";
cin >> arr_size;
int a[arr_size];
for (int i=0; i<arr_size; i++){
cin >> a[i];
}
for (int i = 0; i < 6; i++){
a[i] = a[i] - minElem;
}
You are subtracting the min of the array from each element, so at this point there is only one 0 in the array and rest are positive numbers.
for (int j = 0; j < 6; j++){
if (a[j] > 0){
cout<<a[j]<<endl;
flag++;
}
So at this point flag has to be some positive number, and in this case 5.
if (flag == 0)
break;
This condition will never hit and hence the infinite loop.
it has nothing to do with the dimension.
What happens is that if a[0] is the smallest value => it will run in an infinte loop. Why because a[0] eventually becomes 0.
Why does a[0]=0 run in an infinte loop?
What value does minElement return when a[0] is 0?
try replace int min = a[0]; qith min = (a[0]>0) ? a[0]: 1;
or adding `minElem= (minElem>0) ? minElem: 1;' after 'minElem = minElement(a);'
PS:
Looking at all the answers this seems the simplest minElement that does what you want:
int minElement(int a[]){
int min = a[0];
int k;
for (k=1; k < 6; k++){
if(min==0 && a[k]>0 )
min=a[k];
else
if (a[k] < min and a[k] > 0)
min = a[k];
}
return min;
}
the min will only be zero at iteration N if a[j]==0 for all j+1
I solve this base on the link you provide. I use vector for me to easy remove those minimum length stick.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int noOfInput;
int input;
vector<int> myVec;
cin>>noOfInput;
for (int i=0; i<noOfInput; i++){
cin >> input;
myVec.push_back(input);
}
sort(myVec.begin(),myVec.end(),greater<int>());
while(myVec.size()>0){
int minimum = myVec[myVec.size()-1];
int lengthOfVector = myVec.size();
cout<<myVec.size()<<" ";
for(int i = lengthOfVector-1 ; i >=0 ; i--){
myVec[i]=myVec[i]-minimum;
if(myVec[i]==0){
myVec.pop_back();
}
}
}
return 0;
}