PHP Hourglass Algorithm

Nexmoe October 30, 2020
This article is an AI translation and may contain semantic inaccuracies.

L1-002 Print Hourglass

L1-002 Print Hourglass (20 points)

Write a program to print an hourglass shape using a given symbol. For example, given 17 ”*”, print:

*****
 ***
  *
 ***
*****

An “hourglass” means each line has an odd number of symbols; each line is center‑aligned; adjacent lines differ by 2 symbols; the count decreases down to 1 then increases back up; the first and last lines have the same number of symbols.

Given N symbols, you may not be able to form a perfect hourglass. You should print the largest possible hourglass using as many symbols as possible.

Input format:

One line containing a positive integer N (≤1000) and a symbol, separated by a space.

Output format:

First output the largest hourglass using the given symbol, then output the number of remaining unused symbols on the last line.

Sample input:

19 *

Sample output:

*****
 ***
  *
 ***
*****
2

My trash algorithm

L1-002 Print Hourglass (20 points)

<?php
    $arr = explode(' ',rtrim(fgets(STDIN)));
    $n = 0;
    for($x=0; $n<$arr[0]; $x++){
        $t = $x*2-1;
        if($x > 1){
            $n = $n + $t*2;
        }else{
            $n = $n + $t;
        }
    }
    $n = $n - $t*2 + 1;

    $x2 = $x - 1;
    while($x2>0){
        $x2 = $x2-1;
        $x3=$x2*2-1;
        if($x3>0){
            for($spa=$x-$x2-2; $spa>0 ; $spa--){
                echo " ";
            }
            for($i=0; $i<$x3 ; $i++){
                echo $arr[1];
            }
            echo "\n";
        }
    }
    $x2 = $x - 2;
    while($x2>0){
        $x2 = $x2-1;
        $x3=$x2*2-1;
        if($x3>0){
            for($spa=$x-$x2-2; $spa>0 ; $spa--){
                echo " ";
            }
            for($i=0; $i<$x3 ; $i++){
                echo $arr[1];
            }
            echo "\n";
        }
    }

    $x2 = 0;
    $x3 = $x2*2-1;
    for($spa=$x-$x2-2; $spa>0 ; $spa--){
        echo " ";
    }
    for($i=0; $i<$x3 ; $i++){
        echo $arr[1];
    }
    echo "\n";

    $x2 = $x - 1;
    while($x2>0){
        $x2 = $x2-1;
        $x3=$x2*2-1;
        if($x3>0){
            for($spa=$x-$x2-2; $spa>0 ; $spa--){
                echo " ";
            }
            for($i=0; $i<$x3 ; $i++){
                echo $arr[1];
            }
            echo "\n";
        }
    }

    echo $arr[0]-$n;
?>