Skip to content

Instantly share code, notes, and snippets.

@Earu
Last active May 17, 2022 22:48
Show Gist options
  • Save Earu/03fd55390dffd6c3bb8b410fff69feec to your computer and use it in GitHub Desktop.
Save Earu/03fd55390dffd6c3bb8b410fff69feec to your computer and use it in GitHub Desktop.
Code for the "Simple Text Editor" challenge on hackerrank.com
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Operation
{
protected readonly Stack<Operation> operationStack;
protected readonly string context;
public Operation(Stack<Operation> operationStack, string ctx)
{
this.operationStack = operationStack;
this.context = ctx;
}
public bool IgnoreOperation { get; set; } = false;
public virtual string Execute(string input)
{
return this.context;
}
public string Undo()
{
return this.context;
}
}
class AppendOperation : Operation
{
public AppendOperation(Stack<Operation> operationStack, string ctx) : base(operationStack, ctx) {}
public override string Execute(string input)
{
return this.context + input;
}
}
class DeleteOperation : Operation
{
public DeleteOperation(Stack<Operation> operationStack, string ctx) : base(operationStack, ctx) {}
public override string Execute(string input)
{
int nbToDelete = Convert.ToInt32(input);
return this.context.Substring(0, this.context.Length - nbToDelete);
}
}
class PrintOperation : Operation {
public static StringBuilder output = new StringBuilder();
public PrintOperation(Stack<Operation> operationStack, string ctx) : base(operationStack, ctx)
{
this.IgnoreOperation = true;
}
public override string Execute(string input)
{
int indexToPrint = Convert.ToInt32(input) - 1;
output.AppendLine(this.context[indexToPrint].ToString());
return this.context;
}
}
class UndoOperation : Operation
{
public UndoOperation(Stack<Operation> operationStack, string ctx) : base(operationStack, ctx)
{
this.IgnoreOperation = true;
}
public override string Execute(string input)
{
Operation lastAction = this.operationStack.Pop();
return lastAction.Undo();
}
}
class Solution
{
static void Main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
Stack<Operation> operations = new Stack<Operation>();
string ctx = string.Empty;
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < n; i++) {
string[] args = Console.ReadLine().Split(' ');
Operation operation = null;
switch (args[0]) {
case "1":
operation = new AppendOperation(operations, ctx);
break;
case "2":
operation = new DeleteOperation(operations, ctx);
break;
case "3":
operation = new PrintOperation(operations, ctx);
break;
case "4":
operation = new UndoOperation(operations, ctx);
break;
}
ctx = operation.Execute(args.Length > 1 ? args[1] : null);
if (!operation.IgnoreOperation)
operations.Push(operation);
}
Console.WriteLine(PrintOperation.output.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment