I have Array A[9]= {1,2,3,4,5,6,7,8,9} and I need to delete the numbers which are not dividing by 2. The code I tried to do:
int main()
{
int n;
ifstream fd(Cdf);
fd>>n; // read how many numbers are in the file.
int A[n];
for(int i = 0; i < n; i++)
{
fd >> A[i]; //read the numbers from file
}
for(int i = 0; i < n; i ++) // moving the numbers.
{
if(A[i] % 2 !=0)
{
for(int j = i; j < n; j++)
{
A[i] = A[i+1];
}
}
}
fd.close();
return 0;
}
But I get numbers like 224466888. what I need to do to get 2,4,6,8?
I need to delete numbers in the same array.
First you should use std::vector for dynamic size arrays.
Second, for removing numbers that are even in a vector, you can do :
std::vector<int> inf = {12,0,5,6,8};
auto func = [](int i){return i % 2 != 0;};
inf.erase(std::remove_if(inf.begin(),inf.end(),func), inf.end());
EDIT :
Ok, so you can still do this without std::vectors, but it will be uglier :
#include <algorithm>
int res[] = {2,5,9,8,6,7};
int size = 6;
auto func = [](int i){return i % 2 != 0;};
int new_size = std::remove_if(res,res + size, func) - res;
All the data you want is in [0, new_size[ range, the other part of your array is now garbage.
Your removal loop is indexing with the wrong variable:
for(int j = i; j < n; j++)
{
A[i] = A[i+1];
}
You're using i, which doesn't change in the loop.
Change it to j. You also need to subtract one from the upper limit, as you'd step outside of the array otherwise when accessing A[j + 1].
for(int j = i; j < n - 1; j++)
{
A[j] = A[j + 1];
}
An array can't be used for your purpose. It is allocated on stack and its size can't be changed dynamically (you can't change the size of an array in general, not only when it is allocated on stack).
You could allocate a second array and keep reallocating it with realloc everytime you add a new element but that's not the good way to do it. You are working with C++ so just use a std::vector<int> and your problems will be solved:
std::vector<int> evenArray;
evenArray.reserve(sizeof(A)/sizeof(A[0])/2);
if (number is even) {
evenArray.pushBack(number);
}
Mind that vector stores elements contiguously so this is legal:
int *evenA = &evenArray[0];
For your inner for loop you should be referencing j, not i.
for(int j = i; j < n - 1; j++)
{
A[j] = A[j+1];
}
Otherwise, what's the point of creating j?
Of course, this also means if you read the whole array back you will display all the characters that were shifted (which will just be equal to the last number). So, you should probably keep track of the new length of the array and just iterate to that instead of the end of the array.
EDIT:
In the inner for loop you need to loop to n - 1 otherwise when you have A[j + 1] it will go off the end of the array when you to change it, which may or may not give you a runtime error.
Related
I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++) {
for(int i = 0; i < size; i++) {
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
You are not looping correctly. Looks like you are trying bubble sort which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++)
for(int i = k+1; i < size; i++)
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(array[j]>array[j+1])
{
swap(array[j] , array[j+1]);
}
}
}
}
I see that you are trying to implement the bubble sort algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j and the element next to it at index j+1. If array[j] is greater than array[j+1] , you swap them using the swap() function or by using the temp method. The outer loop will run size - 1 times , and the inner loop will run size - 1 - i times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i . You can see the nested loop runs less number of times in each iteration of the outer loop.
There is only one mistake that your 2nd loop condition should be: i < size -1.
So it should be:
for (int i = 0; i < size -1; i++)
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1, therefore i + 1 is equal to size, thus data[i+1] is out of range. Simply change the condition of your for to be i < size - 1.
Working example: https://godbolt.org/z/e5ohWPfTz
I have an array a={1,2,3,3,2,2,3,3} and I need to remove the duplicates like this:
1: a={1,2,2,2,3,3}
2: a={1,2,3,3}
3: a={1,2}
I need to remove 2 consecutive duplicates: (1,2,3,3 will be 1,2), (1,2,2,2 will be 1,2).
Here is my try, but as you can see, I need some help.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int a[n];
for (int i = 0; i < n; i++)
std::cin >> a[i];
int i, j;
for (i = 0; i < n; i++)
if (a[i] == a[i + 1]) {
for (j = i + 1; j < n; j++)
a[j - 1] = a[j];
n--;
i--;
}
if (n != 0)
for (int i = 0; i < n; i++)
std::cout << a[i] << " ";
return 0;
}
My problem is that I don't know how to remove 2 consecutive values. After multiple tries, I can't resolve this. Thank you in advance!
I'm not going to write code for you, but here are my thoughts.
First, write a function to check if there even exists "consecutive duplicates":
//returns true if there are no consecutive duplicates within the array, false otherwise
func noConsecDups(arr a)
for int i = 0, i <= a.length-2, i++
if a[i] = a[i++]
return false
end of if
end of loop
return true
end function
Now, write a function that removes the consecutive duplicates recursively (might not have to do it recursively, that's just my initial thought) while checking to see if you even need to remove any!
//function that takes an array as input and returns the array with all consecutive duplicates removed
func removeConsecDups(arr a)
if a.length is 1, return a
if a.length is 2 and a[0] != a[1], return a
if(noConsecDups(a)) then there are no consecutive duplicates, return a
otherwise look through the array and just remove the first consecutive duplicates
for int j = 0, j <= a.length-2, j++
if a[j] = a[j+1]
remove a[j+1]
remove a[j]
break
end if statement
end loop
recursively call removeConsecDups(a)
end function
If you just need the final result (an array with no consecutive duplicates left) then your best bet is probably to use a stack and just traverse the whole input array once, comparing the values to the stack top and poping the duplicates off the stack.
If you need to print out the array state after every intermediate step, then #BarronDuBois's suggestion is the way to go.
Either way the code itself should be simple enough, I'd be glad to help with any specific issue.
This project is a homework assignment for school. The instructor has asked us to input 20 random integers then print the smallest in the list and then search the list for the first iteration of the number entered. My problem is returning the smallest number of the list. The function, shown below accepts an integer array and an integer with the size of the array. In Visual Studio, the tests for the smallest number work until the function returns the value. Instead of returning the smallest number, the function returns some kind of default value as opposed to the smallest integer. I have been staring at this code for the past two hours, any help would be appreciated.
int theSmallest(const int a[], int number_used)
{
int temp = a[0];
// Find the smallest number in array a[]
for (int i = 0; i <= number_used; i++)
{
if (temp >= a[i])
{
temp = a[i];
}
}
return temp;
}
Your program has undefined behavior because you are accessing the array a using an invalid index.
When an array has 20 elements, the valid indices are 0-19, not 0-20.
You are using
for (int i = 0; i <= number_used; i++)
and then accessing a[i] in the loop. If number_used is equal to 20, you are accessing a using and index value of 20, which is not correct.
Change that to use i < number_used.
for (int i = 0; i < number_used; i++)
A minor issue is that you are using temp >= a[i], which can be changed to use temp > a[i]. Use of >= in this case will work but it will do more work than necessary.
Here's an updated version of the function:
int theSmallest(const int a[], int number_used)
{
int temp = a[0];
// Find the smallest number in array a[]
for (int i = 1; i < number_used; i++)
{
if (temp > a[i])
{
temp = a[i];
}
}
return temp;
}
Assuming number_used is the size of array, code can be written as:
int theSmallest(const int a[], int number_used)
{
if( a == nullptr or number_used == 0 )
throw std::runtime_error( "invalid argument" );
return *std::min_element( a, a + number_used );
}
Note: you code has issue in case number_used is equal to 0 or a pointer is passed as nullptr, you may not expect that to happen but it is good idea to always validate your input (at least by assert())
Change to i < number_used and I think change to if(temp > a[i]).
You can also start i=1 since you made the assumption index 0 is the smallest.
Change
for (int i = 0; i <= number_used; i++)
to
for (int i = 1; i < number_used; i++)
I need a program that sorts an array of integers without using conditional statements. Numbers are in the range from 0 to 100 and don't repeat.
#include <iostream>
using namespace std;
int main() {
int arr[] = { 34, 12, 24, 65, 63, 22 };
int arraySize = (sizeof(arr) / sizeof(*arr));
unsigned char buf[101] = { 0 };
for (int k = 0; k < arraySize; k++) {
buf[arr[k]]++;
}
unsigned char i = 0;
for (int k = 0; k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
for (int a : arr) {
cout << a << endl;
}
system("pause");
return 0;
}
This program works but I get the error after closing of the command prompt:
Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.
Is there a way to fix it?
The problem is that your code writes past the end of the array. It happens after you have encountered the last element in the counted sequence, but before the array buf has been exhausted, i.e.
for (int k = 0; k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
When you add the highest element, which is 65, to the result, i reaches 6, so assigning a[i] becomes illegal. See what's going on by adding an extra element to your array, setting it to -1, and watching what happens to it (it gets set to 100; demo 1).
You can fix it by adding an early exit condition to stop as soon as you filled the array back, i.e.
for (int k = 0; i < arraySize && k <= 100; k++) {
arr[i] = k;
i += buf[k];
}
Now the -1 past the end of "active" part of our array remains -1 (demo).
The logic of the second loop is wrong. You have six numbers in arr, no doubles, which means that a total of six elements in buf will be set to 1.
That means that after a while, the value of i will be 6, which you then use as an index into arr, but index 6 is the seventh element in an array, leading you to write out of bounds.
I am trying to create a function that will find the intersection of two dynamically allocated arrays comparing array 1 to array 2. For any values in array 1 that are not in array 2, those values should be deleted in array 1 so that array 1 now only holds the common values of both arrays (no repeats). I cannot use vectors, hashes, or any other thing outside of my current functions in my class:
here is my code so far:
bool IntSet::contains(int val) const
{
for (int i = 0; i < numValues; i++)
{
if (set[i] == val)
return true;
}
return false;
}
this function compares an integer parameter to values currently stored in the array...if a value is in the array it returns true and if else false;
this next function takes in a value and removes that value from the array:
void IntSet::remove(int val)
{
for (int i = 0; i < numValues; i++)
{
if (set[i] == val)
for (int j = 0; j < numValues; j++)
set[j] = set[j + 1];
}
numValues--;
}
here's where I've been having problems, this next function is supposed to iterate through one array and compare those values with the values in the other array...if one value from one array is in the other, it should just skip it, but if a value is not in the array calling the function, it should delete that value from the calling array:
void IntSet::removeDifferent(const IntSet &set2)
{
for (int i = 0; i < set2.size(); i++)
{
if (!set2.contains(set[i]))
{
remove(set[i]);
}
}
}
ive tried about 50 different variations on the removeDifferent() function and I just can't seem to figure this one out. Could someone point me in the right direction?
You're iterating i through the indexes of set2, but then you're testing set[i]. Try this:
void IntSet::removeDifferent(const IntSet &set2)
{
for (int i = 0; i < numValues; ) {
if (!set2.contains(set[i])) {
remove(set[i]);
} else {
i++;
}
}
Note that I also removed i++ from the for loop header. This is because when you remove an element, all the following elements are shifted down, so the next element takes its place in the array. If you incremented i, it would skip that element.
You also need to fix remove. It should start its inner loop from i, so it only shifts down the elements after the one being removed, and it should stop at numValues-1, so it doesn't try to access outside the array when it copies set[j+1]. And as an optimization, it can break out of the outer loop once it has found a match (I assume IntSet doesn't allow duplicates, since you only decrement numValues by 1).
void IntSet::remove(int val)
{
for (int i = 0; i < numValues; i++)
{
if (set[i] == val) {
for (int j = i; j < numValues - 1; j++) {
set[j] = set[j + 1];
}
break;
}
}
numValues--;
}
Your problem is in your remove() function:
void IntSet::remove(int val)
{
for (int i = 0; i < numValues; i++)
{
if (set[i] == val)
for (int j = 0; j < numValues; j++)
set[j] = set[j + 1];
}
numValues--;
}
You can figure out yourself why this is wrong by using a paper and pencil here. Start with a typical example: let's say you found the value you're looking for in the third element of a five-element array:
if (set[i] == val)
In this example, i would be set to 2, and numValues would be set to five. It doesn't matter what val is. Whatever it is, you found it when i is 2, and numValues is five: you found it in the third element of a five element array. Keep that in mind.
Now, you know that you are now supposed to remove the third element in this five element array. But what do you think will happen next:
for (int j = 0; j < numValues; j++)
set[j] = set[j + 1];
Well, using the aforementioned paper and pencil, if you work it out, the following will happen:
set[1] will be copied to set[0]
set[2] will be copied to set[1]
set[3] will be copied to set[2]
set[4] will be copied to set[3]
set[5] will be copied to set[4]
There are two problems here:
A) There is no set[5]. Recall that this is a five-element array, si you only have set[0] through set[4]
B) You're not supposed to copy everything in array down to one element. You have to copy only the elements after the element you want to remove.
Fix these two problems, and you will probably find that everything will work correctly.