Coding Challenge #3 - Recursion
-
FUZE Coding Challenge #3
Hi everyone. Welcome to the 3rd challenge. The rules are:-
Post your Fuze code below. (But if the code is too long to type you can post the ID of the project instead).
-
There will be 2 tasks per challenge, a Beginners challenge and an Advanced challenge. Anyone can participate in any one of them or both tasks.
-
We are always open to suggestions!
-
Have fun coding!!
TASK #1
LEVEL: Beginner
Given a string. Recursively walk through the string and return the number of numeric characters within that string.TASK #2
LEVEL: Advanced
Write a program that can solve the Puzzle "Towers of Hanoi". You are given 3 towers labels "A", "B" and "C" as well as any number of discs which are placed on tower "A". You must move all the discs from tower "A" to tower "C" and show each move by the program printed as a string (ex: "move A to B").
Here is more information on the Towers of Hanoi: https://en.wikipedia.org/wiki/Tower_of_Hanoi -
-
Oh hey, I still exist. Very fun puzzles! Here are my solutions:
print(task1("1+1=2"), chr(10)) print(chr(10)) task2(3) update() loop repeat function task1(text) return countNumeric(text, 0) function countNumeric(text, count) if text != "" then var char = chrVal(text[0]) text = text[1:] count = countNumeric(text, count + (char > 47 and char < 58)) endIf return count function task2(discs) return towerOfHanoi(discs, "A", "B", "C") function towerOfHanoi(discs, tower1, tower2, tower3) if discs then towerOfHanoi(discs - 1, tower1, tower3, tower2) print("move ", tower1, " to ", tower3, chr(10)) towerOfHanoi(discs - 1, tower2, tower1, tower3) endIf return 0
prints:
3 move A to C move A to B move C to B move A to C move B to A move B to C move A to C
-
@scrubz Shouldn’t the solution to task 1 print the number of numeric characters?
-
@vinicity Oh, whoops! That's what I get for skimming through the instructions haha.
-
I wanted to give this a try. But Scrubz solution cant be beaten, its nice. But maybe diversity is welcome.
A bad game can still have a good story, so, here is the story of Task 1: I call this "lazy recursion", the code uses recursion, but it just hands over an index, and always the same text variable. So, it does use a lot of memory - maybe you could use this for memory testing (somehow) ;-). By the way I probably introduced a new concept: the measurement of numerics: it answers the question "how numeric is a variable containing text?" (I had no clue how to name this recursive function, because it tests only one char but also sums up all found numeric values).
Task 1
function howNumericIsCharAtIndexAndAfter(index, text) isNumeric = false if index >= len(text) then else c = chrVal(text[index]) if c >= chrVal("0") and c <= chrVal("9") then isNumeric = true endif index += 1 isNumeric += howNumericIsCharAtIndexAndAfter(index, text) endif return isNumeric t = "ab12cd34" print(howNumericIsCharAtIndexAndAfter(0, t))
output:
4