Recursion function reverse BYTE - recursion

FUNCTION Y(s : STRING) RETURNS STRING
DECLARE x : INTEGER
x = LENGTH(s)
IF x = 1
THEN
RETURN s
ELSE
RETURN Y(RIGHT(s, x - 1)) + LEFT(s, 1)
// RIGHT above returns rightmost x - 1 characters of string s
// LEFT above returns leftmost character of string s
ENDIF
ENDFUNCTION
How to dry run this recursion when s="BYTE"
For call(4) i get YTE and B
is it correct ??

Related

Why in a Binary Search do we Divide by 2 and not some other higher constant

for example, why don't we do n/3 instead of n/2
Some Maths
The recurrence relation for a binary search using n/2 is
T(n) = T(n/2) + C
which can be simplified to
log2(m) = n
and n/3
T(n) = T(n/3) + C
which can be simplified to
log3(m) = n
so my question is: since log3(m) < log2(m) why do we use n/2
It is true that Ternary search has fewer recursive calls than Binary search (log3(m) < log2(m)) however Ternary search has more comparisons in the worst case than Binary search.
To examine a bit more let's compare Binary and Ternary search algorithms in C++
Binary Search
// A recursive binary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}
Ternary Search
// A recursive ternary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int ternarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid1 = l + (r - l)/3;
int mid2 = mid1 + (r - l)/3;
// If x is present at the mid1
if (arr[mid1] == x) return mid1;
// If x is present at the mid2
if (arr[mid2] == x) return mid2;
// If x is present in left one-third
if (arr[mid1] > x) return ternarySearch(arr, l, mid1-1, x);
// If x is present in right one-third
if (arr[mid2] < x) return ternarySearch(arr, mid2+1, r, x);
// If x is present in middle one-third
return ternarySearch(arr, mid1+1, mid2-1, x);
}
// We reach here when element is not present in array
return -1;
}
In the worst case, Binary search does 2log2(n) + 1 comparisons where Ternary search does 4log3(n) + 1 comparisons
The comparisons boil down to log2(n) and 2log3(n)
Changing bases, 2log3(n) = (2 / log2(3)) * log2(n)
Since (2 / log2(3)) > 1 Ternay search does more comparisons in the worst case
Source

Calculating a value to return using recursion

In this recursive method, I am trying to calculate a number using the initial call mystery5(-23, -48). After going through my first series of if statements, I get to the numbers 23 and 48. Once I get to the else branch of the decision statements, what precedence does the method call have in the equation? Also, does a negative sign in front of the mystery5 method call in the first two if statements indicate that there will be a positive x value if -23 is inserted into the method call (Ex: -mystery5(-23, -48))?
public int mystery5(int x, int y){
if (x < 0) {
return -mystery5(-x, y);
} else if (y < 0) {
return -mystery5(x, -y);
} else if (x == 0 && y == 0) {
return 0;
} else {
return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10;
}
}
So it looks to me that mystery5(1, 0) returns 1. Assuming that is correct, then the call mystery5(-1, 0) would hit that first statement and it would see that x = -1) which is less than zero. This does return -mystery5(-x,y), so when the values for x and y are put in, this is equivalent to return -mystery5(1,0). The - in front of mystery5 flips the sign on the result of the mystery5 function when called. So when mystery5(1,0) returns a 1, that gets negated to -1. And that is the final return value of mystery5(-1,0).

Convert price values with decimals language neutral to an integer in ASP.NET

I want to convert decimal numbers (price values to be exact), which may:
a) contain 1 OR 2 decimals
b) have either a . or , as decimal separator
to an integer value in cents.
So:
3,5 becomes 350
3,50 becomes 350
3.5 becomes 350
3.50 becomes 350
1,000.34 becomes 100034
1.000,34 becomes 100034
Without building a function that does all these checks is there a way in ASP.NET to do this more quickly?
**UPDATE **
Thanks to Nicholas:
I now have this in VB.NET
Private Shared Function ConvertToPriceInCents(s As String) As Integer
If s Is Nothing Then
Throw New ArgumentNullException("s")
End If
If s = "" Then
Throw New ArgumentOutOfRangeException("s", "s must not be empty.")
End If
Dim priceInCents As Integer = 0
Dim scale As Integer = 1
Dim i As Integer = s.Length
' collect the fractional part; identify the decimal separator
While System.Threading.Interlocked.Decrement(i) >= 0
Dim n As Integer = Asc(s(i)) - Asc("0"c)
If n < 0 OrElse n > 9 Then
Exit While
End If
' bail out, we found the decimal separator
priceInCents += n * scale
scale *= 10
End While
Dim decimalSeparator As Char = s(i)
Dim groupSeparator As Char = If(decimalSeparator = "."c, ","c, "."c)
If scale <> 10 AndAlso scale <> 100 Then
Throw New FormatException("value must have 1 or 2 digits to the right of the decimal separator")
End If
If decimalSeparator <> ","c AndAlso decimalSeparator <> "."c Then
Throw New FormatException("Invalid decimal separator")
End If
' if we only found one digit to the right of the decimal separator,
' we need to normalize and scale up by a factor of 10 (so something like 3.5 represents 350 cents)
If scale = 10 Then
scale *= 10
priceInCents *= 10
End If
' get the integer portion of value
' we're being a little lax here and ignoring group separators regardless of position.
' It's a hard thing to do, especially when you consider that
' - group sizes vary across cultures, and
' - aren't necessarily uniform in size.
While System.Threading.Interlocked.Decrement(i) >= 0
Dim c As Char = s(i)
If c = groupSeparator Then
Continue While
End If
Dim n As Integer = Asc(s(i)) - Asc("0"c)
If n < 0 OrElse n > 9 Then
Throw New FormatException("invalid group separator")
End If
priceInCents += n * scale
scale *= 10
End While
' If we haven't thrown an exception yet,
' we have the value in cents: return it.
Return priceInCents
End Function
You write a method that looks something like this:
static int ConvertToPriceInCents( string s )
{
if ( s == null ) throw new ArgumentNullException("s") ;
if ( s == "" ) throw new ArgumentOutOfRangeException("s","s must not be empty." ) ;
int priceInCents = 0 ;
int scale = 1 ;
int i = s.Length ;
// collect the fractional part; identify the decimal separator
while ( --i >= 0 )
{
int n = s[i] - '0' ;
if ( n < 0 || n > 9 ) break ; // bail out, we found the decimal separator
priceInCents += n*scale ;
scale *= 10 ;
}
char decimalSeparator = s[i] ;
char groupSeparator = decimalSeparator == '.' ? ',' : '.' ;
if ( scale != 10 && scale != 100 ) throw new FormatException("value must have 1 or 2 digits to the right of the decimal separator") ;
if ( decimalSeparator != ',' && decimalSeparator != '.' ) throw new FormatException("Invalid decimal separator") ;
// if we only found one digit to the right of the decimal separator,
// we need to normalize and scale up by a factor of 10 (so something like 3.5 represents 350 cents)
if ( scale == 10 )
{
scale *= 10 ;
priceInCents *= 10 ;
}
// get the integer portion of value
// we're being a little lax here and ignoring group separators regardless of position.
// It's a hard thing to do, especially when you consider that
// - group sizes vary across cultures, and
// - aren't necessarily uniform in size.
while ( --i >= 0 )
{
char c = s[i] ;
if ( c == groupSeparator ) continue ;
int n = s[i] - '0' ;
if ( n < 0 || n > 9 ) throw new FormatException("invalid group separator") ;
priceInCents += n*scale ;
scale *= 10 ;
}
// If we haven't thrown an exception yet,
// we have the value in cents: return it.
return priceInCents ;
}

Counting Recursive Calls by Hand

New CS student, studying for a final. I am trying to figure out how many times a recursive method will be called in general. Added the code as an example. If I input abcd and efgh, how many calls based on the size of the Strings? If n is any data size, the # of calls is n(?) in any recursive method.
public static String interweave(String s1, String s2)
{
if (s1.equals("") ) return s2;
else if (s2.equals("")) return s1;
else return "" + interweave(s1.substring(0,s1.length()-1), s2.substring(0,s2.length()-1))
+s1.charAt(s1.length()-1)+s2.charAt(s2.length()-1);
}
Notice that in your question, at each recursive step you reduce by one the size of both strings until either one of them has length zero (the base cases of the recursion). It's easy to see that the number of recursive calls is min(m, n) + 1, where m is the initial length of s1 and n is the initial length of s2.
For example, if s1 = "abc" and s2 = "de" it will take 2 recursive calls to traverse s2 (the string with the minimum length) plus one extra call for exiting at the base case, therefore min(s1.length(), s2.length()) + 1 == 3. You can test it programmatically like this:
static int counter;
public static String interweave(String s1, String s2) {
counter++;
if (s1.equals(""))
return s2;
else if (s2.equals(""))
return s1;
else
return interweave(s1.substring(0, s1.length()-1), s2.substring(0, s2.length()-1))
+ s1.charAt(s1.length()-1)+s2.charAt(s2.length()-1);
}
public static int count(String s1, String s2) {
counter = 0;
interweave(s1, s2);
return counter;
}
Now when you run the following statements, the formula works as expected:
// s1.length() == s2.length()
System.out.println(count("abcde", "fghij"));
> 6
// s1.length() > s2.length()
System.out.println(count("abcde", "fg"));
> 3
// s1.length() < s2.length()
System.out.println(count("ab", "cdefg"));
> 3
The characters don't mean anything just the length. You could convert this to a numeric problem as follows:
public static String interweave(int s1, int s2)
{
if (s1 == 0) return s2;
else if (s2 == 0) return s1;
else return interweave(s1-1, s2-1)+2;
}

How to evaluate an expression in prefix notation

I am trying to evaluate a list that represents an expression in prefix notation. Here is an example of such a list:
[+, [sin, 3], [- 10 5]]
What is the best way to evaluate the value of the list
It will be simpler if you used postfix instead of prefix. See Reverse Polish Notation (RPN). Given an expression in RPN, it is easy to evaluate that using just one stack.
But since you asked for a way to evaluate prefix expressions without recursion and using stacks (for a possibly simpler way, see EDIT: below), here is one way:
We can do this using two stacks.
One stack (call it Evaluation) holds the operators (like +, sin etc) and operands (like 3,4 etc) and the other stack (call it Count) holds a tuple of the number of operands left to be seen + the number of operands an operator expects.
Anytime you see an operator, you push the operator onto the Evaluation stack and push the corresponding tuple onto the Count stack.
Anytime you see an operand (like 3,5 etc), you check the top tuple of the Count stack and decrement the number of operands left to be seen in that tuple.
If the number of operands left to be seen becomes zero, you pop the tuple from the Count stack. Then from the Evaluation stack you pop off the number of operands required (you know this because of the other value of the tuple), pop off the operator and do the operation to get a new value, (or operand).
Now push the new operand back on the Evaluation stack. This new operand push causes you to take another look at the top of the Count stack and you do the same thing we just did (decrement the operands seen, compare with zero etc).
If the operand count does not become zero, you continue with the next token in the input.
For example say you had to evaluate + 3 + 4 / 20 4
The stacks will look like (left is the top of the stack)
Count Evaluation Input
+ 3 + 4 / 20 4
(2,2) + 3 + 4 / 20 4
(2,1) 3 + + 4 / 20 4
(2,2) (2,1) + 3 + 4 / 20 4
(2,1) (2,1) 4 + 3 + / 20 4
(2,2) (2,1) (2,1) / 4 + 3 + 20 4
(2,1) (2,1) (2,1) 20 / 4 + 3 + 4
(2,0) (2,1) (2,1) 4 8 / 4 + 3 +
Since it has become zero, you pop off two operands, the operator /
and evaluate and push back 5. You pop off (2,0) from the Count stack.
(2,1) (2,1) 5 4 + 3 +
Pushing back you decrement the current Count stack top.
(2,0) (2,1) 5 4 + 3 +
Since it has become zero, you pop off 5,4 and + and evaluate and push back 9.
Also pop off (2,0) from the count stack.
(2,0) 9 3 +
12
EDIT:
A friend suggested a way to do this without multiple stacks:
Start from the end, go to the first operator. The tokens to the right of that will be operands. Evaluate and redo. Seems much simpler than doing it with two stacks. We can use a doubly linked list to represent the input which we change during processing. When you evaluate, you delete nodes, and then insert the result. Or you could perhaps just use one stack.
KISS, evaluate in reverse as a postfix expression.
The way I see it you have two options. Either go left to right or right to left (as paul suggested above). Both methods are demonstrated in the code below.
public static class Evaluator
{
public static double EvaluatePrefix(string expr)
{
if (expr == null) throw new ArgumentNullException("expr");
var symbols = expr.Split(',');
var stack = new Stack<Symbol>();
foreach (var symbol in symbols)
{
double operand;
if (!double.TryParse(symbol, out operand)) //encountered an operator
{
stack.Push(new Operator(symbol));
continue;
}
//encountered an operand
if (stack.Count == 0) throw new ArgumentException("Invalid expression");
double right = operand;
var leftOperand = stack.Peek() as Operand;
while (leftOperand != null)
{
stack.Pop(); //pop left operand that we just peeked
if (stack.Count == 0) throw new ArgumentException("Invalid expression");
double result = Calculate(leftOperand.Value, right, ((Operator)stack.Pop()).OperatorChar);
right = result;
leftOperand = (stack.Count == 0) ? null : stack.Peek() as Operand;
}
stack.Push(new Operand(right));
}
if (stack.Count != 1) throw new ArgumentException("Invalid expression");
var operandSymbol = stack.Pop() as Operand;
if (operandSymbol == null) throw new ArgumentException("Invalid expression");
return operandSymbol.Value;
}
public static double EvaluatePrefixAlternative(string expr)
{
if (expr == null) throw new ArgumentNullException("expr");
double d;
var stack = new Stack<Symbol>(
expr.Split(',').Select(s => double.TryParse(s, out d) ? (Symbol) new Operand(d) : new Operator(s)));
var operands = new Stack<double>();
while (stack.Count > 0)
{
var symbol = stack.Pop();
var operand = symbol as Operand;
if (operand != null)
{
operands.Push(operand.Value);
}
else
{
if (operands.Count < 2) throw new ArgumentNullException("expr");
operands.Push(Calculate(operands.Pop(), operands.Pop(), ((Operator) symbol).OperatorChar));
}
}
if (operands.Count != 1) throw new ArgumentNullException("expr");
return operands.Pop();
}
private static double Calculate(double left, double right, char op)
{
switch (op)
{
case '*':
return (left * right);
case '+':
return (left + right);
case '-':
return (left - right);
case '/':
return (left / right); //May divide by zero !
default:
throw new ArgumentException(string.Format("Unrecognized operand {0}", op), "op");
}
}
abstract class Symbol
{
}
private class Operand : Symbol
{
public double Value { get; private set; }
public Operand(double value)
{
Value = value;
}
}
private class Operator : Symbol
{
public char OperatorChar { get; private set; }
public Operator(string symbol)
{
if (symbol.Trim().Length != 1) throw new ArgumentException("Invalid expression");
OperatorChar = symbol[0];
}
}
}
Some tests:
[TestMethod]
public void TestPrefixEvaluation()
{
Assert.AreEqual(5, Evaluator.EvaluatePrefix("-,*,/,15,-,7,+,1,1,3,+,2,+,1,1"));
Assert.AreEqual(4, Evaluator.EvaluatePrefix("/,-,*,2,5,*,1,2,-,11,9"));
Assert.AreEqual(5, Evaluator.EvaluatePrefixAlternative("-,*,/,15,-,7,+,1,1,3,+,2,+,1,1"));
Assert.AreEqual(4, Evaluator.EvaluatePrefixAlternative("/,-,*,2,5,*,1,2,-,11,9"));
}

Resources