ホームページ  >  記事  >  バックエンド開発  >  PHP のパターン

PHP のパターン

王林
王林オリジナル
2024-08-29 13:11:271003ブラウズ

PHP のパターン プログラミングとは何ですか?画面上にある種のパターンを印刷するのはプログラミングの技術です。これは、パターンを形成する一連の数字、文字、または特殊文字です。パターンの最も単純な例は、フィボナッチ数列 (1、1、2、3、5、8、13、21、34 など) です。それから、画面上のデザインである他のパターン、たとえば星のピラミッドもあります。したがって、基本的に、パターン プログラミングは単に画面上にパターンを印刷することです。

広告 このカテゴリーの人気コース PHP 開発者 - 専門分野 | 8コースシリーズ | 3 つの模擬テスト

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

この記事では、PHP を使用してパターンをコーディングします。でも心配しないでください。コツを掴めば、言語ごとに構文が異なるだけです。ロジックは常に同じです。

PHP のパターンの例

  • プログラムに取り掛かる前に、コーディング パターンの基本ロジックを理解しましょう。パターンは常にネストされたループ (ほとんどはネストされた for ループ) を通じてプログラムされます。これは、ループの方が構文的に理解しやすく、簡潔であるためです。
  • 外側のループは常に行数に関係します。したがって、5 行にわたるパターンを印刷する必要がある場合、外側のループは常に 5 回実行されるとします。
  • 内側のループは常に各行の要素の数に関係します。したがって、最初の行に 1 つの星、2 行目に 2 つの星などを出力する必要がある場合、内部ループがこのロジックを制御するとします。
  • パターンによっては、複数の内部ループまたは 3 レベルのネストされたループが存在する場合があります。また、目的のパターンを生成するには、スペースとタブが関与します。

以上のことを念頭に置いて、パターンをコーディングしてみましょう。

1.スターハーフピラミッド

これは印刷する最も簡単なパターンです。後続の行に増加する星の数を出力します。最初の行には 1 つ星、2 行目には 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 のパターン

適切なインデントを実現するには、スペースを使用してから星を印刷します。したがって、内部ループは 2 つあり、1 つはスペースの数を制御し、もう 1 つは星の数を制御します。

注: k ループ内のスペースの数はダブルスペースであることに注意してください。これは、星とともに単一のスペースも印刷するためです。これにより、パターンが混雑したプリントではなく完成した外観になります。完全なピラミッドを印刷するときにこれを活用します。

コード:

<?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 つの星があり、2 番目の行には 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。