在 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
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP