Moving array elements over one position - c++

I have a homework assignment where we're supposed to create a list of integers, and allow the user to INSERT an integer at a given position in the list. The list should essentially move all integers over one position in the array, then insert the integer that the user input at the index they chose.
So let's say I have an array of {1, 2, 3, 4, 5} and I want to put 9 in index 1, the array should then be {1, 9, 2, 3, 4, 5}.
I thought I figured out the solution with this function:
void *INSERT(int count, int userNum, int index, int array[]){ //Accepts count of array, users number, users index, and array
int tempIndex = index;
index--;
for(int counter = 0; counter < count; counter++)
{
array[tempIndex] = array[tempIndex-1];
tempIndex++;
}
array[index] = userNum;
}
Here is what I have in the main function:
int index = 0; //Hold users index selection
int userNum = 0; //Hold users number
int n = 10;
int a[n] = {1, 2, 3, 4, 5};
int *ptr = a;
cout << "Enter a number to insert: ";
cin >> userNum;
cout << "Enter an index: ";
cin >> index;
INSERT(n, userNum, index, ptr);//call insert function (Accepts count of array, users number, users index, and array)
int listNum = 1;
for(int i = 0; i < n; i++) {
cout << listNum << ". " << a[i] << "\n";
listNum++;
}
However, this is the output after printing the array:
1. 1
2. 9
3. 2
4. 2
5. 2
6. 2
7. 2
8. 2
9. 2
10. 2
I'm not sure where I'm going wrong here that could be causing this output. If I remove the -1 from the INSERT functions for loop like this(commented it out to make it more clear on what's being changed):
void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array
int x = i;
i--;
for(int r = 0; r < c; r++)
{
a[x] = a[x/*-1*/];
x++;
}
a[i] = n;
}
I get the following output with the above code, which is what I'd expect but not what I need. I can post the entire code if needed as well, but I think this explains where the problem is. Thanks in advance for the help
1. 1
2. 9
3. 3
4. 4
5. 5
6. 0
7. 0
8. 0
9. 0
10. 0

Based on your code, just change your insert function to this -
Here we first shift the values to next index in the array and then perform insertion of respective element
void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array
for(int r = c-1; r >= i; r--)
{
a[r+1] = a[r];
}
a[i] = n;
}

This answer may be somewhat controversial because instead of directly solving your assignment for you I'm just telling you how to debug it so you can solve it yourself.
So fixed your code for you:
//Accepts count of array, users number, users index, and array
void *INSERT(
int array_size,
int number_to_insert,
int insert_at,
int numbers[]){
int moving_index = insert_at;
insert_at--; // Why are you doing this?
for(int r = 0; r < array_size; r++)
{
// moving_index was initialized as insert_at
// What happens when insert_at is 0?
// What happens when moving_index >= array_size?
// Who knows...
numbers[moving_index] = numbers[moving_index-1];
// You're incrementing moving_index.
moving_index++;
// What would numbers[moving_index-1] be now?
}
numbers[insert_at] = number_to_insert;
}
Once you answer my questions, I'm sure you'll be able to figure it out.

Related

Difficulty understanding code to count the number of inversions using BIT

Here is the code:
#include<iostream>
using namespace std;
const int MX = 100;
int n,a[MX*2],bit[MX];
void add(int x, int y){
for(;x<=n; x+=-x&x) bit[x]+=y;
}
int query(int x){
int s= 0;
for(;x>0; x-=-x&x) s+=bit[x];
return s;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int ans = 0;
cin >> n; n*=2;
for(int i = 0; i<n; i++){
cin >> a[i];
}
for(int i = n-1; ~i; i--){
ans+=query(a[i]-1);
add(a[i],1);
}
cout << ans;
}
I dont understand how the query and add contribute to finding the number of inversions in an array. If someone can help explain this to me that would be great. Thanks.
Firstly, I hope you understand how add and query work in BIT. If not, think of BIT like a blackbox which stores prefix sums for count of elements 1, 2, ..., n in array A. For example, A[3] = count(1) + count(2) + count(3). add(x, y) increments count(x) by y and query(x) returns the sum count(1) + count(2) + ... + count(x) i.e., the prefix sum till element x.
Elements at index i and j form an inversion if i < j and arr[i] > arr[j]. But the above code reads it the other way; j > i and arr[j] < arr[i] (this save an extra call to query).
Now suppose the array is {3, 4, 1, 5, 2} and {2, 5, 1} have already been inserted in the BIT. Then query(1) = 1, query(2) = 2, query(3) = 2, query(4) = 2 and query(5) = 3 (remember to think of BIT as a blackbox that stores prefix sums). Notice when index i is pointing at element 4, all the elements that have already been inserted having indices j1, j2, ..., jk are all > i so now we only need to count the number of elements < 4 which is the prefix sum till 3 which we get by calling query(3).

C++ array operations

I want from the program to add 3 to elements which are greater than 3 and print them. It takes so much time that I couldn't see the result. Also, when I change n to 8 in loops directly, it gives a result; however, it's not related with what I want. How can I correct this code and improve that?
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n= sizeof(a);
for( int i=1; i<=n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i]= a[i];
}
}
for (int i = 1; i <= n; i++)
cout << b[i];
return 0;
}
The sizeof() function (int n = sizeof(a)) gives 32 because array 'a' contains 8 elements & each element is of 'int' type whose size is 4 byte in memory thats why it returns 32 in 'n' variable.so you must divide the value of 'n' with the size of integer.
Secondly the index of array starts with the zero '0' to one less than the length of array not with the 1 to length of array .
Try the below code ! I am also attach the output of the code .
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a[8] = { -5, 7, 1, 0, 3, 0, 5, -10 };
int b[8];
int n = sizeof(a)/sizeof(int);
for (int i = 0; i < n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i] = a[i];
}
}
for (int i = 0; i < n; i++)
cout << b[i]<<endl;
return 0;
}
The statement in your program int n=size(a) returns the total bytes occupied in memory for a. i.e int occupies 4 bytes and a is an array contains 8 elements so 8X4 = 32 .but while accessing the array elements using loop you are specifying i<=n meains i<=32 but there is only 8 elements but you are trying to access 32 elements which indicates that you are trying to access the elements more than 8.
exeutes the following code
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n=sizeof(a);
cout<<"\n Value of n is : "<<n;
return 0;
}
Output
Value of n is : 32
if you specify the exact number of array size your program will work properly.
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 6, 0, 8, -10};
int b[8];
for( int i=1; i<8; i++)
{
if (a[i]>3)
{
b[i] = a[i] + 3;
}
else
{
b[i]= a[i];
}
}
cout<<"\n Values in a array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<a[i];
cout<<"\n Values in b array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<b[i];
return 0;
}
OUTPUT
Values in a array
-----------------
7 1 0 6 0 8 -10
Values in b array
---------------
10 1 0 9 0 11 -10
I hope that you understand the concept.Thank you
Your int n = sizeof(a); doesn't works as you intend.
I think you want to get the size of array (i.e. 8).
But you gets the size in bytes of elements (e.g. 32, integer size or could be different depending of your system's architecture).
Change to int n = 8, will solve your problem.
Also note that for( int i=1; i<=n; i++) will get an "out of array" element.
Sizeof function gives the value of the total bits of memory the variable occupy
Here in array it stores 8 integer value that has 2bit size for each thus it returns 32

C++ Array Inputing and Reversing Values

For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<std::endl;
}

Regarding pointers and arrays and how they are assigned in memory in C++

So I am trying to solve this question:
Data is fed in the following input format. The first line contains two space-separated integers denoting the number of variable-length arrays, n, and the number of queries, q. Each line of the subsequent lines contains a space-separated sequence in the format
k Ai[0] Ai[1] … Ai[k-1]
where k is the length of the array, Ai, and is followed by the k elements of Ai. Each of the subsequent lines contains two space-separated integers describing the respective values of array number (ranging from 0 to n-1) and index in that particular array (ranging from 0 to ki) for a query. i.e, Given the following input:
3 3
3 1 2 3
5 4 5 6 7 8
4 9 10 11 12
0 1
1 3
2 0
This output is expected
2
7
9
I am basically a beginner in C++. This is the code I have tried but I feel the address at which each subsequent array is stored is giving me some problems
int main(){
int n, q;
scanf("%d %d", &n, &q);
printf("n,q = %d, %d\n", n, q);
int* row[n];
for (int i = 0; i < n; i++){
int k;
scanf("%d", &k);
printf("k = %d\n", k);
int col[k];
row[i] = col;
for (int j = 0; j < k; j++){
int elem;
scanf("%d", &elem);
printf("i,j,elem = %d, %d, %d\n", i, j, elem);
col[j] = elem;
cout << "address is " << &(col[j]) << "\n";
}
}
for (int query = 1; query <= q; query++){
int i, j;
scanf("%d %d", &i, &j);
int answer;
answer = *(row[i] + j);
printf("row[%d][%d] is %d\n", i, j, answer);
cout << "address is " << &answer << "\n";
}
return 0;
}
And this is the output produced:
n,q = 3, 3
k = 3
i,j,elem = 0, 0, 1
address is 0x7ffe236edb70
i,j,elem = 0, 1, 2
address is 0x7ffe236edb74
i,j,elem = 0, 2, 3
address is 0x7ffe236edb78
k = 5
i,j,elem = 1, 0, 4
address is 0x7ffe236edb60
i,j,elem = 1, 1, 5
address is 0x7ffe236edb64
i,j,elem = 1, 2, 6
address is 0x7ffe236edb68
i,j,elem = 1, 3, 7
address is 0x7ffe236edb6c
i,j,elem = 1, 4, 8
address is 0x7ffe236edb70
k = 4
i,j,elem = 2, 0, 9
address is 0x7ffe236edb60
i,j,elem = 2, 1, 10
address is 0x7ffe236edb64
i,j,elem = 2, 2, 11
address is 0x7ffe236edb68
i,j,elem = 2, 3, 12
address is 0x7ffe236edb6c
row[0][1] is 32766
address is 0x7ffe236edbcc
row[1][3] is 32766
address is 0x7ffe236edbcc
row[2][0] is 3
address is 0x7ffe236edbcc
Basically, I find that the array addresses are overlapping. Also, The answer computation by dereferencing is resulting in unexpected outputs. Any explanation to the mistakes made here would be appreciated.
Here is a major problem:
for (int i = 0; i < n; i++){
...
int col[k];
row[i] = col;
...
}
The variable col has its scope only inside the loop. Once the loop iterates the variable cease to exist. Storing a pointer to it will lead to undefined behavior when you try to dereference the pointer.
The simple solution is probably to dynamically allocate memory for col using malloc.
Missed that the question was tagged C++, and confused because the source doesn't actually use any C++-specific code. This kind of makes it worse since variable-length arrays are not part of C++. Some compilers have it as an extension, but you should not use it when programming in C++.
Instead you should be using std::vector and then you can easily solve your problem without your own dynamic allocation. Then you can make row a vector of vectors of int and col a vector of int, and then the assignment will work fine (if row have been set to the correct size of course).
An easy way to use C++ without getting too many memory management bugs is to use standard library types. Leave the bare metal stuff to the poor C guys who do not have that ;)
So instead of meddling with new[] and delete[], use types like std::vector<> instead.
The "modern C++" version below uses iostream for no good reason. Old stdio.h is sometimes the preferred choice and so is sometimes iostream. And sometimes it is just a matter of style and taste.
#include <vector>
#include <iostream>
#include <fstream>
typedef struct Q
{
int iArray;
int iIndex;
} Q_t;
typedef std::vector<std::vector<int> > Data_t;
typedef std::vector<Q_t> Query_t;
bool Load(Data_t& data, Query_t &queries, std::istream& is)
{
size_t ndata = 0;
size_t nqueries = 0;
is >> ndata;
is >> nqueries;
data.resize(ndata);
queries.resize(nqueries);
for (size_t d = 0; d < ndata; d++)
{
size_t l = 0;
is >> l;
data[d].resize(l);
for (size_t i = 0; i < l; i++)
{
is >> data[d][i];
}
}
for (size_t q = 0; q < nqueries; q++)
{
is >> queries[q].iArray;
is >> queries[q].iIndex;
}
return true;
}
int main(int argc, const char * argv[])
{
std::ifstream input("E:\\temp\\input.txt");
Data_t data;
Query_t queries;
if (Load(data, queries, input))
{
for (auto &q : queries)
{
std::cout << data[q.iArray][q.iIndex] << std::endl;
}
}
return 0;
}
The mistake is, you have used 'col' array which loses its scope after completion of for loop. The way you can fix this is by either using dynamic memory allocation or by declaring it outside the for loop
Hope the below code will help you get an idea :)
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, q;
cin >> n;
cin >> q;
int* row[n];
int* col;
for(int i=0; i<n; i++)
{
int k;
cin >> k;
col = new int[k];
row[i] = col;
for(int j=0; j<k; j++)
{
cin >> col[j];
}
}
for(int query=0; query<q; query++)
{
int i,j;
cin >> i;
cin >> j;
cout << row[i][j] << endl;
}
delete[] col;
return 0;
}

Sorting an array to another array C++

My program have to sort an array in another array.
When I run the program it prints 1 2 3 -858993460 5 -858993460 7.
I can not understand where the mistake is in the code.
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[N];
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1] = arr[j];
}
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
return 0;
}
Okay lets face the problems in your code.
The "weird" numbers you see there, came from the uninitialzied array sort_arr. What do I mean by uninitialized? Well sort_arr is a little chunck somewhere in your memory. Since a program usually does not clear its memory and rather claims the memory it used as free, the chunk of sort_arr may contain bits and bytes set by another program. The numbers occure since these bytes are interpreted as an integer value. So the first thing to do would be to initialize the array before using it.
sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
Now why did these numbers occure? Well you're probably expecting your algorithm to set all values in sort_arr which would result in an sorted array, right? Well but your algorithm isn't working that well. See this line:
sort_arr[arr[j] - 1] = arr[j];
What happens when j is 1? arr[1] is then evaluated to 17 and 17 - 1 equals 16. So sort_arr[arr[1] - 1] is the same as sort_arr[16] which exceeds the bounds of your array.
If you want to program a sorting algorithm by your self than I would recommend to start with an simple bubble sort algorithm. Otherwise, if you only need to sort the array have a look at the algorithm header. It is fairly simple to use:
#include <iostream>
#include <algorithm>
#include <iterator> // << include this to use begin() and end()
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
copy(begin(arr), end(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
cout << endl;
}
By the way. You're looking for the biggest value in your array, right? After you have sorted the array sort_arr[N - 1] is the biggest value contained in your array.
If you want to sort a array into another array then one way is you make a copy of the array and then use the sort function in the standard library to sort the second array.
int arr[10];
int b[10];
for(int i=0;i<10;i++)
{
cin>>arr[i];
b[i]=arr[i];
}
sort(b,b+10);
// this sort function will sort the array elements in ascending order and if you want to change the order then just add a comparison function as third arguement to the sort function.
It seems that you think that sort_arr[arr[j] - 1] = arr[j] will sort arr into sort_arr. It won't.
Sorting is already written for you here: http://en.cppreference.com/w/cpp/algorithm/sort You can use that like this:
copy(cbegin(arr), cend(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
Live Example
My guess is this is an attempt to implement a type of counting sort. Note that variable length arrays aren't normally allowed in C++ or some versions of C. You could use _alloca() to allocate off the stack to get the equivalent of a variable length array: int * sort_arr = (int *)_alloca(max * sizeof(int)); .
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
// assuming range of values is 1 to ...
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[max];
for (int i = 0; i < max; i++)
{
sort_arr[i] = 0;
}
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1]++;
}
for (int i = 0; i < max; i++)
{
while(sort_arr[i])
{
cout << i+1 << " ";
sort_arr[i]--;
}
}
return 0;
}