移动的打印方向,使您停留在C ++中的[-k,+ k]边界内

在这个问题中,我们必须找到一种有效的方式来移动正方向或负方向,以使我们保持在用户提供的特定限制内。

在这里,我们给定了一个最大极限K,它是我们可以移动到的最大值和n个正值要移动的数组。我们必须返回序列(即正向或负向)进行移动,以使其永远不会超过K值。

让我们举个例子来更好地理解这个话题,

Input : K = 56 and the array is [25 , 14 , 31 , 16 , 5].
Output : positive positive negative positive positive.

说明

首先,我们将检查0 + a [0] = 0 + 25 = 25 <56是,然后我们将向正方向移动。

现在,我们将检查25 + a [1] = 25 + 14 = 39 <56是,然后我们将朝正方向移动。

现在,我们将检查29 + a [2] = 39 + 31 = 70 <56否,那么我们将检查39-a [2] = 39-31 = 8> 0,然后我们将向负方向移动。

我们将检查8 + a [3] = 8 + 16 = 24 <56是,然后我们将朝正方向移动。

我们将检查16 + a [4] = 16 + 5 = 21 <56是,然后我们将朝正方向移动。

因此,现在让我们创建解决此问题的逻辑。我们必须检查朝正方向移动是否会达到极限。如果否,则朝正方向移动。否则,请检查是否向负方向移动将达到下限,即0。如果否,则向负方向移动。如果两者均为“是”,则不可能返回。

基于此逻辑,创建代码必须遵循的算法是-

算法

Initially set position to 0.
Step 1 : for i -> 0 to n , n is the length of array. Follow step 2 - 4.
Step 2 : if initial_postition + a[i] < K, initial_position + = a[i]. Print “POSITIVE”.
Step 3 : else if initial_postition - a[i] > 0, initial_position - = a[i]. Print “NEGATIVE”.
Step 4 : else , print “NO MORE VALID MOVES”.

示例

现在,让我们创建一个程序来展示解决该问题的算法的实现,

#include <iostream>
using namespace std;
void StepsTaken(int a[], int n, int k){
   string res = "";
   int position = 0;
   int steps = 1;
   for (int i = 0; i < n; i++) {
      if (position + a[i] <= k && position + a[i] >= (-k)) {
         position += a[i];
         cout<<"POSITIVE \t";
      }
      else if (position - a[i] >= -k && position - a[i] <= k) {
         position -= a[i];
         cout<<"NEGATIVE \t";
      } else {
         cout << -1;
         return;
      }
   }
   cout << res;
}
int main(){
   int a[] = { 12 , 24 , 9 , 17 , 8};
   int n = sizeof(a) / sizeof(a[0]);
   int k = 40;
   StepsTaken(a, n, k);
   return 0;
}

输出结果

POSITIVE    POSITIVE    NEGATIVE
      NEGATIVE    POSITIVE