>  기사  >  백엔드 개발  >  PHP의 패턴

PHP의 패턴

王林
王林원래의
2024-08-29 13:11:271001검색

PHP의 패턴 프로그래밍이란 무엇인가요? 화면에 일종의 패턴을 인쇄하는 것은 프로그래밍 기술입니다. 일련의 숫자, 문자 또는 특수 문자로 패턴을 형성할 수 있습니다. 패턴의 가장 간단한 예는 피보나치 수열(1, 1, 2, 3, 5, 8, 13, 21, 34 등)입니다. 그리고 별의 피라미드와 같이 화면에 디자인된 다른 패턴도 있습니다. 따라서 기본적으로 패턴 프로그래밍은 단순히 화면에 패턴을 인쇄하는 것입니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

이 기사에서는 PHP를 사용하여 패턴을 코딩합니다. 그래도 걱정하지 마세요. 일단 익숙해지면 언어마다 다른 구문일 뿐입니다. 논리는 항상 똑같습니다.

PHP 패턴의 예

  • 프로그램으로 바로 넘어가기 전에 코딩 패턴의 기본 논리를 이해해 보겠습니다. 패턴은 항상 중첩 루프(대부분 중첩 for 루프)를 통해 프로그래밍됩니다. 이는 루프가 구문적으로 이해하기 쉽고 간결하기 때문입니다.
  • 외부 루프는 항상 줄 수와 관련이 있습니다. 따라서 5줄에 걸쳐 있는 패턴을 인쇄해야 한다면 외부 루프는 항상 5번 실행됩니다.
  • 내부 루프는 항상 각 줄의 요소 수와 관련이 있습니다. 따라서 첫 번째 줄에 별 1개, 두 번째 줄에 별 2개 등을 인쇄해야 하는 경우 내부 루프가 이 논리를 제어한다고 가정해 보겠습니다.
  • 패턴에 따라 내부 루프가 두 개 이상이거나 중첩 루프가 세 개 이상 있는 경우도 있습니다. 또한 원하는 패턴을 생성하기 위해 공백과 탭이 포함됩니다.

이제 이 모든 점을 염두에 두고 패턴을 코딩해 보겠습니다.

1. 스타 하프 피라미드

가장 간단한 인쇄 패턴입니다. 후속 라인에서 점점 더 많은 수의 별을 인쇄합니다. 첫 번째 줄에 별 1개, 두 번째 줄에 별 2개 등등.

PHP의 패턴

이 패턴을 5줄로 코딩해 보겠습니다. 논리를 염두에 두고 외부 루프는 5번 실행됩니다. 각 라인의 별 개수는 라인 번호에 직접적으로 의존하기 때문에 내부 루프는 외부 루프의 제어 변수의 함수가 됩니다. 방법을 살펴보겠습니다.

Our outer control variable is i and inner control variable is j.
Outer loop iteration 1 –> i = 0
Inner loop iteration 1 –> <em>j </em>=<em> 0</em>
Print star
Outer loop iteration 2  –> i<em> = 1</em>
Inner loop iteration 1 –> <em>j</em><em> =</em><em> 0</em>
Print Star
Inner loop iteration 2 -> <em>j</em> =<em> 1
</em>Print Star
Outer loop iteration 3  –> <em>i</em> =<em> 2
</em>Inner loop iteration 1 –> <em>j =</em> 0
Print Star
Inner loop iteration 2 -> <em>j = 1
</em>Print Star
Inner loop iteration 3 -> <em>j = 2
</em>Print Star

등등. 이것이 외부 루프 제어 변수를 기반으로 내부 루프를 제어하는 ​​방법입니다. 지금부터 프로그램이 어떻게 작동하는지 살펴보겠습니다.

코드:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = 0; $i < $num; $i++)
{
// inner loop handles number of columns
for($j = 0; $j <= $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

출력:

PHP의 패턴

2. 별 반 피라미드 – 거울

별이 오른쪽 정렬되어 있다는 점을 제외하면 별 반 피라미드와 유사합니다.

PHP의 패턴

올바른 들여쓰기를 얻으려면 공백을 사용한 다음 별표를 인쇄합니다. 따라서 두 개의 내부 루프가 있습니다. 하나는 공백 수를 제어하고 다른 하나는 별 수를 제어합니다.

참고: k-loop의 공백 수는 두 배의 공백이라는 점에 유의하세요. 별과 함께 단일 공백을 인쇄하기 때문입니다. 이는 혼잡한 인쇄물이 아닌 패턴의 완성된 모습을 제공합니다. 우리는 전체 피라미드를 인쇄할 때 이를 활용하여 활용할 것입니다.

코드:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = 0; $i < $num; $i++)
{
// inner loop handles indentation
for($k = $num; $k > $i+1; $k-- )
{
// Print stars
echo "  ";
}
// inner loop handles number of stars
for($j = 0; $j <= $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

출력:

PHP의 패턴

3. 별 반 피라미드 – 거꾸로

이 피라미드 패턴의 경우 새 줄이 나올 때마다 별의 수가 계속 감소합니다. 첫 번째 줄에는 별 5개, 두 번째 줄에는 별 4개 등이 있습니다.

PHP의 패턴

논리를 염두에 두고 외부 루프는 항상 줄 수를 제어해야 하고 내부 루프는 별 수를 제어해야 한다는 것을 알고 있습니다. 이 논리는 변경할 수 없습니다. 하지만 변경할 수 있는 것은 루프를 시작하는 방법, 즉 순서를 늘리거나 줄이는 것입니다. 이는 0에서 5까지 반복하거나 5에서 0까지 내림차순으로 반복할 수 있음을 의미합니다. 따라서 이와 같은 반전 패턴의 경우 첫 번째 줄에 별 수가 더 많다는 것을 알 수 있습니다. 그래서 우리는 주문 루프를 줄이기로 결정했습니다.

코드:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = $num; $i > 0; $i--){
// inner loop handles number of stars
for($j = 0; $j < $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

출력:

PHP의 패턴

4. Star Half Pyramid– Inverted Mirrored

This pattern is an indented inverted half pyramid. The number of stars decreases with each line and stars are right-aligned.

PHP의 패턴

I believe by now you would be able to guess the logic for this one.

Code:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = $num; $i > 0; $i--)
{
// inner loop handles indentation
for($k = $i; $k < $num; $k++ )
{
// Print stars
echo "  ";
}
// inner loop handles number of stars
for($j = 0; $j < $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

Output:

PHP의 패턴

5. Star Full Pyramid

This pattern prints the full pyramid. Or in other words, it prints a triangle of stars on the screen.

PHP의 패턴

This pattern is essentially a combination of Half pyramid and its mirror. Although there is a slight twist when we code it. Revisit the Note in Mirrored Half Pyramid. Remember, how we used double spacing to give a finished look to our pattern? Here we would use single spacing so that the stars are alternately aligned in odd and even number of rows, giving us a true triangular pattern.

Code:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = 0; $i < $num; $i++)
{
// inner loop handles indentation
for($k = $num; $k > $i+1; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 0; $j <= $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

Output:

PHP의 패턴

6. Star Diamond

This pattern prints a complete diamond shape on the screen. The number of stars increases until the maximum defined and then decrease back to 1, giving us a full diamond shape.

PHP의 패턴

To print this pattern, we would need to divide the pattern into two halves. The upper half – which prints the increasing number of stars. The lower half– which prints the decreasing number of stars. To print both the halves, we would use two outer loops and corresponding inner loops.

Code:

<?php
function print_pattern($num)
{
// The Upper Half Pattern
// Outer loop handles number of rows
for ($i = 0; $i < $num; $i++)
{
// inner loop handles indentation
for($k = $num; $k > $i+1; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 0; $j <= $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
// The Lower Half Pattern
// Outer loop handles number of rows
for ($i = $num-1; $i > 0; $i--)
{
// inner loop handles indentation
for($k = $num-1; $k >= $i; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 0; $j < $i; $j++ )
{
// Print stars
echo "* ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

Output:

PHP의 패턴

7. Number Pattern

For this number pattern, we will print the numbers in relation to the row number. Thus, digit 1 would be printed once, 2 twice, 3 thrice and so on.

PHP의 패턴

If you would have followed this tutorial line by line, by now you must have understood very well the working of nested loops to print patterns. This pattern also follows the same logic. Instead of stars, we print numbers. Now you ask how do we get the numbers? The answer is- simply through our control variables i and j.

Code:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = 1; $i <= $num; $i++)
{
// inner loop handles indentation
for($k = $num; $k > $i; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 1; $j <= $i; $j++ )
{
// Print numbers
echo $i." ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

Output:

PHP의 패턴

8. Character Pattern

In this pattern, we would print the alphabets ABCDE in a pattern. Starting with A, the subsequent rows would introduce a new alphabet sandwiched between the previous alphabets.

PHP의 패턴

The only trick in this pattern is to get the characters from our control variables. We do this by leveraging the ASCII value of the characters. The ASCII value of A to Z is 65 to 90. So, we calculate the ASCII value in each iteration and print the corresponding character. The chr() function in PHP is used to print a character from the ASCII code.

Code:

<?php
function print_pattern($num)
{
// Outer loop handles number of rows
for ($i = 1; $i <= $num; $i++)
{
// inner loop handles indentation
for($k = $num; $k > $i; $k-- )
{
// Print spaces
echo "  ";
}
// inner loop handles number of stars
for($j = 1; $j <= $i; $j++ )
{
// Print characters
echo chr(64+$j)." ";
}
for($j = $i-1; $j >= 1; $j-- )
{
// Print characters
echo chr(64+$j)." ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 5;
print_pattern($num);
?>

Output:

PHP의 패턴

Print for full alphabets and the pattern looks pretty cool.

PHP의 패턴

9. The Binary Hourglass– Bonus Pattern

This pattern is a dynamic pattern that prints the hourglass relative to the time elapsed, not an actual calculation though. For e.g., if one hour has elapsed, it will print one line of 0s in the upper half and one line of 1s in the lower half.

Code:

<?php
function print_pattern($num, $hour)
{
// Outer loop handles number of rows
for ($i = $num; $i > 0; $i--)
{
// inner loop handles indentation
for($k = $num; $k > $i; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 0; $j < $i; $j++ )
{
// Print characters
if($num-$i < $hour)
echo "0 ";
else
echo "1 ";
}
// go to new line after each row pattern is printed
echo "\n";
}
for ($i = 1; $i < $num; $i++)
{
// inner loop handles indentation
for($k = $num-1; $k > $i; $k-- )
{
// Print spaces
echo " ";
}
// inner loop handles number of stars
for($j = 0; $j <= $i; $j++ )
{
// Print characters
if($num-$i <= $hour)
echo "1 ";else
echo "0 ";
}
// go to new line after each row pattern is printed
echo "\n";
}
}
//Call function and send number of lines as parameter
$num = 8;
$hour = 3;
print_pattern($num, $hour);
?>

Output: 1 hour has elapsed.

PHP의 패턴

Output: 2 hours have elapsed.

PHP의 패턴

Output: 3 hours have elapsed.

PHP의 패턴

And so on.

Conclusion

There is a lot to play with patterns. It’s all about keeping the code logic in mind. Once you get the code logic completely understood, there is no pattern you can’t print.

위 내용은 PHP의 패턴의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.