Skip to content

Commit

Permalink
add sierpinski challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
krother committed May 20, 2024
1 parent 315128e commit 81a2417
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 1 deletion.
72 changes: 72 additions & 0 deletions challenges/sierpinski.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
Sierpinski Triangle
===================

**🎯 Construct a Sierpinski Triangle with a Cellular Automaton.**

Consider the following rules:

.. code:: python3
rules = {
' ': ' ',
' #': '#',
' # ': '#',
' ##': ' ',
'# ': '#',
'# #': ' ',
'## ': ' ',
'###': ' ',
}
Now when you start with a string consisting of a single hash flanked by spaces:

::

#

The rules define how the next line looks like.
For the new line you look up character triplets from the original string.
The three triplets `" #", " # ", "# "` involving the original hash result in a new hash each.
So the second line is:

::

###

If you propagate that line once again, the triplets with two hashes reult in a space:

::

# #

If you propagate once again, the first four lines look like:

::

#
###
# #
### ###

Write a program that propagates the following line 32 times:

.. code:: python3
line = " " * 32 + "#" + " " * 32
Add an empty space at the beginning and end of each new line so that the line length stays the same.

.. hint::

Experiment with the rule set defined by the dictionary by changing its values.

What you can practise in this coding challenge
----------------------------------------------

- loops
- string operations
- looking up things in dictionaries

.. seealso::

`Sierpinski Triangle on Wikipedia <https://en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle>__`
2 changes: 1 addition & 1 deletion index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ Coding Challenges
:maxdepth: 1

challenges/ctree.rst
challenges/pyramid.rst
challenges/fizzbuzz.rst
challenges/quiz.rst
challenges/checker.rst
Expand All @@ -70,6 +69,7 @@ Coding Challenges
challenges/querprodukt.rst
challenges/birthdays.rst
challenges/misty_mountains.rst
challenges/sierpinski.rst
challenges/count_words.rst
challenges/spiral.rst

Expand Down
21 changes: 21 additions & 0 deletions solutions/sierpinski.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

code = {
' ': ' ',
' #': '#',
' # ': '#',
' ##': ' ',
'# ': '#',
'# #': ' ',
'## ': ' ',
'###': ' ',
}

N = 32
line = " " * N + "#" + " " * N
for _ in range(N):
print(line)
new = " "
for start in range(len(line) - 2):
sub = line[start: start + 3]
new += code[sub]
line = new + " "

0 comments on commit 81a2417

Please sign in to comment.