首頁  >  文章  >  後端開發  >  使用C++編寫,找出滿足方程式的六元組的數量

使用C++編寫,找出滿足方程式的六元組的數量

王林
王林轉載
2023-09-11 17:17:11558瀏覽

使用C++編寫,找出滿足方程式的六元組的數量

在本文中,我們將描述一種尋找滿足方程式的六元組的方法。因此,我們以一個方程式為例,需要找到滿足下面方程式的a、b、c、d、e和f的值。

( a + b + c ) * e / d = f

讓我們重新排序方程式−

( a + b + c ) = ( f * d ) / e

這是給定問題的一個簡單範例-

Input : arr [ ] = { 1, 3 }
Output : 4
Explanation : ( a, b, c, e, f ) = 1, d = 3
   ( a, b, c, d, e ) = 1, f = 3
   ( a, b, c ) = 1, ( d, e, f ) = 3
   ( a, b, c, d, f ) = 3, ( e ) = 1

Input : arr [ ] = { 2, 5 }
Output : 3

找到解決方案的方法

我們將使用一種天真的方法來找到給定問題的解決方案。

天真的方法

在這個問題中,透過觀察LHS和RHS,我們可以找到所有可能的LHS結果並將其儲存在一個陣列中,同樣地,創建一個RHS的數組,並將其填入所有可能的RHS結果。

檢查這兩個陣列是否有相同的值,並對每個找到的值遞增計數,最後顯示結果。

範例

#include<bits/stdc++.h>
using namespace std;
int findsamenumbers(int *arr1, int *arr2, int n){
    int i = 0, j = 0, k = 0, count=0;
    while(( i < n*n*n+1) && (j < n*n*n+1)){
        if(arr1[i] < arr2[j])
            i++;
        else if(arr1[i] == arr2[j]){
            count++;
        int temp = arr1[i];
        while(temp==arr1[++i]){
            count++;
        }
        while(temp==arr2[++j]){
            count++;
        }
    }
    else
        j++;
    }  
    return count;
}
int main(){
    int arr[] = {2,5};
    int n = sizeof(arr)/sizeof(arr[0]);
    // Generating all possible values of LHS array
    int index = 0,i;
    int LHS[n*n*n ];
    for ( i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            for(int k = 0; k < n; k++){
                LHS[index++] = (arr[i] * arr[j]) / arr[k];
            }
        }
    }
    // Generating all possible value of RHS array
    int RHS[n*n*n ];
    index=0;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            for (int k = 0; k < n; k++){
                RHS[index++] = (arr[i] + arr[j] + arr[k]);
            }
        }
    }
    sort(RHS, RHS + (n*n*n));
    sort(LHS, LHS + (n*n*n));
    int result = findsamenumbers(LHS, RHS, n);
    cout<<"Number of sextuplets that satisfy an equation: "<<result;
    return 0;
}

輸出

Number of sextuplets that satisfy an equation: 3

上述程式的解釋

在這個程式中,我們建立了兩個陣列來保存LHS和RHS的每個結果。我們使用三個巢狀迴圈來將(a, b, c)的每個可能值放入LHS,將(d, e, f)的每個可能值放入RHS。之後,我們對這兩個數組進行排序,以比較它們並找到兩個數組中相同的值,將這兩個數組傳遞給findsamenumber()函數。

在findsamenumber()函數中,我們使用兩個巢狀迴圈來檢查相同的值。當我們找到兩個相同的元素時,我們檢查該數字在兩個陣列中的頻率,以便計算每個可能值的次數。

if(arr1[i] == arr2[j]){
   count++;
   int temp = arr1[i];
   while(temp==arr1[++i]){
      count++;
   }
   while(temp==arr2[++j]){
      count++;
   }

結論

在本文中,我們求解了滿足給定數組中的方程式的六聯組的數量。我們找到了 6 個變數方程式 (a b c) * e / d = f 中變數的每個可能值。我們可以用任何其他程式語言(例如 C、Java 和 python)來解決這個問題。

以上是使用C++編寫,找出滿足方程式的六元組的數量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除