In: Computer Science
Use C#
RECURSION - PAPERFOLDS
Concept Summary:
1. Recursion
For this assignment1 you will design a recursive method and the main program that calls the recursive method.
Description
Take a piece of paper and fold it in half. Unfold it and there is one fold, which I'll signify with a "v". If you fold the paper twice (always keeping the folds in the same direction and the creases parallel), it will have three folds when you unfold it, and they will be in a "^ v v" pattern. Fold a piece of paper three times, and you will see "^ ^ v v ^ v v" as the sequence of folds.
Folding a piece of already folded paper sounds a lot like recursion, and indeed it is. In case you can't see the algorithm, here it is:
If you fold a paper once, the fold pattern is "v".
For additional folds, it is the pattern you have only reversed and flipped over, then a
"v" fold, and then the pattern you already have tacked on the end.
Submission Guidelines:
Turn in 1 program file that calls the recursive method from the Main program.
Assignment:
Write a static method, paperFold, which is a recursive routine that returns a string representing the fold pattern for a paper folded n times. The driver program that calls the paperFold () method
Write one or more helper methods to generate a string that takes a fold sequence and returns it reversed and flipped over such that a "v ^ ^ ^" becomes a "v v v ^".
Hint: You could write one to reverse the string and one to flip the string.
As in many recursive solutions, expect the fold method to be extremely simple (and of course recursive).
Skeleton Code
C# Version:
public static void Main (string[] args) { for(int i=1;i<5;i++)
{
string fold_string=paperfold(i);
Console.WriteLine("For "+i+" folds we get: "+fold_string+"\n"); }
}
Sample Output:
For 1 folds we get: v
For 2 folds we get: ^vv
For 3 folds we get: ^^vv^vv
For 4 folds we get: ^^v^^vvv^^vv^vv
Solution :
Here's the code in C # :-
using System;
class Fold
{
public static void Main() //Main function
{
Console.WriteLine("Enter n");
int n = Convert.ToInt32(Console.ReadLine());
for(int i =1;i<n;i++)
Console.WriteLine("For " +i+ " folds, we get : "+paperFold(i));
}
public static string reverse(string s) // Helper function to reverse string
{
int n = s.Length;
string ret = "";
for (int i = 1; i <= n;i++)
{
ret = ret + s[n-i];
}
return ret;
}
public static string flip(string s) // Helper function to flip string
{
string ret ="";
for (int i = 0; i<s.Length;i++)
{
if (s[i].Equals('v'))
ret = ret + '^';
else
ret = ret + 'v';
}
return ret;
}
public static string paperFold(int i) //Constructing paperfold recursively
{
if (i==1)
return "v";
string ret = flip(reverse(paperFold(i-1))) + "v" + paperFold(i-1);
return ret;
}
}
Since the question mentions a purely recursive approach, I haven't used memoization at all. A way to make this program run faster would be to store the output of paperFold(i) in an array so that we do not have to reconstruct it when it is called once again.