[英]C function to check if array is balanced (recursive)
我正在嘗試編寫一個 function 來檢查數組是否平衡。 我想出了以下內容:
//Defining my struct
struct tuples
{
bool trueorfalse;
int sum;
};
typedef struct tuples tuple; //Renaming it to "tuple"
//Defining my function
tuple balanced(int A[], int l, int r)
{
if(l == r) // Base case
{
tuple s;
s.trueorfalse = true;
s.sum = A[l];
return s;
}
tuple left; //Creating tuple for the left side of the array
tuple right; //Creating tuple for the right side of the array
int m = (l+r)/2; //Computing the middle
left = balanced(A, l, m); //recursive call for the left side
right = balanced(A,m+1, r); //recursive call for the right side
if(left.trueorfalse && right.trueorfalse && left.sum >= (right.sum / 2.0f) && left.sum <= right.sum *2) //Check the conditions to be a balanced array on the subarrays
{
tuple f; //If this is the case create a new tuple with true and the sum
f.trueorfalse = true;
f.sum = left.sum + right.sum;
return f;
}
else
{
tuple g;
g.trueorfalse = false;
g.sum = left.sum + right.sum;
return g;
}
}
但這似乎適用於一些示例,但並非適用於所有示例。 示例: A =[1,2,5,2,4,2] 是平衡樹,但我的 function 沒有返回值為 true 的結構。
編輯:
我們將平衡定義如下:
前半部分的元素之和不超過后半部分元素之和的兩倍且不少於一半,並且
上半場和下半場是平衡的
我修好了它。
順便說一句,您所說的奇數 arrays A =[1,2,5,2,4,2] 不平衡,因為 A[3]+A[4] > A[5]*2
代碼:
#include <stdio.h>
typedef struct
{
bool trueorfalse;
int sum;
}tuple;
tuple balanced(int A[], int size);
bool Is_Balanced(int a, int b);
int main(void)
{
int A[]={1,2,5,2,4,2};
tuple res =balanced(A,6);
if(res.trueorfalse)printf("balanced");
else printf("notbalanced");
}
tuple balanced(int A[], int size)
{
if(size<4)//maximum recursion depth
{
tuple s;
if(size==3) s.trueorfalse = Is_Balanced((*(A)+*(A+1)),*(A+2));
else s.trueorfalse = Is_Balanced(*(A),*(A+1));
s.sum = 0;
for(int i=0;i<size;i++)s.sum += *(A+i);
return s;
}
tuple left;
tuple right;
left = balanced(A, size/2);
right = balanced(A+size/2, size/2);
tuple f;
if(left.trueorfalse && right.trueorfalse)
f.trueorfalse = Is_Balanced(left.sum,right.sum);
else f.trueorfalse = false;
f.sum = left.sum + right.sum;
return f;
}
bool Is_Balanced(int a, int b)
{
return (a<=(2*b) && a>=(2/b)?true:false);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.