How to delete an Array with negative integers - c++

I was trying to solve the following problem,
Given an array of integers, every element appears three times except
for one. Find that single one.
When the input are all positive, I will not get any errors, but when the input contains negative integers, the line delete index; will give error, does anybody know why?
i.e.
A[] = {1,2,3,4,1,2,3,4,1,3,4} works fine, but A[] = {-2,-2,1,1,-3,1,-3,-3,-4,-2} does not.
The code is as follow,
#include <iostream>
#include <map>
class Solution {
public:
int singleNumber(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int *index;
std::map<int, int> m;
index = new signed int[(n+1)/3];
int flag = 0;
int result;
for(int i=0; i<n; i++) {
if(m.find(A[i]) == m.end()) {
m[A[i]] = 1;
index[flag] = A[i];
flag++;
} else {
m[A[i]] = m[A[i]] + 1;
}
}
for(int i=0; i<(n+1)/3; i++) {
if(m[index[i]] != 3) {
result = index[i];
}
}
delete index;
return result;
}
};
int main()
{
Solution s;
int A[] = {1,2,3,4,1,2,3,4,1,3,4};
int result = s.singleNumber(A, 11);
std::cout <<result;
return 0;
}

The first array contains 11 elements, which causes the line index = new signed int[(n+1)/3]; to allocate an array of (11+1)/3 = 4 elements. The second array contains 10 elements, which causes that line to allocate an array of (10+1)/3 = 3 elements.
3 elements is insufficient to record the unique values in A (-4, -3, -2, and 1), so you overflow the array.
You should allocate at least (n+2)/3 elements. It would also be prudent to test the value of flag to ensure it never exceeds the array bounds. It will not if the input array obeys the constraint that every element but one appears three times (presuming this means it will appear one or two times, not four or more), but can you rely on that constraint being obeyed?
Additionally, the loop for(int i=0; i<(n+2)/3; i++) is insufficient to iterate through all the elements that were added to the map. You should be sure you iterate through all the members of m.
Incidentally, singleNumber can be implemented in a much more fun way without any dynamic allocation or library calls:
int singleNumber(int A[], int n) {
int b = 0, c = 0;
while (n--)
{
b ^= A[n] & c;
c ^= A[n] & ~b;
}
return c;
}
However, this is completely not what your instructor is expecting.

Related

Program works fine with small arrays, but it is suspended when the arrays get larger. How to allocate memory to large arrays?

I'll explain my code first before going into my question in more details.
The program will continue to count the next number until the nth number is generated, and then print out that number.
Here's how it works.
With a given sequence of starting numbers, for example, 0,3,6
The 1st number is 0.
The 2nd number is 3.
The 3rd number is 6.
Now, consider the last number, 6. Since that was the first
time the number had been spoken, the 4th number spoken is 0.
(if the last number has been spoken before, then, the next number
is the difference between the turn number when it was last spoken
and the turn number of the time it was most recently spoken before
then. )
since the last number, which is the 4th number (0) has been
spoken before, the most recent place where 0 appears before the last
number is turn 1. Therefore, the 5th number is 4 - 1, which is 3.
...keep counting until the nth number.
My code works fine when n is 2022, but the program stop running when n = 30,000,000
The is how I allocate memory to my arrays
int *test_case_one = new int[30000000];
Below is my entire code
#include <iostream>
#include <string>
using namespace std;
void test_cases( int Array[]);
int isfound( int table[], int current, int range);
int main()
{
int *test_case_one = new int[30000000];
test_case_one[0] = 1;
test_case_one[1] = 3;
test_case_one[2] = 2;
test_cases(test_case_one);
delete[] test_case_one;
}
void test_cases( int Array[])
{
int *table = new int[30000000];
int turn;
int last;
table[0] = Array[0];
table[1] = Array[1];
table[2] = Array[2];
table[3] = 0;
for ( int i = 4; i < 30000000; i++)
{
last = table[i -1];
turn = isfound(table, last, i);
if ( turn != -1) {
table[i] = (i-1) - turn;
}
else {
table[i] = 0;
}
}
cout<< table[29999999] << endl;
delete[] table;
}
int isfound( int table[], int last, int range)
{
for ( int j = range-1; j > 0 ; j--) {
if ( last == table[j -1]) {
return (j - 1);
}
}
return -1;
}
How can I fix this memory overload issue?
You should not build a table of the values, but a table of last rank per value, initialized to 0. That way when you get a value, you have a direct access to next value and you algo become simply linear.
If you are sure that none of the initialization values will be greater than the expected number of iterations, then everything is fine because as other values will be index differences, this will also be less than that number.
Here is a simple code for your 0-3-6 example:
#include <iostream>
int main()
{
int number;
std::cout << "Total number (>=7): ";
std::cin >> number;
if (!std::cin || number < 5) return EXIT_FAILURE;
// 3 initial values are 0, 3, 6, so 4th will be 0
int* data = new int[number];
for (int i = 0; i < number; i++) data[i] = 0;
data[0] = 1;
data[3] = 2;
int val = 6;
for (int index = 3; index <= number; index++) {
int newval = data[val] ? index - data[val] : 0;
data[val] = index;
val = newval;
// uncomment next line to see intermediary values
//printf("%d: %d\n", index + 1, val);
}
delete[] data; // always release dynamic objects...
printf("Final %d: %d\n", number, val);
return 0;
}
BTW, in modern C++ you should rarely directly allocate a raw array with new, precisely because if you do, you will be responsible for its deletion. It is much more common and easy to use standard containers, here a std::vector. (Thanks to #EtiennedeMartel for the remark).

Finding Duplicates in a array - Syntax Explanation

I don't have any idea about this syntax int *count = new int[sizeof(int)* (size - 2)]
What kind of array that will create.
I thought they are trying to create map like structure. But how does it work?
#include <bits/stdc++.h>
using namespace std;
void printRepeating(int arr[], int size)
{
int *count = new int[sizeof(int)*(size - 2)];
int i;
cout << " Repeating elements are ";
for(i = 0; i < size; i++)
{
if(count[arr[i]] == 1)
cout << arr[i] << " ";
else
count[arr[i]]++;
}
}
// Driver code
int main()
{
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printRepeating(arr, arr_size);
return 0;
}
// This is code is contributed by rathbhupendra
Finding duplications in an array is of course a solved problem. IMHO a very simple solution is:
sort the array use std::sort()
use a loop to check if an element is equal to it's successor, ie. for(int i = 1; i < num_elements; i++){ if(arr[i-1]==arr[i]){...duplicate!...}}
This requires O(n) memory and O(n*log(n)) time, so it's quite ok. You can also use a hashmap, but that's pretty much the same.
Anyways, to your question(s):
int *count = new int[sizeof(int)* (size - 2)];
This is incorrect. I assume it used to be this C code:
int num_elements = size-2; // we want size-2 elements (not sure why)
int total_bytes = sizeof(int) * num_elements;
int *count = calloc(total_bytes); // reserve space, and set to 0
Which one could translate to this C++ code:
int num_elements = size-2;
int * count = new int[num_elements]{0}; // alloc and set to zero
So the person who did the port misunderstands fundamentals about C++.
Let's dig further.
For the sake of it, the problem formulation appears to be:
You are given an array of n+2 elements. All elements of the array
are in range 1 to n. And all elements occur once except two
numbers which occur twice. Find the two repeating numbers
I have made tiny changes to make the solution less crazy, and I've added annotations.
// #include <bits/stdc++.h> is a bad choice.
// This includes _EVERYTHING_ in C++,
// but it only works in GCC afaik. For this particular
// case we just need cout, so:
#include <iostream>
// using the std namespace like this spills function calls like crazy in the global namespace.
// it is both, conventient and "not too bad" (imho) in cpp files,
// but never ever do this in .h files where it affects multiple cpp files.
using namespace std;
void printRepeating(int arr[], int size)
{
// create a new array of size-2 and set to zero
int *count = new int[(size - 2)]{0};
int i;
cout << " Repeating elements are ";
// loop all elements
for(i = 0; i < size; i++)
{
int value = arr[i];
// increase the count for `value`
// note that if value<=0 or value>size-2,
// then the program will crash!
// the problem description is contrived, but it does
// state that all values need to be >0 and <=size-2,
// so this next array access is fine!
count[value-1]++;
// we still have to subtract 1, because C arrays start
// at index 0, but our problem description says we start at 1.
// we could also create an array of size-1 and
// "ignore" the first position in count[0] (it would never get used!)
// if the element appears the second time...
if(count[value-1] == 2){
// then print it
cout << value << " ";
// btw: if you check with count[value-1]==2, then only
// the first duplicate is printed.
// you could compare with count[value-1]>=2 then all
// repeating elements are printed repeatetly.
}
}
// free up the memory. we allocated with `new[]`
// so we also have to use `delete[]`
delete [] count;
}
// Driver code
int main()
{
int arr[] = {4, 2, 4, 5, 2, 3, 1};
// next line is a standard trick.
// a single int consumes 4bytes (typically),
// the array will have size 7*4=28 bytes, so sizeof(arr)=28
// the first element is an int, so sizeof(arr[0]) = 4
// so sizeof(arr)/sizeof(arr[0]) = 7
// c and c++ don't have arr.length like java,etc., that's
// why under certain circumstances this "trick" is used.
int arr_size = sizeof(arr)/sizeof(arr[0]);
// call the function
printRepeating(arr, arr_size);
return 0;
}
// This is code is contributed by rathbhupendra.
// Maybe fixed and annotated by hansi:)
I hope this helps you and answers some questions. Good luck with your C++ adventures!

How to remove integers in array less than X in C++?

I found the same question for PHP and I tried to do the same in C++.
I tried following:
// returns new array with numbers lower then "number", len is set to
// new length.
int * filter(int array[], int &len, int number) {
int cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
cnt++;
}
}
int *ret = new int[cnt];
cnt = 0;
for (int i = 0; i < len; i++) {
if (array[i] < number) {
ret[cnt] = array[i];
cnt++;
}
}
len = cnt;
return ret;
}
This function will create a new array with the integers that are lower than the integer number. I tried to bypass the problem that I don't know how long the new array should be.
Is there any better way to solve this problem?
Yes, use std::vector type. It will automatically handles allocations for you each time you push value to it (using push_back method).
Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
for (int value : a) {
std::cout << value << '\n';
}
}
It's also a good idea to avoid new syntax, as it doesn't automatically deallocate, unlike std::vector.
Also, while this is unrelated to question, C++ provides a function that does what you want already called std::copy_if.
std::remove is the algorithm you're looking for.
#include <iterator>
#include <algorithm>
int main()
{
int array[4] = {1, 42, 314, 42};
// If you only know `array` as a pointer, and `len`, then
// `std::begin(array)` becomes `array`, and
// `std::end(array)` becomes `array + len`.
auto end = std::remove(std::begin(array), std::end(array), 42);
// Now `end` points to the "new end" of the array.
// And `std::distance(std::begin(array), end)` is the "new length".
}
It moves all matched elements (42 in the example) to the end of the array. When inspecting array after std::remove runs, you get {1, 314, 42, 42}, and end points past the last nonmatching element (the first 42 in this case).
It's also possible to copy the nonmatching elements to another array using std::remove_copy, or std::copy_if, but in order to do this, you'll have to allocate another array of elements. At this point, you're better off using a dynamic growing array such as std::vector. In that case, use std::vector::erase like here in the answers with std::remove.

Checking if an index of an array is empty

I'm currently trying to write a script so that I can add an item to the last index the array has an item in. For example, if I initialized an array int a[5] and a[0], a[1], a[2] all have something, then the integer would be added to a[3]Here is what I have :
int main(){
int a[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
for (int i = 0; i < 5; i++){
if (a[i] < 0){
a[i] = 40; //Just an example for what it would be like.
}
}
}
I can't help but feel that there is a better way to do this, maybe a different if condition. I want to know if there's another way to check if the next index is empty.
You could use an array index counter. Say, int counter = 0;
Use the counter as an index when you store integers to the array a, like a[counter] = 5 After you add an integer to your array, increment the counter, counter++.
This way you could make sure that the next value being added to the array is always added the way you described in the question
A few things to probably clear up what looks like a misunderstanding around what an array is:
When you declare an array say
int main()
{
int a[5];
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
All elements in the array exist already. Namely, you can access a[0] ... a[4] without hitting an error. All values of the array have already been set implicitly and you can see this by seeing the output of the printf. Note that those are values that you haven't set yourself and will vary. If you're curious about why they vary, you can see this: Variable initialization in C++
To set those values explicitly, you can initialize all values in the array to 0 like so:
int main()
{
int a[5] = {0};
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
or through use of a static initializer
int main()
{
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
printf("a[%d] = %d", i, a[i]);
}
}
However because all values of the array already exist on creation, there isn't really such a state as "uninitialized array" in C++ as they are . The value of a[3] is either set implicitly or explicitly depending on how you created the array.
std::vector is a dynamically growing array, based on how much space you need. In order to have this effect, std::vector keeps track of how much of the array is "used" through use of a size variable. If you wanted to reimplement that to get an idea of how it might be done, you would probably want a class like:
class MyArray
{
public:
MyArray() : m_size(0)
{
}
void AddVal(int data)
{
if (m_size < 5)
{
m_array[m_size++] = data;
}
}
int GetSize()
{
return m_size;
}
private:
int m_array[5];
int m_size;
}
If you initialize the array to 0, you can check if the value is 0.
Initilize:
int array[5] = {0};
Check for 0:
array[4] == 0;

Convert one dimensional array to two dimensional array

For my homework it is given one dimensional array and i have to convert it in a two dimensional array. The two dimensional array has 2 for the number of columns, because i have to represent the one dimensional array as pairs(the value of the number, the number of appearences in the array).
This is what have tried. The error appears on the last 2 lines of code: access violation writing location 0xfdfdfdfd.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
const int NR=17;
int arr[NR]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5};
int **newArr;
int count=0;
int countLines=0;
int searched;
for(int i=0;i<NR;i++)
{
newArr=new int*[countLines];
for(int i=0;i<countLines;i++)
{
newArr[i]=new int[2];
}
searched=arr[i];
if(i>0)
{
for(int k=0;k<countLines;k++)
{
if(newArr[countLines][0] == searched)
{
searched=arr[i]++;
}
for(int j=0;j<NR;j++)
{
if(searched==arr[j])
{
count++;
}
}
countLines++;
}
}
else
{
for(int j=0;j<NR;j++)
{
if(searched==arr[j])
{
count++;
}
}
countLines++;
}
newArr[countLines][0]=searched;
newArr[countLines][1]=count;
}
}
First you are using newArr in the first loop before allocating it any memory. You cannot dereference a pointer which owns no legal memory. It results in undefined behavior.
Secondly in the last part, you are allocating newArr a memory equal to countLines thus.
newArr = new int*[countLines] ;
It means that the indices in the first dimension of newArr are 0------>countLines-1. Doing newArr[countLines][0] = searched ; is again undefined. Make it newArr[countLines - 1].
I'm not going to bother with a line-by-line code analysis since (a) you're changing it while people are answering your question and (b) it would literally take too long. But here's a summary (non-exhaustive) of klunkers:
You are leaking memory (newArr) on each loop iteration starting with the second.
You're out-of-bounds on your array access multiple times.
You should not need to use a pointer array at all to solve this. A single array of dimension [N][2] where N is the number of unique values.
One (of countless many) way you can solve this problem is presented below:
#include <iostream>
#include <algorithm>
int main()
{
// 0. Declare array and length
int arr[]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5};
const size_t NR = sizeof(arr)/sizeof(arr[0]);
// 1. sort the input array
std::sort(arr, arr+NR);
/* alternaive sort. for this input size bubble-sort is
more than adequate, in case your limited to not being
allowed to use the standard library sort */
/*
for (size_t i=0;i<NR;++i)
for (size_t j=i+1;j<NR;++j)
if (arr[i] > arr[j])
{
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
*/
// 2. single scan to determine distinct values
size_t unique = 1;
for (size_t i=1;i<NR;++i)
if (arr[i] != arr[i-1])
unique++;
// 3. Allocate a [unique][2] array
int (*newArr)[2] = new int[unique][2];
// 4. Walk array once more, accumulating counts
size_t j=0;
newArr[j][0] = arr[0];
newArr[j][1] = 1;
for (size_t i=1;i<NR;++i)
{
if (arr[i] != arr[i-1])
{
newArr[++j][0] = arr[i];
newArr[j][1] = 0;
}
++newArr[j][1];
}
// 5. Dump output
for (size_t i=0;i<unique;++i)
cout << newArr[i][0] << " : " << newArr[i][1] << endl;
delete [] newArr;
return EXIT_SUCCESS;
}
Output
1 : 3
2 : 1
3 : 2
4 : 3
5 : 3
6 : 3
7 : 2