Oct 2, 2011 12:53 AM
(This post was last modified: Oct 2, 2011 12:55 AM by Ethereal.)
Earlier, I lost track of the total number of posts I had in TAFWA. For those who don't know, that's just TA's way of keeping track of helpful posts. They are stored in this format:
I wanted to add up all of the amounts, so I wrote a quick little recursive algorithm, for a little practice, I guess.
By the way, I know this isn't a beautiful algorithm, but it works and that is what matters; its an example to help people understand basic recursion.
Input:
Output:
Works for anything up to:
which is enough for its use.
So yeah, just a basic example. Hadn't released anything public for some time, but decided I might as well post this.
Code
(Amount) Month Day, YearI wanted to add up all of the amounts, so I wrote a quick little recursive algorithm, for a little practice, I guess.
By the way, I know this isn't a beautiful algorithm, but it works and that is what matters; its an example to help people understand basic recursion.
PHP Code
<?php
private int GetTotalNumber(string text)
{
int count = 0;
foreach (string line in text.Split('\n'))
{
count += GetNumber(line.Trim());
}
return count;
}
private int GetNumber(string line, int counter = 0, int temp = 0)
{
if (line == "") return temp;
else if (line[counter] == '(') return GetNumber(line, counter + 1, temp);
else if (line[counter] == ')') return temp;
else if (char.IsNumber(line[counter]))
if (char.IsNumber(line[counter + 1]))
{
string tempStr = line.Substring(counter, counter + 1);
return GetNumber(line, counter + 2, temp + Convert.ToInt32(tempStr));
}
else
return GetNumber(line, counter + 1, temp + (((char)(Convert.ToInt32(line[counter])))) - '0');
else
return temp;
}
Input:
Code
(15)
(3)
(8)
(7)Output:
Code
33Works for anything up to:
Code
(99)which is enough for its use.
So yeah, just a basic example. Hadn't released anything public for some time, but decided I might as well post this.


