Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

การพิมพ์นิพจน์วงเล็บสมดุลโดยใช้วงเล็บที่กำหนดในโปรแกรม C


ได้ตัวแปร a, b, c, d ที่มีค่ากำหนดไว้ จะพิมพ์วงเล็บตามตัวแปรที่ใช้

ตัวแปร:

a for ((  b for ()  c for )(  d for ))

งานคือใช้วงเล็บทั้งหมดและพิมพ์นิพจน์วงเล็บสมดุล หากไม่สามารถสร้างได้พิมพ์ -1 หากมีคำตอบหลายอันพิมพ์อันไหนก็ได้

ตัวอย่าง

Input: a = 3, b = 2, c = 4, d = 3
Output : (((((()()()()())))))()()

เพื่อให้ได้ผลลัพธ์นี้ ให้ตรวจสอบก่อนว่าสามารถสร้างนิพจน์สมดุลได้หรือไม่ หากได้ ให้:

  • พิมพ์จำนวนวงเล็บประเภท 1
  • พิมพ์จำนวนวงเล็บประเภท 3
  • พิมพ์จำนวนวงเล็บประเภท 4
  • พิมพ์จำนวนวงเล็บประเภท 2

อัลกอริทึม

START
Step 1 -> Declare Function void print(int a, int b, int c, int d)
Declare int i
IF ((a == d && a) || (a == 0 && c == 0 && d == 0))
  Loop For i=1; i<=a; i++
    Print ((
  End
  Loop For i=1; i<=c; i++
    Print )(
  End
  Loop For i=1; i<=d; i++
    Print ))
  End
  Loop For i=1; i<=b; i++
    Print ()
  End
Else
  Print can't be formed
Step 2 -> main()
  Declare int a = 3, b = 2, c = 4, d = 3
  Call print(a,b,c,d)
STOP

ตัวอย่างโค้ด C

#include
void print(int a, int b, int c, int d){
    int i;
    if ((a == d && a) || (a == 0 && c == 0 && d == 0)){
        for (i = 1; i <= a; i++)
            printf("((");
        for (i = 1; i <= c; i++)
            printf(")(");
        for (i = 1; i <= d; i++)
            printf("))");
        for (i = 1; i <= b; i++)
            printf("()");
    }
    else
        printf("can't be formed");
}
int main(){
    int a = 3, b = 2, c = 4, d = 3;
    print(a, b, c, d);
    return 0;
}

ผลลัพธ์

การรันโปรแกรมจะได้ผลลัพธ์ดังนี้:

(((((()()()()())))))()()