Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

How can I fix my Strategy Pattern C# program?

My program is that the user can input any string and choose between two option the bubble sort or the quicksort and after that my program will execute the sorting but I am having a problem with the user input.

I don't know how to call the user input into my BubbleSort and also into my Quicksort.

I have red lines in my code specially on Implementaion and userInput. How will I fix it? I am a newbie in creating a strategy pattern.

Here are my errors:

/Users/xhantan/Projects/SortString/SortString/Program.cs(69,29,69,38): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(70,37,70,46): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(67,23,67,36): error CS0161: 'QuickSort.Implementaion(object)': not all code paths return a value
/Users/xhantan/Projects/SortString/SortString/Program.cs(42,30,42,39): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(39,23,39,37): error CS0161: 'BubbleSort.Implementation(object)': not all code paths return a value
/Users/xhantan/Projects/SortString/SortString/Program.cs(28,40,28,54): error CS7036: There is no argument given that corresponds to the required formal parameter 'data' of 'IStrategy.Implementation(object)'
    0 Warning(s)
    6 Error(s)

Here is my code:

using System;

namespace SortStrategyPattern
{
    class Context
    {
        private IStrategy _strategy;

        public Context()
        { }

        public Context(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void SetStrategy(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void UserInput()
        {
            Console.Write("Enter a string: ");

            String userInput = Console.ReadLine();

            userInput = this._strategy.Implementation();
        }
    }

    public interface IStrategy
    {
        object Implementation(object data);
    }

    class BubbleSort : IStrategy
    {
        public object Implementation(object data)
        {
            char temp;
            char[] charStr = userInput.ToCharArray();
            for (int x = 1; x < charStr.Length; x++)
            {
                for (int y = 0; y < charStr.Length - 1; y++)
                {
                    if (charStr[y] > charStr[y + 1])
                    {
                        temp = charStr[y];
                        charStr[y] = charStr[y + 1];
                        charStr[y + 1] = temp;
                    }
                }
            }


            Console.Write("Bubble Sort: ");
            foreach (char input in charStr)
            {
                Console.Write(input + ", ");
            }
        }
    }

    class QuickSort : IStrategy
    {
        public object Implementaion(object data)
        {
            var charArray = userInput.ToCharArray();
            quicksort(charArray, 0, userInput.Length);

            Console.Write("Quick Sort: ");
            foreach (char s in charArray)
            {
                Console.Write(s + ", ");
            }
        }

        static void quicksort(char[] userInput, int start, int end)
        {
            if (start < end)
            {
                int pivotIndex = partition(userInput, start, end);
                quicksort(userInput, start, pivotIndex);
                quicksort(userInput, pivotIndex + 1, end);
            }
        }

        static void swap(char[] userInput, int i, int j)
        {
            char temp = userInput[i];
            userInput[i] = userInput[j];
            userInput[j] = temp;
        }

        static int partition(char[] userInput, int start, int end)
        {
            int pivotIndex = userInput[start];
            int swapIndex = start;
            for (int i = start + 1; i < end; i++)
            {
                if (userInput[i] < pivotIndex)
                {
                    swapIndex++;
                    swap(userInput, i, swapIndex);
                }
            }
            swap(userInput, start, swapIndex);
            return swapIndex;
        }

        public object Implementation(object data)
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            char response;

            do
            {
                Console.WriteLine();
                Console.WriteLine("Choose between the two sorting strategies:");
                Console.WriteLine("	a) - Bubble Sort");
                Console.WriteLine("	b) - Quick Sort");
                Console.WriteLine();
                Console.Write("Your option: ");

                {
                    response = char.Parse(Console.ReadLine());
                }

                Console.WriteLine();

                switch (response.ToString().ToLower())
                {
                    case "a":

                        new BubbleSort();
                        break;


                    case "b":

                        new QuickSort();
                        break;

                    default:
                        Console.WriteLine("Invalid answer. Please enter a valid option.");
                        response = '';
                        break;
                }

            } while (response == '');
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are nearly there. However, let's improve it a little:

Interface

public interface ISort
{
   T[] Sort<T>(T[] data) where T : IComparable;
}

BubbleSort

public class BubbleSort : ISort
{
   public T[] Sort<T>(T[] data) where T : IComparable
   {
      var result = data.ToArray();
      for (var x = 1; x < result.Length; x++)
      {
         for (var y = 0; y < result.Length - 1; y++)
         {
            if (result[y].CompareTo(result[y + 1]) <= 0) continue;
            var temp = result[y];
            result[y] = result[y + 1];
            result[y + 1] = temp;
         }
      }

      return result;
   }
}

QuickSort

public class QuickSort : ISort
{
   public T[] Sort<T>(T[] data) where T : IComparable
   {
      var result = data.ToArray();
      InternalQuickSort(result, 0, result.Length);
      return result;

   }

   private static void InternalQuickSort<T>(T[] data, int start, int end) where T : IComparable
   {
      if (start >= end) return;
      var pivotIndex = Partition(data, start, end);
      InternalQuickSort(data, start, pivotIndex);
      InternalQuickSort(data, pivotIndex + 1, end);
   }

   private static void Swap<T>(T[] data, int i, int j) where T : IComparable
   {
      T temp = data[i];
      data[i] = data[j];
      data[j] = temp;
   }

   private static int Partition<T>(T[] data, int start, int end) where T : IComparable
   {
      var pivotIndex = data[start];
      var swapIndex = start;
      for (var i = start + 1; i < end; i++)
      {
         if (data[i].CompareTo(pivotIndex) >= 0) continue;
         swapIndex++;
         Swap(data, i, swapIndex);
      }

      Swap(data, start, swapIndex);
      return swapIndex;
   }
}

Usage

private static ISort GetSorter(char option)
   => char.ToLower(option) switch
   {
      'a' => new BubbleSort(),
      'b' => new QuickSort(),
      _ => null
   };

static void Main(string[] args)
{
   char response;

   do
   {
      Console.WriteLine();
      Console.WriteLine("Choose between the two sorting strategies:");
      Console.WriteLine("	a) - Bubble Sort");
      Console.WriteLine("	b) - Quick Sort");
      Console.WriteLine("	x) - To Quit");
      Console.WriteLine();
      Console.Write("Your option: ");

      if (!char.TryParse(Console.ReadLine(), out response))
         continue;

      if (response == 'x')
         break;

      var sorter = GetSorter(response);

      if (sorter == null)
         continue;

      Console.Write("Type something to sort: ");

      var data = Console.ReadLine();

      Console.WriteLine();

      var result = sorter.Sort(data.ToCharArray());

      Console.WriteLine(string.Join(", ", result));

   } while (response != 'x');
}

Output

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: a
Type something to sort: qwertyuiop

e, i, o, p, q, r, t, u, w, y

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: b
Type something to sort: qwertyuiop

e, i, o, p, q, r, t, u, w, y

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: x

Additional Resources

Generics (C# Programming Guide)

Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations

IComparable Interface

Defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...