Rysowanie prostokąta w aplikacji konsolowej

0

Witam,

Znalazłem takie zadanie i szczerze mówiąc nie mam pojęcia jak to zrobić bez pętli.


// Create a function makeRectangle that will print an m by n rectangle of * to the screen

// For example, makeRectangle(3,5) should print a 3 by 5 rectangle of *, as shown below:

//  * * *
//  * * *
//  * * *
//  * * *
//  * * *

// Don't  use loops for this one! :)

2
def makeRectangle(m, n):
    print("\n".join(["*" * m] * n))

poza tym weź sobie zobacz, co robią poszczególne elementy, żeby zrozumieć (do obadania w konsoli):

["*" * 3] # ['***']
["*" * 3] * 4 # ['***', '***', '***', '***']
"::".join(["kot", "pies", "kaczka"]) # 'kot::pies::kaczka'
# tylko tam mamy "\n" czyli znak nowej linii, zamiast "::"

print("test\ndruga linia") 
# drukuje:
#test
#druga linia
0

Nice, ale trochę cheatujesz:) pythonową składnią; tak jest, imo, najbardziej "agnostycznie", pseudokod:

def print_line(n):
    if n == 0:
        return ""
    print("*", end=" ")
    print_line(n - 1)


def rect(n, m):
    if m == 0:
        return ""
    print_line(n)
    print()
    rect(n, m - 1)


if __name__ == "__main__":
    rect(3, 5)
2

Skoro w dziale o javascripcie, to można też z użyciem biblioteki standardowej: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat .

0

Wygląda to tak ale nie wiem dlaczego ostatni wiersz drukuje undefine.


function makeRectangle(n, times) {

    const str = "*".repeat(n);
    
    if ( times === 1 ) {
        console.log(str);
    } else {
        console.log(str);
        makeRectangle(n, times - 1)
    }
  }

  console.log(makeRectangle(3, 5));
3
Glt87 napisał(a):

Wygląda to tak ale nie wiem dlaczego ostatni wiersz drukuje undefine.

console.log(makeRectangle(3, 5));

Ten ostatni console.log jest niepotrzebny, bo funkcja nic nie zwraca (czyli dostajemy undefined)

EDIT:

Możesz też najpierw zbudować cały prostokąt i dopiero na sam koniec w jednym console.logu go wyświetlić

function makeRectangle(n, times) {
   const stars = '*'.repeat(n) + '\n';
   const fullRectangle = stars.repeat(times);

   console.log(fullRectangle);
} 

1 użytkowników online, w tym zalogowanych: 0, gości: 1