Skip to content

Instantly share code, notes, and snippets.

@jordi-petit
Last active April 26, 2018 07:28
Show Gist options
  • Save jordi-petit/11f30e11c42623287f62e54aedce1d8a to your computer and use it in GitHub Desktop.
Save jordi-petit/11f30e11c42623287f62e54aedce1d8a to your computer and use it in GitHub Desktop.
AP1 2017-10-11 Recursivitat 2
# Floc de Koch
# (vegeu https://en.wikipedia.org/wiki/Koch_snowflake)
import turtle # https://docs.python.org/3.6/library/turtle.html
# pinta el segment bàsic de Koch _/\_ amb segments de llargada long i passos passes recursives
def figura(long, passos):
if passos == 1:
turtle.forward(long)
turtle.left(60)
turtle.forward(long)
turtle.right(120)
turtle.forward(long)
turtle.left(60)
turtle.forward(long)
else:
figura(long/3, passos-1)
turtle.left(60)
figura(long/3, passos-1)
turtle.right(120)
figura(long/3, passos-1)
turtle.left(60)
figura(long/3, passos-1)
# pinta el floc de Koch
def floc(long, passos):
figura(long, passos)
turtle.right(120)
figura(long, passos)
turtle.right(120)
figura(long, passos)
floc(100, 3)
input() # espera a tancar la finestra
// Torres de Hanoi
#include <iostream>
using namespace std;
// Mou n discos de ori a dst passant per aux.
void hanoi(int n, char ori, char dst, char aux) {
if (n != 0) {
hanoi(n - 1, ori, aux, dst);
cout << "moure de " << ori << " a " << dst << endl;
hanoi(n - 1, aux, dst, ori);
}
}
int main() {
int n;
cin >> n;
hanoi(n, 'A', 'C', 'B');
}
@jordi-petit
Copy link
Author

Tornant-ho a mirar: la funció figura() es pot simplificar més:

def figura(long, passos):
    if passos == 0:
        turtle.forward(long)
    else:
        figura(long/3, passos-1)
        turtle.left(60)
        figura(long/3, passos-1)
        turtle.right(120)
        figura(long/3, passos-1)
        turtle.left(60)
        figura(long/3, passos-1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment