Shifting Array Elements in c++ - c++

Write a program that uses an array of size eight (8) and then prompts
the user to input eight integers for the array. The program should do
the following:
Print the numbers in the output given in the sample Input/Output.
The user is prompted to enter an integer value k, the program will then shift the array elements k positions to the right, while the last
K elements are moved to the beginning of the array. For example: if
we have an array [1 2 3 4 5 6 7 8], shifting 2 positions to the right
should give the array [7 8 1 2 3 4 5 6].
I did this question but I got the output (if assumed number of shift = 3)
[1 0 3 1 2 3 4 5] which is wrong, the output should be [6 7 8 1 2 3 4 5]
This is my code, what is the mistake?
#include<iostream>
using namespace std;
int main()
{
int arrays[8];
int k;
cout<<"Enter Values for a Arrays of size 8"<<endl;
for(int i=0; i<8; i++)
{
cin>>arrays[i];
}
cout<<"You Entered Numbers are: [ ";
for(int i=0; i<8; i++)
{
cout<<arrays[i]<<" ";
}
cout<<" ]\n";
cout<<"Enter the Number of Shift: ";
cin>>k;
for(int i=8; i>0; i--)
{
arrays[i]=arrays[i-k];
}
//The Output
for(int i=0; i<8; i++)
{
cout<<arrays[i]<<" ";
}
return 0;
}

The error is in
for(int i=8; i>0; i--)
{
arrays[i]=arrays[i-k];
}
First of all when i<3 you get a negative index. You can solve this using the % operator which returns the reminder.
Secondly you are overwriting the values that still must be copied. For example suppose the shifting is 3: at the first iteration you copy the fifth element inside the eighth. But then you should also copy the eighth inside the third.
One simple solution is to declare a new array and do the following:
int shifted[8];
...
for (int i=0; i<8; i++)
{
shifted[i] = arrays[(i-k)%8]
}
Consider also using C++ vectors.

Related

Is there a way to use std::sort() and still maintain a 1 based indexing?

I want my array to maintain a 1 based indexing even after the sort() is completed. My code below gives me a garbage value at the last index when i = n because the loop should have been
for(int i = 0; i < n; i++) while printing the code after the sort is completed. Is there a way to use std::sort() and still maintain a 1 based indexing?
int n;
cin >> n; // 6
int a[n+1];
for(int i = 1; i <= n; i++)
cin >> a[i]; // INPUT ARRAY: 6 4 2 7 2 7
sort(a, a+n+1);
for(int i = 1; i <= n; i++)
cout << a[i] << " "; // OUTPUT AFTER SORTING: 2 4 6 7 7 6421920
Well yes, only sort starting from index 1.
std::sort(a+1,a+n+1);
Yes, there is a way. Just omit the dummy element when you call sort:
sort(a+1, a+n+1);

What are all of these numbers following the expected output?

I was trying to write a program to take an input and output the reverse of that input; here was my code:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int num[n];
for (int i=1; i<=n; i++)
{
cin >> num[i];
}
for (int i=n; i>=0; i--)
{
cout << num[i] << " ";
}
return 0;
}
I realized that in the second for loop, i can equal 0 and then i equals -1. However, the outputs don't really make sense. For example, an input of
6
8 1 2 6 3 9
results in
9 3 6 2 1 8 8 8
and a lot of the time it's just the array reversed but with an 8 added onto the end, but sometimes there are these types of numbers:
9
1 0 2 8 1 4 2 9 8
8 9 2 4 1 8 2 0 1 1703936
Where do these ending numbers come from? Because I don't understand what's going on, I can't generalize what the problem is, but if you have an easily-accessible IDE nearby and will copy and paste my code (assuming it's not a well-known problem and I'm making everyone laugh at my stupidity), could anyone tell me why there are these numbers added onto the end?
for (int i=1; i<=n; i++)
In C++, array indexes are 0-indexed. This means if your array is size n, the valid indexes are 0, 1, 2, ..., n-1.
Your loop will loop over 1, 2, 3, ..., n. Do you see the issue? You never write to the 0'th index, and you write one past the last index (which is not allowed).
Then when you go to print:
for (int i=n; i>=0; i--)
You print n, n-1, n-2, ..., 0. You're printing the n'th element, which is again, not allowed.
Instead, your loops should look like:
for (int i=0; i<n; i++)
{
cin >> num[i];
}
for (int i = 0; i < n; i++)
{
cout << num[n - i - 1] << " ";
}
Your second loop begins with i equal to n ... but that's not a valid array index, because an array containing n elements has indexes [0..n-1]! Therefore, you are seeing "memory garbage."
So, your second loop should be:
for (int i=n-1; i>=0; i--)
You seem to think that arrays are indexed from 1 which is your main issue.
for (int i=1; i<=n; i++)
The last element of an array if length-1, so if you had 3 elements the last index is 2, not 3; however, the loop above starts at 1 (the second element) and then accesses an index out of bounds, which is undefined behaviour.
But really you don't need to use indices at all, just for (auto& i : n) will iterate properly over your container. If you want to loop using indices, you need
for (int i = 0; i < n; i++) // forwards
for (int i = n-1; i >= 0; i--) //backwards
It's worth noting that variable length arrays (that is, arrays whose lengths are not known at compile time) are not standard C++, but are an extension of GCC. It would be worth ditching that behaviour now, and using vector instead:
int length = 0;
std::cin >> length;
std::vector<int> n(length);

Counting number of swaps by comparing adjacent elements in an array

I am trying to count number of swaps to sort the given array in ascending order. Inside the for loop I have a if condition to check the condition weather to swap or not , But inside if condition I have added a cout statement to check which elements are being compared, When I have that cout statement number of swaps printed are different, and when I remove that statement number of swaps printed are different, for sample:
if I have cout statement
Sample Input
1
4
4 1 2 3
and output came as
3
if I remove or comment that cout statement
Sample Input
1
4
4 1 2 3
and output came as
4
I can't figure out the reason for this.
#include <iostream>
using namespace std;
int main() {
int swap=0,t,n,arr[20],temp;
cin>>t;
while(t!=0) {
cin>>n;
for(int i = 0 ; i < n ; i++) {
cin>>arr[i];
}
for(int i = 0 ; i < n ; i++) {
if(arr[i]>arr[i+1]) {
swap++;
cout<<arr[i]<<">"<<arr[i+1]<<endl; //this cout statement
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
cout<<swap<<endl;
--t;
}
return 0;
}
Your result is non-deterministic since you are accessing a position of the array that should not be accessed, i.e. when i = n - 1, a[i+1] is trying to access a[n] that is "dirty" memory.
Furthermore I think that your algorithm does not do what you want it to do. I suggest you to read here before going further. From the right code, it's enough to add the counter (as you did) to obtain the correct result.

a function that takes an array A and index i and rearrange it

Question is: write a function that takes an array A of length n and an index i into A, and rearrange the elments such that all elements less than A[i] appear first, followed by elements equal to A[i], followed by elements greater than A[i].
explanation for my code:
Ask user for n numbers, which is 11. And ask him what the index that he wants to rearrange the elements with. It takes it to function1, and creates a for loop and does an if else statement. if A[i] < A{index} , place it in the begining, else if it's less, place it at the end, or place it in the middle:
Here is my code
#include <iostream>
using namespace std;
void function1(int a[], int ind);
int main()
{
int a[11];
int index;
cout << " enter the numbers: " << endl;
for(int i=0; i < 11; i++)
cin >> a[i];
cout << "what is the index ? " << endl;
cin >> index;
function1(a,index);
}
void function1(int a[], int ind)
{
int x = a[ind];
int newArray[11];
for(int i=0; i < 11; i++)
{
if(a[i] < x)
{
newArray[i] = a[i];
}
else if(a[i] > x)
{
newArray[10-i] = a[i];
}
else
{
newArray[10/2] = a[i];
}
}
for(int i=0; i<11; i++)
cout << newArray[i] << " ";
}
The output that I am expecting to get is the rearrangement of the new array which will probably look similar to this:
a[0....x....n-1], where x is the index that represents a[i]
however I am getting incorrect output with numbers randomly scattered across
what is wrong with my logic ?
The problem is that (like Olaf Dietsche pointed out) you take just one index where two are necessary. Further you can't know if the element that is neither smaller not bigger than a[ind] (means equal to a[ind]) is to be inserted in the middle of the new array. (Imagine 3 2 1 and index 3 results in 2 1 3 but 3 isn't in the middle!)
Updated Version (allows for multiple elements with same value as pivot element)
void rearange(int* data, int size, int pivot)
{
int* temp_data = new int[size];
int start_index = 0, end_index = size - 1;
for (int i = 0; i < size; i++)
{
if (data[i] < data[pivot]) // -> insert 'before' pivot element
{
temp_data[start_index] = data[i];
start_index++;
}
else if (data[i] > data[pivot]) // -> insert 'behind' pivot element
{
temp_data[end_index] = data[i];
endIndex--;
}
// else: skip pivot(s)
}
// insert pivot element(s)
for (int i = start_index; i <= end_index; i++)
{
temp_data[i] = data[pivot];
}
for (int i = 0; i < size; i++)
{
std::cout << temp_data[i] << " ";
}
delete[] temp_data;
}
Input:
11 10 9 8 7 7 7 6 5 4 3
5
Output
6 5 4 3 7 7 7 8 9 10 11
As you see, all elements smaller than element 5 (with value of 7) are before, all elements greater are behind the pivot element. All other elements with same value as pivot are wrapped around position 5, wherever there's free space. However the rearranged elements are not yet sorted (apart from being positioned relative to pivot element)!
You use the same index i for the smaller and larger values. This means, if only the last value a[10] is larger than x, you will write it in the first location newArray[10 - 10], even though you already filled all places up to the 10th. Another problem is, when you have multiple middle values. They will all be stored into newArray[5].
What you want to achieve is called partitioning, as used in the quicksort algorithm.
You need to maintain two indexes (pointers), one for the smaller (left) and one for the larger (right) values.
You have to determine the size of your array at the beginning and pass the fixed size of the array to the function as a parameter.

Number of a row consisting of the same set of numbers as another row C++

OK guys, I have this problem where I have to print the number of the rows of a matrix that are composed from the same set of numbers as the number of a row I input. For example:
Input:4 5 3
1 2 2 3
2 4 1 3
1 1 1 3
3 1 1 2
3 1 3 2
Output:0 4
Note that we first input the number of the columns,then the rows and then the row k.
I get on the input only the 0 and can't figure why? I think my logic is ok, but who knows I'm new to programing. So if you could tell me where my mistake is that would be great. Here is my code:
#include<iostream>
using namespace std;
int const l=50;
int main ()
{
int n,m,k,br=0,br2=0;
bool t1=false;
bool t2=false;
cin>>n>>m>>k;
int a[l][l];
for(int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
cin>>a[i][j];
}
for(int i=0;i<m;i++)
{
for(int p=0;p<n;p++)
{
for(int j=0;j<n;j++)
{
if(a[k][p]==a[i][j])
{
br++;
}
}
if(br==0)
{
t1=true;
}
br=0;
}
for(int j=0;j<n;j++)
{
for(int p=0;p<n;p++)
{
if(a[i][j]==a[k][p])
{
br2++;
}
}
if(br2==0)
{
t2=true;
}
br2=0;
}
if(t1==false && t2==false && i!=k)
{
cout<<i<<" ";
}
}
}
Here is my solution for you. From a high level viewpoint, the basic task is that you want to do a bunch of comparisons between members within an array. I'm not really sure of your code, so here is my own unique solution for you.
step 1 - find all the members of the array row or column that you are interested in, and add them to your list. if you know the sizes of everything than use an array, if not then use a vector. lets call this 1d array memberlist[]
step 2 - loop through memberlist[] and search for each member of memberlist within a every row/column. For this example lets say you are interested in rows, not that there is any real difference.
step 3 - make yet another int array which we will call matchlist[]. matchlist should have a length equal to the number of rows in the array you are comparing with. initialize every value in matchlist to zero.
step 4 - every time you have a hit from the memberlist[] comparing to the rows, add 1 to the corresponding row's score sheet in matchlist.
at the end of the first loop, you should have checked every row for every member of the row you are trying to match it with, and you will get a score for each one contained within matchlist[]. choose the ones with the score you can accept, whether or not thats the full length of memberlist[] or maybe 3 out of 4.
int rowsize = 5;
int columnsize = 5;
//step 1
testarray[rowsize][columnsize] = {whatever you want};
//choose row
cin>>row;
int i;
int j;
int memberlist[rowsize] = {0};
for(i = 0; i < rowsize; i++){
memberlist[i] = testarray[i][columnsize]
}
//memberlist is programmed
int tempid;
int membercounter;
int tempmember;
int matchlist[columnsize];
// step2 & 3
for (membercounter = 0; membercounter < rowsize; membercounter++){
tempmember = memberlist[membercounter];
for(i=0;i<columnsize;i++){
for (j=0;j<rowsize;j++)
tempid = temparray[j][i];
//step 4
if ( tempid == tempmember){matchlist[i]++;}
}
}
}
// use some code to cout the columns based on the matchlist score
for (i=0; i< columnsize; i++)
{ printf( "matchlist[%d] has a score of %d \n", i,matchlist[i]);}
//or whatever you want.
I hope this helps. Cheers.