So I have written a small program that calculates A[0]*B[0] - A[1]*B[1] - A[2]*B[2] - ... - A[n-1]*B[n-1] using vectors.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
double CalcProduct(vector<double> v1,vector<double> v2){
size_t size; int i = 0;
vector<double> product;
double input, input2;
cout << "Enter vector size: ";
cin >> size;
cout << "Enter values for first vector: ";
while (i++ != size) {
cin >> input;
v1.push_back(input);
}
i = 0;
cout << "Enter values for second vector: ";
while (i++ != size) {
cin >> input2;
v2.push_back(input2);
}
double result = 0.0;
if (size >= 1) {
result += v1[0] * v2[0];
for (int i = 1; i < size; ++i)
result -= v1[i] * v2[i];
}
cout << "\nThe 'happy' product of both vectors is: " << result << endl;
}
int main()
{
vector<double> v1;
vector<double> v2;
CalcProduct(v1,v2);
return 0;
}
However, what would happen if I want to compute A[1]*B[1] - A[3]*B[3] - A[5]*B[5] - ....? I tried adding +1 to v1 and v2 before they sum up in result but my logic seems to be wrong. Sample input:
5
1 2 3 4 5
4 5 6 7 5
Expected output: -18
You're doing the calculation in this loop
for(int i = 1; i < size; ++i)
result -= v1[i] * v2[i];
so instead of incrementing i, you can make jumps of 2:
for(int i = 1; i < size; i+=2) {
result -= v1[i] * v2[i];
}
Note that it's a good practice to check that you're not running out of bounds, also I like to surround body of for loop with { and } even if it contains one line.
Edit: I didn't note that you already added the first element before the loop, you can easily solve this by starting from i=3 instead of 1.
First of all, calcProduct is doing three things at once: Reading the values, calculating the product and writing the result to the output. Hence, you should split that into two methods and maybe do the printout from main().
Secondly, once you have generated the vectors, you can use vector.size() to avoid out of bounds situations by checking loop counters against it.
// give vector as reference
void ReadInput(vector<double>& v1,vector<double>& v2)
{
size_t size = 0; // use size_t here as this will be well defined
size_t i = 0; // on 32 and 64 bit architectures
// maybe you should have more error handling here as
// one might desire size to be in some application
// specific range
cout << "Enter vector size: ";
cin >> size;
cout << "Enter values for first vector: ";
while (i++ != size)
{
cin >> input;
v1.push_back(input);
}
i = 0;
cout << "Enter values for second vector: ";
while (i++ != size)
{
cin >> input2;
v2.push_back(input2);
}
}
// giving the parameters as (const) references avoids unneccessary copying
// of data
double CalcProduct(const vector<double>& v1, const vector<double>& v2,
size_t start, size_t step)
{
double result = 0.0;
// do parameter checking before the calculation in order to keep
// the code more structured (e.g. this can be move to a seperate
// function if it gets too complex
if ( v1.size() != v2.size()
|| start > v1.size()
|| start+step > v1.size())
|| start < 1 )
{
throw out_of_range("CalcProduc(): parameter mismatch");
}
result = v1[start] * v2[start];
for (size_t i = start+step; i < v1.size(); i+=step)
{
result -= v1[i] * v2[i];
}
return result;
}
int main()
{
vector<double> v1;
vector<double> v2;
ReadInput(v1, v2);
cout << "\nThe 'happy' product of both vectors is: " << CalcProduct(v1, v2, 1, 2) << endl;
return 0;
}
Related
I am stuck with this program so far, and I don't know what else to do.
I just need help with the recursive function so I can do the other modes too, which are multiplication and subtraction.
#include "std_lib_facilities.h"
//this contains all the libraries my university offers.
int sum(vector <int> test, int i){
if (i < 0){
return 0;
}
else {
return test[i] + sum(test, i - 1);
}
}
int main(){
int n;
int x;
int mode;
int result = 0;
cout << "give the size of the vector:\n";
cin >> n;
while (n < 0){
cout << "you can't give negative number!give again:\n";
cin >> n;
}
vector <int> myvector;
for (int i = 0; i <= n-1; i++){
cout << "give numbers to fill the vector:\n";
cin >> x;
myvector.push_back(x);
}
cout << "give 1 for sum 2 for multiplication 3 for substraction\n";
cin >> mode;
while (mode < 1 && mode > 3){
cout << "this mode doesn't exist.give again:\n";
cin >> mode;
}
if (mode == 1){
result = sum(myvector, n);
cout << "result is:" << result;
}
}
I want to get all the indexes starting from backwards to sum them all.
You are accessing outside the bounds of your array.
The simple fix to your issue is to pass n-1 to your sum function.
result=sum(myvector,n - 1);
However, there is no need for you to pass n at all, rather i would suggest you add a function that starts the recursion like this. (this is a rather common pattern for recursion)
int sum(const vector<int>& test, int i);
int sum(const vector<int>& test)
{
if(test.empty())
{
return 0;
}
if(test.size() == 1)
{
return test[0];
}
return sum(test, test.size() - 1);
};
int sum(const vector<int>& test, int i)
{
if(i < 0)
{
return 0;
}
return test[i] + sum(test, i - 1);
};
then call it like sum(myvector);
I have a little problem with check for multiplicity for 3. It says that my arr must be integer, but in objective I need to have a float massive. How to make this check "arr[i] % 3 == 0" for float numbers.
thanks.
#include <iostream>
#include <cmath>
using namespace std;
float minElement(float arr[], int length) {
float minElement = arr[0];
for (int i = 0; i < length; i++)
{
if (minElement > arr[i])
minElement = arr[i];
}
return minElement;
}
float multiplyArr(float arr[], int length) {
float multiply = 1;
for (int i = 0; i < length; i++)
{
if (arr[i] != 0 && arr[i] % 3 == 0)
multiply *= arr[i];
}
return multiply;
}
int main()
{
float length;
cout << "Enter integer value: ";
cin >> length;
float* p_darr = new float[length];
cout << "Enter values: " << endl;
for (int i = 0; i < length; i++) {
cin >> p_darr[i];
}
cout << "Max. element: " << minElement(p_darr, length) << endl;
cout << "Multiply: " << multiplyArr(p_darr, length) << endl;
delete[] p_darr;
return 0;
}
Assuming
float massive
to mean "large value". You cannot perform this operation, as it would be meaningless. Comments (and other answers) will suggest fmod. I'll advise against.
If I give you the value 3.6x10^12 and ask you what's the remainder after division by 3, you can't give me a meaningful answer.
3600000000000 % 3 is 0. 3600000000001 % 1 is 1. 3600000000002 % 2 is 2.
But all three values are 3.6x10^12.
If you need integer modulo values, it typically means you need integer precision. Float values won't offer it.
Rather, you should read your input as a string, parse it character by character, and compute the modulo so far. This is a typical first assignment in a computer theory class (as I used to TA).
I need to sort 2 vectors (A and B) using mergesort and put the sorted elements into a 3rd vector (R).
On a test with 3 elements in A (1,3,5) and B being (2,4,6) my code runs OK until I have to insert the 4th element. At this point my code crashes with a vector subscript out of range error.
This is my first time using vectors but I thought the push_back() function resizes the vector. My hunch is that the target vector (R) can only hold 3 elements so when I go to insert the 4th element, my code crashes. Do I need to do something to resize R?
using namespace std;
#include <iostream>
#include <vector>
// combine two sorted lists A and B into R
// displays comparison every time it is done
void combine(vector<int> A, vector<int> B, vector<int>& R)
{
int ia = 1;
int ib = 1;
int ir = 1;
while (!A.empty() && !B.empty()) {
if (A[ia] < B[ib]) {
R.push_back(A[ia]);
ia++;
ir++;
}
else {
R.push_back(B[ib]);
ib++;
ir++;
}
}
if (!A.empty()) {
for (int i = ia; i < A.size(); i++) {
R.push_back(A[i]);
}
}
else if (!B.empty()) {
for (int i = ib; i < B.size(); i++) {
R.push_back(B[i]);
}
}
cout << "comparison" << endl;
// be careful -- R comes in as an empty vector
}
int main()
{
vector<int> L1;
vector<int> L2;
vector<int> L3;
int N; // how many elements in each of L1 and L2
int e; // for each element
cout << "How many elements in each list?" << endl;
cin >> N;
cout << "List1" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L1.push_back(e);
}
cout << "List2" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L2.push_back(e);
}
combine(L1, L2, L3);
cout << "The result is: ";
for (int i = 0; i < N * 2; i++)
{
cout << L3[i];
} cout << endl;
}// end of main
vector A and B always not empty, unless pop_front
simply as likes,
if(A.at(0) < B.at(0)) {
C.push_back(A.at(0));
A.pop_front();
}
or, loop until size of A and B
int ia = 0;
int ib = 0;
while(ia < A.size() && ib < B.size())
{
if(A.at(ia) < B.at(ib))
{
C.push_back(A.at(ia));
ia++;
}
// ...
}
You are correct at point: I thought the push_back() function resizes the vector.
The error is due to invalid index access in your program.
In your program, your terminating condition for while loop is while (!A.empty() && !B.empty()). Since you are not removing any element for vector A or B so terminating condition will never satisfy. Which leads to an infinite loop and which further leads to access of invalid index in either vector A or B (Depending upon, out of ia or ib, which have crossed actual size of respective vector).
Also note followings:
You have started accessing elements from index 1 and not 0. Indices of vectors start from 0.
That conditions if (!A.empty()) and if (!B.empty()) will be always true. Since you are not removing elements from vector A and B.
Following is corrected code. You can see it working here:
#include <iostream>
#include <vector>
using namespace std;
// combine two sorted lists A and B into R
// displays comparison every time it is done
void combine(vector<int> A, vector<int> B, vector<int>& R)
{
int ia = 0;
int ib = 0;
int sA = A.size();
int sB = B.size();
while ((ia < sA) && (ib < sB)) {
if (A[ia] < B[ib]) {
R.push_back(A[ia]);
ia++;
}
else {
R.push_back(B[ib]);
ib++;
}
}
while(ia < sA)
{
R.push_back(A[ia++]);
}
while(ib < sB)
{
R.push_back(B[ib++]);
}
cout << "comparison" << endl;
// be careful -- R comes in as an empty vector
}
int main()
{
vector<int> L1;
vector<int> L2;
vector<int> L3;
int N; // how many elements in each of L1 and L2
int e; // for each element
cout << "How many elements in each list?" << endl;
cin >> N;
cout << "List1" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L1.push_back(e);
}
cout << "List2" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L2.push_back(e);
}
combine(L1, L2, L3);
cout << "The result is: ";
for (int i = 0; i < N * 2; i++)
{
cout << L3[i] << " | ";
} cout << endl;
}// end of main
Following is corrected code with some improvements and using iterator. You can see it working here:
using namespace std;
#include <iostream>
#include <vector>
// combine two sorted lists A and B into R
// displays comparison every time it is done
void combine(const vector<int>& A, const vector<int>& B, vector<int>& R)
{
auto itA = A.begin();
auto itB = B.begin();
while ( (itA != A.end()) && (itB != B.end()) )
{
if (*itA < *itB)
{
R.push_back(*itA);
itA++;
}
else
{
R.push_back(*itB);
itB++;
}
}
while(itA != A.end())
{
R.push_back(*itA);
itA++;
}
while(itB != B.end())
{
R.push_back(*itB);
itB++;
}
cout << "comparison" << endl;
// be careful -- R comes in as an empty vector
}
int main()
{
vector<int> L1;
vector<int> L2;
vector<int> L3;
int N; // how many elements in each of L1 and L2
int e; // for each element
cout << "How many elements in each list?" << endl;
cin >> N;
cout << "List1" << endl;
for (int i = 0; i < N; i++)
{
cout << "element :"<<endl; cin >> e; L1.push_back(e);
}
cout << endl << "List2" << endl;
for (int i = 0; i < N; i++)
{
cout << "element :"<<endl; cin >> e; L2.push_back(e);
}
combine(L1, L2, L3);
cout << "The result is: ";
for (int i = 0; i < N * 2; i++)
{
cout << L3[i]<<" | ";
}
}// end of main
In your loop you check if the vectors are empty, I think you should instead be checking that their counters are in range or something like that. For example if vector A is [1,2] and B is [3,4,5] after looping twice and inserting the A vector ia will now be out of bounds but you still make it to the if statement where A[ia] is compared to B[ib] I believe this is where you are going out of bounds on your vector. Also I believe vector index starts at 0, this could also be your problem.
how i could run fast dynamic programming algorithm to get all the possible answers .
imagine we have 20 entries and it only shows 1 line of best answers , i want it to run all the way and show the others too, till all the entries are shows as a result, and no repetitions is allowed .
thank you so much. really appreciate it.
here is the code :
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
float W ,N; //N = olcu sayisi, W = profil boyu
vector<float> numbers; //stores the set of numbers
pair<float, multiset<float>> calc(float i, float j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<float, float>, pair<float, multiset<float>>> dp; //stores results to avoid repeated calculations
pair<float, float> p(i, j); //pair for convenience
if(i == 0) //base case
{
return make_pair(0, multiset<float>(
{}));
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
auto temp2 = calc(i - 1, j - numbers[i - 1]); //compute result if using number
temp2.first += numbers[i - 1];
temp2.second.insert(numbers[i - 1]);
pair<float, multiset<float>> result;
if(temp1.first != temp2.first) //compare results and choose best
{
result = temp1.first > temp2.first ? temp1 : temp2;
}
else
{
result = temp1.second.size() < temp2.second.size() ? temp1 : temp2;
}
dp[p] = result;
return result;
}
int main()
{
cout << "sineklik sayisi: ";
cin >> N;
N = 2 * N;
cout << "Profil olcusu: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Olculeri giriniz: ";
for(int i = 0; i < N; i++) //input loop
{
float temp;
cin >> temp;
numbers.push_back(temp);
}
pair<float, multiset<float>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << " Left behind is " << W - result.first << ", obtained using the set of numbers {";
if(result.second.size() > 0)
{
cout << *result.second.begin();
for(auto i = ++result.second.begin(); i != result.second.end(); i++)
{
cout << ", " << *i;
}
}
cout << "}.\n";
}
Edit: This is one of my older answers. I wasn't as good back then, and now I know there is a much simpler, faster, and less memory-consuming solution to this problem. If we compute the DP bottom-up in a table that only stores the closest possible sum, we can reconstruct the subsets recursively later using the table values we computed.
A solution that outputs all sets of numbers with sum equal to the greatest possible sum not greater than the target value and containing the least possible number of numbers:
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
int N, W; //N = number of numbers, W = target sum
vector<int> numbers; //stores the set of numbers
pair<int, set<multiset<int>>> calc(int i, int j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<int, int>, pair<int, set<multiset<int>>>> dp; //stores results to avoid repeated calculations
pair<int, int> p(i, j); //pair for convenience
if(i == 0) //base case
{
set<multiset<int>> temp;
temp.emplace();
return make_pair(0, temp);
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
pair<int, set<multiset<int>>> temp2 = calc(i - 1, j - numbers[i - 1]), newtemp2; //compute result if using number
newtemp2.first = temp2.first + numbers[i - 1];
for(const auto k : temp2.second)
{
multiset<int> temp = k;
temp.insert(numbers[i - 1]);
newtemp2.second.insert(temp);
}
pair<int, set<multiset<int>>> *result;
if(temp1.first != newtemp2.first) //compare results and choose best
{
result = temp1.first > newtemp2.first ? &temp1 : &newtemp2;
}
else if(temp1.second.begin()->size() != newtemp2.second.begin()->size())
{
result =
temp1.second.begin()->size() < newtemp2.second.begin()->size() ? &temp1 : &newtemp2;
}
else
{
temp1.second.insert(newtemp2.second.begin(), newtemp2.second.end());
result = &temp1;
}
dp.insert(make_pair(p, *result));
return *result;
}
int main()
{
cout << "Enter the number of numbers: ";
cin >> N;
cout << "Enter target sum: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Enter the numbers: ";
for(int i = 0; i < N; i++) //input loop
{
int temp;
cin >> temp;
numbers.push_back(temp);
}
pair<int, set<multiset<int>>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << ", which can be obtained using a set of "
<< result.second.begin()->size() << " numbers " << result.second.size()
<< " different ways:\n";
for(const auto &i : result.second)
{
cout << '{';
if(i.size() > 0)
{
cout << *i.begin();
for(auto j = ++i.begin(); j != i.end(); ++j)
{
cout << ", " << *j;
}
}
cout << "}\n";
}
}
This solution will not allow a number to appear in the output more than the number of times it appeared in the input. If you want to only allow a number to appear once in the output even if it appeared multiple times in the input, change the multiset numbersleft to a set.
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
int N, W; //N = number of numbers, W = target sum
vector<int> numbers; //stores the set of numbers
pair<int, set<multiset<int>>> calc(int i, int j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<int, int>, pair<int, set<multiset<int>>>> dp; //stores results to avoid repeated calculations
pair<int, int> p(i, j); //pair for convenience
if(i == 0) //base case
{
set<multiset<int>> temp;
temp.emplace();
return make_pair(0, temp);
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
pair<int, set<multiset<int>>> temp2 = calc(i - 1, j - numbers[i - 1]), newtemp2; //compute result if using number
newtemp2.first = temp2.first + numbers[i - 1];
for(const auto k : temp2.second)
{
multiset<int> temp = k;
temp.insert(numbers[i - 1]);
newtemp2.second.insert(temp);
}
pair<int, set<multiset<int>>> *result;
if(temp1.first != newtemp2.first) //compare results and choose best
{
result = temp1.first > newtemp2.first ? &temp1 : &newtemp2;
}
else if(temp1.second.begin()->size() != newtemp2.second.begin()->size())
{
result =
temp1.second.begin()->size() < newtemp2.second.begin()->size() ? &temp1 : &newtemp2;
}
else
{
temp1.second.insert(newtemp2.second.begin(), newtemp2.second.end());
result = &temp1;
}
dp.insert(make_pair(p, *result));
return *result;
}
int main()
{
cout << "Enter the number of numbers: ";
cin >> N;
cout << "Enter target sum: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Enter the numbers: ";
for(int i = 0; i < N; i++) //input loop
{
int temp;
cin >> temp;
numbers.push_back(temp);
}
pair<int, set<multiset<int>>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << ", which can be obtained using sets of "
<< result.second.begin()->size() << " numbers:\n";
multiset<int> numbersleft;
numbersleft.insert(numbers.begin(), numbers.end());
for(const auto &i : result.second)
{
bool good = true;
for(const int &j : i)
{
if(numbersleft.find(j) == numbersleft.end())
{
good = false;
break;
}
}
if(good)
{
for(const int &j : i)
{
numbersleft.erase(j);
}
cout << '{';
if(i.size() > 0)
{
cout << *i.begin();
for(auto j = ++i.begin(); j != i.end(); ++j)
{
cout << ", " << *j;
}
}
cout << "}\n";
}
}
}
I need some help, I know this question was asked before but I don't get it and I cant solve it, so I need help. I need to move the elements of my array to a position to left. So if the input will be 1,2,3,4,5 then the output will be 2,3,4,5,1. I have done the same to right but to left I cant figure it out, please also explain the logic , thanks.
#include <iostream>
using namespace std;
int a[100],n,i,tempr,templ;
int main()
{
cin>>n;
for(i=1;i<=n;i++) cin >> a[i];
for(i=1;i<=n;i++)
{
tempr = a[n];
a[n] = a[i];
a[i] = tempr;
cout<<"Right: "<<a[i]<<endl;
}
for(i=1;i<=n;i++)
{
templ = a[2];
a[2] = a[i];
a[i] = templ;
cout<<"Left: "<<a[i]<<endl;
}
return 0;
}
Please help!
First problem is bad indexing:
for(i=1;i<=n;i++) cin >> a[i]; //wrong logic, C++ indexing start from 0
Correct approach:
for(i=0;i<n;i++) //all your loops
Second problem is wrong logic for shifting elements:
Corrected version:
//input example: 1 2 3 4 5
//to the left
int temp = a[0]; //remember first element
for(i=0;i<n-1;i++)
{
a[i] = a[i+1]; //move all element to the left except first one
}
a[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
//to the right
temp = a[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
a[i+1] = a[i]; //move all element to the right except last one
}
a[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
EDIT:
How to display both shifts:
#include <iostream>
using namespace std;
int to_left[5], to_right[5],n,i,tempr,templ;
int main()
{
cout << "Input array size: ";
cin >> n;
for(i=0;i<n;i++)
{
cin >> to_left[i]; //read values to first array
to_right[i]=to_left[i]; //then copy values to second one
}
//shift first array to left
int temp = to_left[0];
for(i=0;i<n-1;i++)
{
to_left[i] = to_left[i+1]; //move all element to the left except first one
}
to_left[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << to_left[i] << endl;
//shift second array to right
temp = to_right[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
to_right[i+1] = to_right[i]; //move all element to the right except last one
}
to_right[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << to_right[i] << endl;
return 0;
}
Note that your code look very much like C code. In C++, you can declare variables in any segment of code, not just at the beginning. In C++, you can declare variable in for loop like this: for(int i=0; i<...) - no need for global variable i
For reference, this would be good C++ code example that satisfies problem you are facing:
#include <iostream>
#include <vector>
int main()
{
std::size_t n; //size_t is unsiged type used for various sizes of containers or types
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n); //two dynamic arrays containing integers, takin n as their size
for(std::size_t i=0;i<to_left.size();++i) //use vector size(), instead of n, also ++i in considered better for loops that i++ (may be faster)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
int temp = to_left[0]; //declare temp here, not at the begining of code
for(std::size_t i=0;i<n-1;++i)
to_left[i] = to_left[i+1];
to_left[n-1] = temp;
std::cout << "To left: " << std::endl;
for(std::size_t i=0;i<n;++i)
std::cout << to_left[i] << std::endl;
temp = to_right[n-1]; //reuse temp
for(int i=to_right.size()-1;i>=0;--i) //note int, not std::size_t, because size_t is always >=0, loop would never end.
to_right[i+1] = to_right[i];
to_right[0] = temp;
std::cout << "To right: " << std::endl;
for(std::size_t i=0;i<n;i++)
std::cout << to_right[i] << std::endl;
return 0;
}
And here would be ideal C++ code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::size_t n;
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n);
for(std::size_t i=0;i<to_left.size();++i)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
// rotate first array to the left
std::rotate(to_left.begin(), to_left.begin() + 1, to_left.end());
// rotate second array to right
std::rotate(to_right.rbegin(), to_right.rbegin() + 1, to_right.rend());
std::cout << "To left:" << std::endl;
for(auto x : to_left) //C++11 feature, x iterates through container
std::cout << x << std::endl;
std::cout << "To right:" << std::endl;
for(auto x : to_right)
std::cout << x << std::endl;
return 0;
}
Or you can use memmove(...) projected exactly for those purpose, here your sample:
#include <iostream>
#include <cstring>
using namespace std;
//rotate Left
void r_left(int *a,int n)
{
int tmp=a[0];
memmove(a,a+1,sizeof(int)*(n-1));
a[n-1]=tmp;
}
//rotate right
void r_right(int *a,int n)
{
int tmp=a[n-1];
memmove(a+1,a,sizeof(int)*(n-1));
a[0]=tmp;
}
void show(int *a,int n)
{
while(n--)
cout<<*a++<<' ';
cout<<endl;
}
int main()
{
int ar[]={1,2,3,4,5};
int n=sizeof(ar)/sizeof(ar[0]);
r_left(ar,n);
show(ar,n);
r_right(ar,n);
show(ar,n);
return 0;
}
easiest way to swap elements in C++ is to use std::iter_swap()
so for an array of 4 elements to swap elements 1 and 4 you would do the following
int a[4];
std::iter_swap(a, a+3);
note that you also need to #include <algorithm> for this to work
the basic logic of the function is that you give the location in memory of the 2 elements, so as the first element of an array is also its location in memory, you can pass a + n, when n is equal to the n-1 index number of the element you want to swap
As other already have stated it's all about indices. In a for-loop you are almost always in trouble if your stop condition is i <= size, because arrays in C++ are zero-indexed.
Where Black Moses alogrithm is far the easiest to understand (and probably the fastes), I read your code as if you try to swap the first value of the array through the array to the last position. Below I have tried to pin out this approach.
#include <stdio.h>
#include <tchar.h>
#include <iostream>
void ShiftLeft(int* pArr, size_t length)
{
for (size_t i = 1; i < length; i++)
{
int tmp = pArr[i - 1]; // Preserves the previous value
pArr[i - 1] = pArr[i]; // Overwrites the previous position with the current value
pArr[i] = tmp; // Stores the previous value in the current position
// All in all the first value is swapped down the array until it is at the length - 1 position
// and all the other values are swapped to the left.
/* For an array with 4 values the progression is as follows:
i = 0: 1 2 3 4
i = 1: 2 1 3 4
i = 2: 2 3 1 4
i = 3: 2 3 4 1
*/
}
}
void ShiftRight(int* pArr, size_t length)
{
for (size_t i = length - 1; i > 0; i--)
{
// This code does exactly the same as for ShiftLeft but the loop is running backwards
int tmp = pArr[i - 1];
pArr[i - 1] = pArr[i];
pArr[i] = tmp;
}
}
void Print(int* pArr, size_t length)
{
for (size_t i = 0; i < length; i++)
{
std::cout << pArr[i] << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
size_t length = sizeof(arr) / sizeof(arr[0]);
Print(arr, length);
ShiftLeft(arr, length);
Print(arr, length);
ShiftRight(arr, length);
Print(arr, length);
return 0;
}
#include <iostream>
using namespace std;
int a[100], outR[100], outL[100], n, i;
int main() {
cin >> n;
for (i = 0; i < n; i++) cin >> a[i];
// Right
for (i = 0; i < n; i++) {
outR[i+1]= a[i];
}
outR[0] = a[n-1]; // add first number
// Left
for (i = 1; i < n; i++) {
outL[i-1]= a[i];
}
outL[n-1] = a[0]; // add last number
// Answer
cout << "Right:\n";
for(i=0; i<n; i++) {
cout << outR[i] << endl;
}
cout << "Left:\n";
for(i = 0; i < n; i++) {
cout << outL[i] << endl;
}
return 0;
}
Simple answer where you can easily see everything, good luck.
You may be interested in ,,vector coding", it seems be easier if you spend some time on this:
#include <iostream>
#include <vector>
using namespace std;
vector <int> a, outR, outL;
size_t i;
int main () {
int n, temp_int;
cin >> n;
while (n--) {
cin >> temp_int; // here you read number to your vector
a.push_back(temp_int); // here you add this to vector
// remember that vector start from element 0 as like arrays
}
// Left
// remember that last element will be first
// you may have acces to size of your vector easily
for (i = 0; i < (a.size()-1); i++) {
outL.push_back(a.at(i+1)); // here you create new vector
}
outL.push_back(a.at(0)); // add last elemet which rotated
// Right
// to rotate left first you have push last element so
outR.push_back(a.at(a.size()-1)); // add first elemet which rotated
for (i = 1; i < a.size(); i++) {
outR.push_back(a.at(i-1)); // here you push rest
}
cout << "Left" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outL.at(i) << endl; // here you print value
}
cout << "Right" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outR.at(i) << endl; // here you print value
}
return 0;
}
int* leftShiftOneByOneWIthoutTemp(int arr[], int sz)
{
for (int i=0 ;i < sz-1; i++)
{
arr[i] = arr[sz-1] + arr[i];
arr[sz-1] = arr[i] - arr[sz-1] ;
arr[i] = arr[i] - arr[sz-1] ;
std::cout << "iter "<< i << std::endl;
printArray(arr,5);
}
std::cout << "final "<< std::endl;
printArray(arr,5);
return arr;
}
Replace your code (to shift array left) with below code.
templ = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
cout<<"Left: "<<a[i]<<endl;
}
a[n-1] = templ;
cout<<"Left: "<<a[n-1]<<endl;