Moving values in Array to the left/right to k positions? - c++

I have an array of n values. I have a value p which can be 1 or -1. I have to move the positions in the Array k positions to the left if p = 1 or to the right if p = -1.
1 ≤ N ≤ 1.000.000
0 ≤ K ≤ 1.000.000
I tried:
#include <iostream>
using namespace std;
int main() {
int n, p, k;
int v[1000002];
cin >> n >> k >> p;
for ( int i = 1; i <= n; i++ ) {
cin >> v[i];
}
if( p == 1) {
for ( int i = k + 1; i <= n ; i++ ) {
cout << v[i] << " ";
}
for ( int i = 1; i <= k; i++ ) {
cout << v[i] << " ";
}
}
else {
for ( int i = n - k + 1; i <= n; i++ ) {
cout << v[i] << " ";
}
for ( int i = 1; i <= n - k; i++ ) {
cout << v[i] << " ";
}
}
return 0;
}
The problem is I use an online tester to do tests on it to see if it applies to all possible cases, but this solution passes all but 3 tests. The results are correct, but it says that I have surpassed the time limit for the respective test. I cannot comprehend how because I only use essential code like reading and printing the array.

I'm not sure if it will help resolve your timeouts, but I can see the following to reduce your calls a tiny bit:
After you read in n, p and k, calculate your offset.
Create a vector that is offset in size.
Read into vector until it's full.
Pipe all input directly to stdout.
Write out of the vector to stdout.
This process will reduce the readin->writeout to a single step for (n - offset elements, where offset = k or n - k depending on p).
If this still fails, you can build a stringstream and write to stringstream, and flush to cout once in a while (i.e. every 8 k or so) to reduce calls to your io channel (cout).
Sample code:
int n, p, k;
cin >> n >> k >> p;
int offset = p == 1 ? k : n - k;
std::vector tmp(offset);
std::stringstream sout;
for (size_t i = 0; i < offset; i++)
{
cin >> tmp[i];
}
for (size_t i = offset; i < n; i++)
{
cin >> sout << ' ';
if (sout.size() > _BUFFER_MAX)
{
cout << sout.str();
std::stringstream().swap(sout);
}
}
cout << sout.str();
std::stringstream().swap(sout);
for (size_t i = 0; i < tmp.size(); i++)
{
sout << tmp[i] << ' ';
if (sout.size() > _BUFFER_MAX)
{
cout << sout.str();
std::stringstream().swap(sout);
}
}
cout << sout.str();

I appreciate the way you're trying to "cheat". There will be many times in your programming career when the best plan is to provide what the customer asks for, completely ignoring the way they think you should provide it.
That enormous array at the beginning is awful, though -- you should use a std::vector with n elements, not 10000002.
I'm surprised that you are running out of time, since all the time is in I/O, and you are making the "obvious" I/O calls that will be similar to what everyone else is doing... but there are a lot of details you don't know about the test environment.
Try putting this at he start of main:
std::ios_base::sync_with_stdio(false);
See: https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio
By default, every time you write to cout, the data is pushed into the stdout C stream. It's possible that the test environment is set up in a way the makes this slow.
If you turn off the syncing, you can use cout's internal bufferring, which will make all those little writes a lot faster in those cases.

I have managed to find the problem in my code.
Apparently the problem was that the number of positions to move could be bigger than the actual number of values. This led to some very long for's.
I feel pretty stupid , but I have learned many new things through your answers. Thank you very much!

if k is very large you can simply take it to the mod n (k%n)
you can perform placements in O(n) by calculating the final index of each element after rotation using the formulas:
(i + k) % n for right rotation and (i - k) % n for left rotation.
note: you should add an extra 'n' to handle negative modulo.
here's the code:
int v[1000001];
int main() {
int n, p, k;
cin >> n >> k >> p;
k %= n;
for (int i = 0; i < n; i++) {
if (p == -1) //right
cin >> v[(i + k) % n];
else if (p == 1) //left
cin >> v[(i - k + n) % n];
}
for (int i = 0; i < n; i++) {
cout << v[i] << " ";
}
return 0;
}

Related

Print the array value which can produce the input by using addition operator

How do I edit the given program to get all possible combinations of array values which will provide the given data using addition operator?
The following code works fine only if there is only one combination. For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4. Thus the output desired is array [1] & array[3]. Attached coding works fine for this. But for array ={1, 3, 3, 4, 2}, there is two possibilities but the code returns nothing...
#include<iostream>
using namespace std;
int main() {
int n = 5; int m = 0;
int givendata;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cin >> givendata;
if (m < n) {
for (int i = 0; i < n; i++) {
int sum = a[n - i] + a[m];
if (sum == givendata) {
cout << m << " " << n - i;
}
}
}
m = m + 1;
return 0;
}
You need to use a double loop to compare all the values:
// start at 0, the first position of the array. Loop until the 2nd to last element
for (int i=0; i<n-1;i++)
{
// start this index at one higher than i. Since a+b == b+a, there's no need to
// add the later values in the array with the previous ones, we've already
// done that
for (int j=i+1; j<n; j++)
{
int sum = a[i]+a[j];
if (sum == givendata)
{
std::cout << a[i] << " + " << a[j] << " = " << givendata << std::endl;
}
}
}
Demonstration
Also see Why is "using namespace std;" considered bad practice?

How to fix this code of "1/0! + 1/1! + 1/2! +....+ 1/n!"

So, I am trying to write a program to compute the value of the series 1/0! + 1/1! + 1/2! + .. + 1/n!. I think this is a pretty easy question to solve. But, the 1/0! i.e. the 1st term of the series is where it is creating all the problems for me. Please help me out. Please pardon for the silly mistakes if I have made since I started learning C++ 2 months ago and I am trying to solve various problems ever since.
#include <iostream>
using namespace std;
int fact(int j)
{
int facto = 1;
if (j == 0) {
return facto;
}
else {
for (int i = 2; i <= j; i++) {
facto = facto * i;
}
return facto;
}
}
int main()
{
int n, p;
float sum = 0, k;
cout << "Enter the value of n: " << endl;
cin >> n;
for (int i = 0; i < n; i++) {
p = fact(i);
cout << p << endl;
k = 1 / p;
cout << k << endl;
sum = sum + k;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I have 2 questions :
1) When I am giving 0 as input, I am getting 0(i.e. the value of sum) as output(but, I am expecting to get 1) and, when I am giving 1 as input, it is giving 1 as output(expecting 2 as output). Please help me in pointing out the loophole.
2) When I am giving 0 as input, it is not printing the values of 'p' and 'k' but any input greater than 0 is showing the values of 'p' and 'k' for each time it completes the loop. Why ??
Change the loop the following way
for(int i=0; i<=n; i++)
^^^^^
Or change the loop to do-while loop as for example
int i = 0;
do
{
//...
} while ( i++ < n );
Also this statement
k = 1/p ;
change like
k = 1.0f/p ;

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

Visual studio doesn't take array: int magicSquare[n][n]?

I wrote my code and I'm ready to submit it but the teacher will be testing it on Visual studio 2015. Every time I test it, it gives me an error that this int magicSquare[n][n] is wrong and that n can't be read.
How do i revise this part to make visual studio read this array from n ?
My code:
#include <iostream>
using namespace std;
// This function is to create the requested magic squares
int main()
{
int n;
//asking for n
cout << "Please enter an odd number" << endl;
cin >> n;
//checking in case n doesnt follow rules
if (n < 3 || n % 2 == 0)
{
cout << "Invalid Entry, Please re-enter an odd number that is 3 or larger " << endl;
}
else
{
// A function to generate odd sized magic squares
int magicSquare[n][n];
// Setting every slot to 0
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magicSquare[j][i] = 0;
}
}
// Initializing position to 1
int j = n / 2;
int i = n - 1;
// Setting each value to generate the magic square
for (int num = 1; num <= n * n; )
{
if (j == -1 && i == n)
{
i = n - 2;
j = 0;
}
else
{
//send to next number
// moving it to the right side
if (i == n)
i = 0;
//send to next number again
// moving it to the upper side
if (j < 0)
j = n - 1;
}
//second condition
if (magicSquare[j][i])
{
i -= 2;
j++;
continue;
}
else
//add the number
magicSquare[j][i] = num++;
//first condition
i++; j--;
}
//displaying sum of col/row
cout << "The sum of each row/col: " << n * (n*n + 1) / 2 << endl;
//Dispplaying magic square
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
cout << " " << magicSquare[i][j];
cout << "\n";
}
}
cout << endl;
//re running program
return main();
}
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables.'n' must be a constant value.
In C++, arrays that are declared that way must use an n that is known at compile time. There are various ways to construct a matrix in C++. Perhaps the simplest is to define a vector of vectors.
Change
int magicSquare[n][n];
to
std::vector<std::vector<int>> magicSquare(n);
for (auto &row : magicSquare) row.resize(n);

Program not computing subtraction properly

I'm working on a math assignment, not anything that requires programming, but since I enjoy it I try to do it for some of the assignments just to see if I can. This one was writing an integer as a sum of Fibonacci numbers. Here's the code for it:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> fib;
vector<int> sum;
int n = 0;
int total = 0;
cout << "Enter a number." << endl;
cin >> n;
total = n;
fib.push_back(1);
fib.push_back(1);
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = n; i >= 0; i--)
{
if(total - fib[i] >= 0)
{
sum.push_back(fib[i]);
total -= fib[i];
}
if(total == 0)
{
break;
}
if(total < 0)
{
cout << "Program Error. Exiting" << endl;
exit(1);
}
}
cout << "The sequence of the fewest Fibonacci numbers adding to " << n << " is:" << endl;
for(int i = 0; i < sum.size(); i++)
{
cout << sum[i] << endl;
}
return(0);
}
It seems to run fine until I try to put in the number 7.
When it gets to if(total - fib[i] >= 0) it works as its supposed to. total is supposed to get down to 2 and fib[i] also reaches 2 for some i. It calculates this fine and goes into the if statement. but then when it does total -= fib[i] it makes total = -1, thus breaking the code.
Any suggestions as how to fix this?
Edit: It's not just 7. I tried 100, and got extremely large (both positive and negative) numbers that I was too lazy to see if they actually added up to 100 since there were about 30 or so of them. I'm not sure where this would come from.
Edit2: The issue with the #100 is not that it doesn't work, but the value is too large for an int to hold, for anyone having similar situations.
Change
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
To
for (int i = 2; i <=n; i++) {
int tmp = fib[i-1] + fib[i-2];
fib.push_back(tmp);
}
vector<int> fib allocates 8 elements space by default, vector[8+] access will cause memory error, you should use push_back(), vector will auto reallocate space when it's full.
Before your line for(int i = 2; i <= n; i++) the size of your fib vector is only 2, because you didn't reserve any space for it, and you called push_back only twice.
This means, if you try to set any element of it after that, you will encounter undefined behavior. You accessed memory which doesn't belong to you.