예제 #1
0
 public static ConsoleInput ReadInput()
 {
     var result = new ConsoleInput[1];
     var resultCount = 0;
     WinCon.ReadConsoleInput(hConsoleInput, result, 1, ref resultCount);
     return result[0];
 }
예제 #2
0
파일: Server.cs 프로젝트: Bart97/BeemuSharp
        public Server(IPAddress addr, ushort port)
        {
            if (Program.Taskbar != null)
                Program.Taskbar.SetProgressState(TaskbarProgressBarState.Indeterminate);
            ScriptHost = ScriptHost.Create();

            socket = new TcpListener(addr, port);
            Program.Logger.LogInfo(String.Format("Listening on {0}:{1}", addr, port));
            thread = new Thread(AcceptClients);

            pingTimer = new Timer(new TimerCallback(this.PingClients), new AutoResetEvent(false), 60000, 60000);
            npcRespawnTimer = new Timer(new TimerCallback(this.RespawnNPCs), new AutoResetEvent(false), 2000, 1000);

            Database = new Database("eoserv.db4o");
            Program.Logger.LogSuccess("Database loaded.");
            Global = new GlobalChat();
            clients = new Dictionary<ushort, IClient>();
            maps = new Dictionary<ushort, IMap>();
            characters = new List<Character>();

            ItemData = new EIF("./data/dat001.eif");
            Program.Logger.LogSuccess(String.Format("Loaded {0} items.", ItemData.Count));
            NpcData = new ENF("./data/dtn001.enf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} NPCs.", NpcData.Count));
            ClassData = new ECF("./data/dat001.ecf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} classes.", ClassData.Count));
            SpellData = new ESF("./data/dsl001.esf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} spells.", SpellData.Count));
            MapData = new MapDataSet("./data/maps/");
            Program.Logger.LogSuccess(String.Format("Loaded {0} maps.", MapData.Count));

            /*ItemData.GetPubFile("./tmp/");
            NpcData.GetPubFile("./tmp/");
            ClassData.GetPubFile("./tmp/");
            SpellData.GetPubFile("./tmp/");*/

            foreach (KeyValuePair<ushort, MapData> entry in MapData)
            {
                entry.Value.GetPubFile("./tmp/");
                maps.Add(entry.Key, new Map(entry.Value));
                maps[entry.Key].SpawnNpcs(this);
            }

            if (Program.Taskbar != null)
                Program.Taskbar.SetProgressState(TaskbarProgressBarState.NoProgress);

            slnClient = new SLNClient();
            consoleInput = new ConsoleInput(this);

            Program.Logger.LogSuccess("Server started");
        }
예제 #3
0
            static bool ConsoleInput_KeyPressedOverride_Prefix(ConsoleInput __instance, ref bool __result)
            {
                KeyCode keyCode = __instance.processingEvent.keyCode;

                if (keyCode != KeyCode.Tab || __instance.text.Length == 0 || __instance.caretPosition != __instance.text.Length)
                {
                    return(true);
                }

                string ret = tryCompleteText(__instance.text);

                if (ret != "")
                {
                    __instance.text = ret;
                }

                __instance.caretPosition = __instance.text.Length;

                __result = true;
                return(false);
            }
예제 #4
0
 public void Draw()
 {
     switch (State)
     {
     case ConsoleState.Closing:
     case ConsoleState.Opening:
     case ConsoleState.Open:
         SpriteBatch.Begin();
         // Draw background.
         if (BgRenderer.Texture != null)
         {
             BgRenderer.Draw();
         }
         else
         {
             SpriteBatch.Draw(
                 WhiteTexture,
                 WindowArea,
                 new RectangleF(
                     0,
                     0,
                     WindowArea.Width,
                     WindowArea.Height),
                 BackgroundColor);
         }
         // Draw bottom border if enabled (thickness larger than zero).
         if (BottomBorderThickness > 0)
         {
             SpriteBatch.Draw(
                 WhiteTexture,
                 new RectangleF(0, WindowArea.Bottom, WindowArea.Width, BottomBorderThickness),
                 BottomBorderColor);
         }
         // Draw output and input strings.
         ConsoleOutput.Draw();
         ConsoleInput.Draw();
         SpriteBatch.End();
         break;
     }
 }
예제 #5
0
        public void ProgramMain_hit_third()
        {
            using (ConsoleOutput cout = new ConsoleOutput())
            {
                using (ConsoleInput cin = new ConsoleInput(new List <Double> {
                    3.5, 4.5,
                    10.0, 1.0, -2, -10, 3.0, 4.0, 0.0, 0.0
                }))
                {
                    Biathlon.Program.Main();

                    string expected = String.Format(
                        "Biathlon{0}Initial X: Initial Y: " +
                        "X: Y: " +
                        "X: Y: " +
                        "X: Y: " +
                        "You hit it!{0}",
                        Environment.NewLine);
                    Assert.AreEqual(expected, cout.GetOuput());
                }
            }
        }
예제 #6
0
        private static void Add()
        {
            //get the existing list of players
            _playerList = _playerService.GetAll();

            //instantiate the new player object
            Player player = new Player();

            //for each property get info from the user
            player = ConsoleInput.GetUserInput <Player>();

            //get the current date and time for DateAdded
            player.DateAdded = DateTime.Now;

            //call the player service and add the player
            player = _playerService.Add(player);

            //give the user feed back--pause for one second on screen
            string message = $"Success: Added a new player ID: {player.Player_Id}";

            ConsoleMessage.ShowMessage(message);
        }
예제 #7
0
	public static void Introduction()
	{
		Console.Write("\t\t\t\tWord Game:\n");
		Console.Write("Enter '1' for use the example\n");
		Console.Write("\t or\n");
		Console.Write("Enter '2' for use your values\n");
		short entered;
		do
		{
			entered = short.Parse(ConsoleInput.ReadToWhiteSpace(true));

		} while (entered != 1 && entered != 2);

		if (entered == 1)
		{
			Example();
		}
		else
		{
			Submit_your_values();
		}
	}
예제 #8
0
        public static User CreateUser()
        {
            string firstName = ConsoleInput.GetInputOnText("Enter first name");
            string lastName  = ConsoleInput.GetInputOnText("Enter last name");
            string login     = ConsoleInput.GetInputOnText("Enter login");
            string password  = "";

            do
            {
                password = ConsoleInput.GetHiddenConsoleInput("Enter password");
                string passwordToCheck = ConsoleInput.GetHiddenConsoleInput("Enter password again");
                if (passwordToCheck != password)
                {
                    Console.WriteLine("Error: passwords differ");
                    continue;
                }
                break;
            } while (true);
            User newUser = new User(firstName, lastName, login, password);

            return(newUser);
        }
예제 #9
0
        static void Main()
        {
            ExpenseHandler william = new ExpenseHandler(new Employee("William Worker", Decimal.Zero));
            ExpenseHandler mary    = new ExpenseHandler(new Employee("Mary Manager", new Decimal(1000)));
            ExpenseHandler victor  = new ExpenseHandler(new Employee("Victor Vicepres", new Decimal(5000)));
            ExpenseHandler paula   = new ExpenseHandler(new Employee("Paula President", new Decimal(20000)));

            william.RegisterNext(mary);
            mary.RegisterNext(victor);
            victor.RegisterNext(paula);

            Decimal expenseReportAmount;

            if (ConsoleInput.TryReadDecimal("Expense report amount:", out expenseReportAmount))
            {
                IExpenseReport expense = new ExpenseReport(expenseReportAmount);

                ApprovalResponse response = william.Approve(expense);

                Console.WriteLine("The request was {0}.", response);
            }
        }
예제 #10
0
        public void RunHelloWorld()
        {
            // Arrange
            ConsoleController controller = new ConsoleController((Repos.ILogRepository) new Mock <Repos.ILogRepository>(), (Repos.IFiddleRepository) new Mock <Repos.IFiddleRepository>());

            string helloWorldCode = OpenFiddle.Resources.CodeSamples.HelloWorldConsoleCSharp;

            ConsoleInput input = new ConsoleInput
            {
                Id       = "FakeHash",
                Code     = helloWorldCode,
                Language = Models.Shared.Language.CSharp
            };

            // Act
            var result = controller.Run(input);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(input.Id, result.Id);
            Assert.AreEqual(helloWorldCode, result.Code);
            Assert.AreEqual("Hello World\r\n", result.Output);
        }
        private static void Main(string[] args)
        {
            Console.CursorVisible = false;

            var player       = ((char)2).ToString();
            var position     = 1;
            var consoleInput = new ConsoleInput();

            var gameController = new GameController(
                player,
                position,
                maze,
                wall,
                consoleInput,
                new ConsoleRenderer());

            var playerController = new PlayerController(consoleInput, maze, wall, gameController.EndGame, player, position, airPixel);

            gameController.Start(playerController);

            Console.WriteLine("Game Over!");
            Console.ReadKey();
        }
예제 #12
0
        public static void Log(object text, ConsoleColor color)
        {
            ConsoleOutput output = (ConsoleOutput)fiOutput.GetValue(null);
            ConsoleInput  input  = (ConsoleInput)fiInput.GetValue(null);
            bool          cancel = false;

            ServerEvents.RunConsoleOutput(ref text, ref color, ref cancel);
            if (cancel)
            {
                return;
            }
            if (output == null)
            {
                Debug.Log(text);
                return;
            }
            Console.ForegroundColor = color;
            if (Console.CursorLeft != 0)
            {
                input.clearLine();
            }
            Console.WriteLine(text);
            input.redrawInputLine();
        }
        public void Start()
        {
            int n;
            int m;

            n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            m = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            List <int>[] adj     = new List <int> [n];
            bool[]       visited = new bool[n];
            for (int i = 0; i < n; i++)
            {
                adj[i] = new List <int>();
            }

            for (int i = 0; i < m; i++)
            {
                int x;
                int y;
                x = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
                y = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
                adj[x - 1].Add(y - 1);
            }
            Console.Write(NumberOfStronglyConnectedComponents(adj));
        }
예제 #14
0
    static int Main()
    {
        int l;
        int w;
        int h;

        initWarehouse();
        while (true)
        {
            //Prompts user for length and width
            Console.Write("please enter length ");
            l = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            if (l == -1)
            {
                break;
            }

            Console.Write("please enter width ");
            w = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            if (w == -1)
            {
                break;
            }

            Console.Write("please enter height ");
            h = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            if (h == -1)
            {
                break;
            }

            addItem(l, w, h);
            printWarehouse();
        }
        return(0);
    }
예제 #15
0
        private void HandleMainMenuInput(ConsoleInput message)
        {
            switch (message.Input)
            {
            case "w":
                Become(WithdrawalState);
                _console.Tell(
                    new ConsoleOutput(
                        new[] {
                    "WITHDRAWAL!!!",
                    "PLEASE ENTER AMOUNT..."
                },
                        clear: true,
                        boxed: true,
                        padding: 10));
                break;

            case "d":
                Become(DepositState);
                _console.Tell(
                    new ConsoleOutput(
                        new[] {
                    "DEPOSIT!!!",
                    "PLEASE ENTER AMOUNT..."
                },
                        clear: true,
                        boxed: true,
                        padding: 10));
                break;

            default:
                _console.Tell(MakeMainMenuScreenMessage());
                _console.Tell("What!? Try again...");
                break;
            }
        }
예제 #16
0
        static int Main(string[] args)
        {
            Solution myTree = new Solution();
            Node     root   = null;

            int t;
            int data;

            t = int.Parse(ConsoleInput.ReadToWhiteSpace(true));

            while (t-- > 0)
            {
                data = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
                root = myTree.insert(root, data);
            }

            Console.WriteLine(myTree.count(root));
            Console.WriteLine(myTree.preOrder(root).ToArray <int>());
            Console.WriteLine(myTree.inOrder(root).ToArray <int>());
            Console.WriteLine(myTree.postOrder(root).ToArray <int>());
            //Console.WriteLine(myTree.count(root));

            return(0);
        }
        static void Main()
        {
            List <Employee> managers = new List <Employee>
            {
                new Employee("William Worker", decimal.Zero),
                new Employee("Mary Manager", new decimal(1000)),
                new Employee("Victor Vicepres", new decimal(5000)),
                new Employee("Paula President", new decimal(20000)),
            };

            decimal expenseReportAmount;

            while (ConsoleInput.TryReadDecimal("Expense report amount:", out expenseReportAmount))
            {
                IExpenseReport expense = new ExpenseReport(expenseReportAmount);

                bool expenseProcessed = false;

                foreach (Employee approver in managers)
                {
                    ApprovalResponse response = approver.ApproveExpense(expense);

                    if (response != ApprovalResponse.BeyondApprovalLimit)
                    {
                        Console.WriteLine("The request was {0}.", response);
                        expenseProcessed = true;
                        break;
                    }
                }

                if (!expenseProcessed)
                {
                    Console.WriteLine("No one was able to approve your expense.");
                }
            }
        }
        public void Start()
        {
            int n;
            int m;

            n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            m = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
            List <int>[] adj = new List <int> [n];
            for (int i = 0; i < n; i++)
            {
                adj[i] = new List <int>();
            }

            for (int i = 0; i < m; i++)
            {
                int x;
                int y;
                x = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
                y = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
                adj[x - 1].Add(y - 1);
                adj[y - 1].Add(x - 1);
            }
            Console.Write(bipartite(adj));
        }
예제 #19
0
 public void LoadContent(ConsoleInput input)
 {
     _input = input;
 }
        public void ConsoleInputTestIfSettingWorks()
        {
            var newConsoleInput = new ConsoleInput(10);

            Assert.IsTrue(newConsoleInput != null);
        }
예제 #21
0
 public static void Main()
 {
     ConsoleInput.Begin();
 }
예제 #22
0
 public void LoadContent(ConsoleInput input)
 {
     _input = input;
     _input.InputChanged += (s, e) => CheckRepeatingProcess();
     _input.Caret.Moved  += (s, e) => CheckRepeatingProcess();
 }
        private static void AssignEvents(GameEngine engine, ConsoleInput movement)
        {
            movement.OnWriteL += (sender, eventInfo) => engine.MoveAtDirection(Direction.Left, engine.MoveLeft);
            movement.OnWriteR += (sender, eventInfo) => engine.MoveAtDirection(Direction.Right, engine.MoveRight);
            movement.OnWriteU += (sender, eventInfo) => engine.MoveAtDirection(Direction.Up, engine.MoveUp);
            movement.OnWriteD += (sender, eventInfo) => engine.MoveAtDirection(Direction.Down, engine.MoveDown);

            movement.OnWriteTop += (sender, eventInfo) => engine.ShowTopResults();
            movement.OnWriteRestart += (sender, eventInfo) => engine.InitializeNewGame();
            movement.OnWriteExit += (sender, eventInfo) => engine.QuitGame();

            //Assert.AreSame(movement.OnWriteL == movement.OnWriteL);
        }
예제 #24
0
        /// <summary>
        /// Reads a line of input text from the underlying console.
        /// </summary>
        /// <returns>The line of text, or null if the end of input was
        /// encountered.</returns>
        public string ReadLine()
        {
            var cursorWasVisible = ConsoleOutput.CursorVisible;
            var ctrlCWasInput    = ConsoleInput.TreatControlCAsInput;

            try
            {
                ConsoleInputOperationResult consoleKeyResult;

                ConsoleOutput.CursorVisible       = true;
                ConsoleInput.TreatControlCAsInput = true;

                UpdateCursorSize();

                do
                {
                    // Grab a new key press event.
                    var key = ConsoleInput.ReadKey(true);

#if VERBOSE
                    // Log information about the key press.
                    LogKey(key);
#endif

                    // Process the event.
                    try
                    {
                        consoleKeyResult = ProcessKey(key);
                    }
                    catch (NotImplementedException)
                    {
                        consoleKeyResult = ConsoleInputOperationResult.Normal;
                    }
                }while (consoleKeyResult == ConsoleInputOperationResult.Normal);

                switch (consoleKeyResult)
                {
                case ConsoleInputOperationResult.EndOfInputStream:
                    return(null);

                case ConsoleInputOperationResult.EndOfInputLine:
                    ConsoleOutput.WriteLine(string.Empty);
                    break;
                }

                var result = LineInput.Contents;

                // Add to history.
                LineInput.SaveToHistory();

                // Reset temporary state
                LineInput.ClearLine(true);

                return(result);
            }
            finally
            {
                ConsoleOutput.CursorVisible       = cursorWasVisible;
                ConsoleInput.TreatControlCAsInput = ctrlCWasInput;
                ConsoleOutput.CursorSize          = _defaultCursorSize;
            }
        }
예제 #25
0
 public void LoadContent(ConsoleInput console) => _input = console;
예제 #26
0
 public override void Tick()
 {
     ConsoleInput.Tick();
     m_context.net.Tick();
     m_context.ipc.Tick();
 }
예제 #27
0
        public static void Main()
        {
            var numbers = ConsoleInput.TakeInput(new List<int>());
            LongestSubSequence((List<int>)numbers);

        }
예제 #28
0
 public bool Compile(ConsoleInput input)
 {
     throw new NotImplementedException();
 }
예제 #29
0
 public override bool WantCard()
 {
     return(ConsoleInput.GetBool("Another card? "));
 }
예제 #30
0
        private static int Main(string[] args)
        {
            _cliArgs = new CliArgs();
            if (!CommandLineParser.ParseArguments(args, _cliArgs))
            {
                string usage = CommandLineParser.ArgumentsUsage(typeof(CliArgs));
                Console.WriteLine(usage);
                return 5;
            }

            string hostname = _cliArgs.Hostname;
            IStatementReader statementInput = new ConsoleInput(hostname);
            if (null != _cliArgs.File)
            {
                statementInput = new FileInput(_cliArgs.File);
            }

            try
            {
                var statementReader = new StatementSplitter(statementInput);
                Run(hostname, statementReader);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error {0}", ex);
                return 5;
            }

            return 0;
        }
 public override void HandleConsoleInput(ConsoleInput input)
 {
     GameInstance.GetModule<Console>().Output("Received");
 }
예제 #32
0
 public void Dispose()
 {
     ConsoleInput.Dispose();
     ConsoleOutput.Dispose();
     ConsoleError.Dispose();
 }
예제 #33
0
        public static StreamReader GetStdInAsStreamReader()
        {
            string input = ConsoleInput.ReadToEnd();

            return(GetStreamReaderFromString(input));
        }
예제 #34
0
        // $G$ CSS-999 (-3) You should have used constants here.
        // $G$ DSN-999 (-5) this method is to long - should be divided to several methods
        // $G$ CSS-999 (-5) main should be short and not interactive with the user
        public static void Main()
        {
            Console.Title           = "בול פגיעה";
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Black;
            bool playerWantsToStartANewGame = true;

            while (playerWantsToStartANewGame)
            {
                Console.WriteLine("How many tries (between 4 to 10)?");
                Console.Write("Answer: ");
                byte numberOfRetries = readNumberOfRetries();
                s_BoardRows = new TuringMachine <BoardRow>(numberOfRetries, new BoardRow("         ", "       "));
                BulPegia.GenerateRandomPassword();
                string guess = null;
                long   headMovement;
                do
                {
                    Screen.Clear();
                    Console.WriteLine("Current board status:" + Environment.NewLine);
                    writeBoard();
                    if (guess != BulPegia.Password)
                    {
                        Console.WriteLine("Enter next guess (4 letters between A to H) or 'Q' to quit");
                        guess        = readGuess();
                        headMovement = (long)BulPegia.AppendNewRowToBoard(
                            guess,
                            delegate(string i_pin, string i_result)
                        {
                            return(s_BoardRows.Write(new BoardRow(i_pin, i_result)));
                        });
                    }
                    else
                    {
                        BulPegia.PlayerSuccessfullyGuessedPassword(Console.WriteLine, (byte)currentBoardRowIndex);
                        goto askPlayerIfHeOrSheWouldLikeToStartANewGame;
                    }
                }while (headMovement == 1);
                Screen.Clear();
                Console.WriteLine("Current board status:" + Environment.NewLine);
                const bool v_WritePassword = true;
                writeBoard(v_WritePassword);
                if (guess == BulPegia.Password)
                {
                    BulPegia.PlayerSuccessfullyGuessedPassword(Console.WriteLine, BulPegia.k_PasswordLength);
                    goto askPlayerIfHeOrSheWouldLikeToStartANewGame;
                }

                Console.WriteLine(BulPegia.k_LossMessage);
askPlayerIfHeOrSheWouldLikeToStartANewGame:
                Console.WriteLine(BulPegia.k_YesNoQuestionAboutStartingANewGame + " (Y/N)");
                const bool v_intercept = true;
                switch (ConsoleInput.ReadKey(isInvalidKey, not(v_intercept)).KeyChar)
                {
                case 'y':
                case 'Y':
                    playerWantsToStartANewGame = true;
                    Screen.Clear();
                    break;

                case 'n':
                case 'N':
                    playerWantsToStartANewGame = false;
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine(BulPegia.k_GoodByeMessage);
                    Console.WriteLine(k_PressAnyKeyToExitMessage);
                    Console.ReadKey(v_intercept);
                    break;

                default: throw new UnreachableCodeReachedException();
                }
            }
        }
예제 #35
0
        public static void DoExercises()
        {
            string exercise = "";

            while (exercise != "q")
            {
                Console.WriteLine("Exercise n°?");
                exercise = Console.ReadLine();
                ConsoleOutput.Title(exercise);

                #region Exercise 1

                if (exercise == "1")
                {
                    int[] myArray = new int[20];

                    for (int i = 0; i < myArray.Length; i++)
                    {
                        myArray[i] = i * 5;

                        Console.Write("{0}{1}", myArray[i], (i < myArray.Length - 1) ? ", " : ("." + Environment.NewLine));
                    }
                }

                #endregion Exercise 1

                #region Exercise 2

                if (exercise == "2")
                {
                    double[][] arrays = new double[2][];

                    List <double>[] bufferLists = new List <double> [2];

                    bufferLists[0] = new List <double>();

                    bufferLists[1] = new List <double>();

                    Console.WriteLine("Input numbers to be put into an array. When you're finished press {Enter} to fill a second array");
                    for (int c = 0; c <= 1;)
                    {
                        Console.WriteLine(c == 0 ? "First array:" : "Second array");
                        double input;
                        while (true)
                        {
                            string inputStr = Console.ReadLine();
                            if (Double.TryParse(inputStr, out input))
                            {
                                bufferLists[c].Add(input);
                            }
                            else if (inputStr == "")
                            {
                                arrays[c] = new double[bufferLists[c].Count];
                                //copy list to array
                                for (int i = 0; i < arrays[c].Length; i++)
                                {
                                    arrays[c][i] = bufferLists[c][i];
                                }
                                c++;
                                break;
                            }
                            else
                            {
                                Console.WriteLine("input a real number please");
                            }
                        }
                    }
                    Console.Write("The two arrays");

                    if (arrays[0].IsEqualTo(arrays[1]))
                    {
                        Console.Write(" are equal\n");
                    }
                    else
                    {
                        Console.Write(" aren't equal\n");
                    }

                    //Equality test
                    //if (arrays[0].Length != arrays[1].Length)
                    //	Console.Write(" aren't equal\n");
                    //else
                    //{
                    //	bool equal = true;
                    //	for (int i = 0; i < arrays[0].Length; i++)
                    //	{
                    //		if (arrays[0][i] != arrays[1][i])
                    //		{
                    //			Console.Write(" aren't equal\n");
                    //			equal = false;
                    //			break;
                    //		}
                    //	}
                    //	if (equal)
                    //	{
                    //		Console.Write(" are equal\n");
                    //	}
                    //}
                }

                #endregion Exercise 2

                #region Exercise 3

                if (exercise == "3")
                {
                    Console.WriteLine("Input 2 words to sort alphabetically");
                    string[] inputs = new string[] { Console.ReadLine(), Console.ReadLine() };
                    if (inputs[0] == inputs[1])
                    {
                        Console.WriteLine("The words are the same.");
                    }
                    else
                    {
                        Console.Write(inputs[0]);
                        if (inputs[0].ComesFirst(inputs[1]))
                        {
                            Console.Write(" comes before ");
                        }
                        else
                        {
                            Console.Write(" comes after ");
                        }
                        Console.Write(inputs[1] + Environment.NewLine);
                    }
                }

                #endregion Exercise 3

                #region Exercise 4

                if (exercise == "4")
                {
                    Console.WriteLine("Input integers to put in an array, separated by commas");
                    int[] nums         = ConsoleInput.ReadIntArrayCommaSeparated();
                    int[] seriesLength = new int[nums.Length];
                    seriesLength.Fill(1);
                    //Series check
                    for (int i = 1; i < nums.Length; i++)
                    {
                        if (nums[i] == nums[i - 1])
                        {
                            seriesLength[i] = seriesLength[i - 1] + 1;
                        }
                    }

                    int   iB     = seriesLength.Biggest();
                    int[] series = new int[seriesLength[iB]];
                    series.Fill(nums[iB]);
                    Console.WriteLine("The biggest series of consecutive integers in this array is :");
                    series.Print(false, ", ");
                    Console.Write(Environment.NewLine);
                }

                #endregion Exercise 4

                #region Exercise 5

                if (exercise == "5")
                {
                    Console.WriteLine("Input integers to put in an array, separated by commas");
                    int[] nums         = ConsoleInput.ReadIntArrayCommaSeparated();
                    int[] seriesLength = new int[nums.Length];
                    seriesLength.Fill(1);
                    for (int i = 1; i < nums.Length; i++)
                    {
                        if (nums[i] == nums[i - 1] + 1)
                        {
                            seriesLength[i] = seriesLength[i - 1] + 1;
                        }
                    }
                    int   biggestSeriesEndIndex = seriesLength.Biggest();
                    int[] series = new int[seriesLength[biggestSeriesEndIndex]];
                    //Let's fill the series array with values copied from the original one
                    for (int i = 0; i < seriesLength[biggestSeriesEndIndex]; i++)
                    {
                        series[i] = nums[biggestSeriesEndIndex - seriesLength[biggestSeriesEndIndex] + i + 1];
                    }

                    Console.WriteLine("The biggest series of consecutively increasing integers is :");
                    series.Print(false, ", ");
                    Console.Write(Environment.NewLine);
                }

                #endregion Exercise 5

                #region Exercise 6

                if (exercise == "6")
                {
                    Console.WriteLine("Input integers separated by commas to put into an array");
                    int[] nums       = ConsoleInput.ReadIntArrayCommaSeparated();
                    int[] numsMarked = new int[nums.Length];
                    for (int i = 0; i < nums.Length - 1; i++)
                    {
                        if (numsMarked[i] == 0)
                        {
                            for (int c = i + 1, lastGood = c - 1; c < nums.Length - i; c++)
                            {
                                if (numsMarked[c] == 0 && nums[c] == nums[lastGood] + 1)
                                {
                                    numsMarked[c] = numsMarked[lastGood] + 1;
                                    lastGood      = c;
                                }
                            }
                        }
                    }
                    int   biggestSeriesIndex = numsMarked.Biggest();
                    int[] series             = new int[numsMarked[biggestSeriesIndex] + 1];
                    Console.WriteLine("numsMarked[biggestSeriesIndex] = " + numsMarked[biggestSeriesIndex] + "   biggestSeriesIndex = " + biggestSeriesIndex);                    //DEBUG
                    for (int i = series.Length - 1, n = nums[biggestSeriesIndex]; i >= 0; i--, n--)
                    {
                        series[i] = n;
                    }
                    Console.WriteLine("The biggest series of (not necessary consecutive) increasing integers is :");
                    series.Print(false, ", ");
                    Console.Write(Environment.NewLine);
                }

                #endregion Exercise 6

                #region Exercise 7

                if (exercise == "7")
                {
                    Console.WriteLine("Input integers separated by commas to put into an array");
                    int[] nums = ConsoleInput.ReadIntArrayCommaSeparated();
                    Console.WriteLine("Input a number K (K < {0}), the program will find the series of integers of length K with the maximum sum.", nums.Length);
                    int   k    = ConsoleInput.ReadInt(0, nums.Length);
                    int[] sums = new int[nums.Length];
                    for (int i = 0; i < nums.Length - k; i++)
                    {
                        int sum = nums[i];
                        for (int s = 1; s <= k; s++)
                        {
                            sum += nums[s];
                        }
                        sums[i] = sum;
                    }
                    int   biggestSumStartIndex = sums.Biggest();
                    int[] series = new int[k];
                    for (int i = biggestSumStartIndex, c = 0; i < biggestSumStartIndex + k; i++, c++)
                    {
                        series[c] = nums[i];
                    }
                    Console.WriteLine("The series of {0} consecutive integers with the biggest sum is:", k);
                    series.Print(false, ", ");
                    Console.Write(Environment.NewLine);
                }

                #endregion Exercise 7

                #region Exercise 8

                if (exercise == "8")
                {
                    for (string input = ""; input != "q";)
                    {
                        Console.WriteLine("Select an array to sort using a \"selection\" sort algorithm: (\"q\" to quit)");
                        Console.Write("1. {");
                        testIntArrays[0].Print(false, ", ");
                        Console.Write("}" + Environment.NewLine);
                        Console.Write("2. {");
                        testIntArrays[1].Print(false, ", ");
                        Console.Write("}" + Environment.NewLine);
                        Console.WriteLine("3. Input array");
                        int[] array;
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            array = testIntArrays[0].Sort(SortOption.Selection);
                            break;

                        case "2":
                            array = testIntArrays[1].Sort(SortOption.Selection);
                            break;

                        case "3":
                            Console.WriteLine("Input integers separated by commas:");
                            array = ConsoleInput.ReadIntArrayCommaSeparated();
                            array.Sort(SortOption.Selection);
                            break;

                        default:
                            array = new int[] { 0 };
                            break;
                        }
                        if (input != "q")
                        {
                            Console.Write("Sorted array: {");
                            array.Print(false, ", ");
                            Console.Write("}" + Environment.NewLine);
                        }
                    }
                }

                #endregion Exercise 8

                #region Exercise 9

                if (exercise == "9")
                {
                    for (string input = ""; input != "q" && input != "quit";)
                    {
                        Console.WriteLine("Select an array in which to find the subsequence of maximal sum:");
                        ArraysExercises.PrintArraySelection();
                        int[] array;
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            array = testIntArrays[0].MaxSumSubsequence();
                            break;

                        case "2":
                            array = testIntArrays[1].MaxSumSubsequence();
                            break;

                        case "3":
                            array = testIntArrays[2].MaxSumSubsequence();
                            break;

                        case "4":
                            array = testIntArrays[3].MaxSumSubsequence();
                            break;

                        case "5":
                            Console.WriteLine("Input integers separated by commas:");
                            array = ConsoleInput.ReadIntArrayCommaSeparated();
                            array = array.MaxSumSubsequence();
                            break;

                        default:
                            array = null;
                            break;
                        }
                        if (input != "q" && array != null)
                        {
                            Console.Write("Maximal sum subsequence: {");
                            array.Print(false, ", ");
                            Console.WriteLine("}" + Environment.NewLine);
                        }
                    }
                }

                #endregion Exercise 9

                #region Exercise 10

                if (exercise == "10")
                {
                    for (string input = ""; input != "quit" && input != "q";)
                    {
                        Console.WriteLine("Select an array in which to find the most frequently occuring value:");
                        ArraysExercises.PrintArraySelection();
                        int mostFrequentValue = Int32.MinValue;
                        int frequency         = 0;
                        Console.Write("> ");
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            mostFrequentValue = testIntArrays[0].MostFrequentValue(out frequency);
                            break;

                        case "2":
                            mostFrequentValue = testIntArrays[1].MostFrequentValue(out frequency);
                            break;

                        case "3":
                            mostFrequentValue = testIntArrays[2].MostFrequentValue(out frequency);
                            break;

                        case "4":
                            mostFrequentValue = testIntArrays[3].MostFrequentValue(out frequency);
                            break;

                        case "5":
                            mostFrequentValue = ConsoleInput.ReadIntArrayCommaSeparated().MostFrequentValue(out frequency);
                            break;

                        default:
                            mostFrequentValue = 0;
                            break;
                        }
                        Console.WriteLine("The most frequent value in the array appears {1} and is: {0}", mostFrequentValue, frequency > 1 ? frequency + " times" : "once");
                    }
                }

                #endregion Exercise 10

                #region Exercise 11

                if (exercise == "11")
                {
                    for (string input = ""; input != "quit" && input != "q";)
                    {
                        Console.WriteLine("Input an integer number:");
                        int sum = ConsoleInput.ReadInt();
                        Console.WriteLine("Select an array in which to find a series of consecutive integers with a sum of {0}:", sum);
                        ArraysExercises.PrintArraySelection();
                        int[] neighbors;
                        Console.Write("> ");
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            neighbors = testIntArrays[0].ConsecutiveWithSum(sum);
                            break;

                        case "2":
                            neighbors = testIntArrays[1].ConsecutiveWithSum(sum);
                            break;

                        case "3":
                            neighbors = testIntArrays[2].ConsecutiveWithSum(sum);
                            break;

                        case "4":
                            neighbors = testIntArrays[3].ConsecutiveWithSum(sum);
                            break;

                        case "5":
                            neighbors = ConsoleInput.ReadIntArrayCommaSeparated().ConsecutiveWithSum(sum);
                            break;

                        default:
                            neighbors = new int[0];
                            break;
                        }
                        if (neighbors.Length == 0)
                        {
                            Console.WriteLine("The array you chose doesn't contain any consecutive numbers with a sum of {0}", sum);
                        }
                        else
                        {
                            Console.Write("The series of numbers{0}{{", Environment.NewLine);
                            neighbors.Print(false, ", ");
                            Console.WriteLine("}}{1}has a sum of {0}.", sum, Environment.NewLine);
                        }
                    }
                }

                #endregion Exercise 11

                #region Exercise 12

                if (exercise == "12")
                {
                    Console.WriteLine("Input 1 or 2 numbers corresponding to the X and Y values of a square matrix");
                    int[] input = ConsoleInput.ReadIntArrayCommaSeparated(2);
                    int[] xy    = new int[2];
                    if (input.Length == 1)
                    {
                        xy[0] = xy[1] = input[0];
                    }
                    else
                    {
                        xy[0] = input[0];
                        xy[1] = input[1];
                    }
                    for (int i = 1; i <= 4; i++)
                    {
                        Console.WriteLine((PrintOrder)i + "/");
                        PrintSeriesMatrix2D(xy[0], xy[1], (PrintOrder)i);
                    }
                }

                #endregion Exercise 12

                #region Exercise 13

                if (exercise == "13")
                {
                    int[,] matrix         = Random2dMatrix(8, maxValue: 26);
                    int[,] maxSumPlatform = matrix.MaxSumPlatform(3);
                    matrix.Print(highlight: maxSumPlatform);
                }

                #endregion Exercise 13

                #region Exercise 14

                if (exercise == "14")
                {
                    int[,] matrix2d = Random2dMatrix(9, maxValue: 4);
                    matrix2d.Print();
                    Console.WriteLine("...........................");
                    int[,] matrix2dLongestSequence = matrix2d.LongestSequence();
                    Console.WriteLine("The longest sequence of equal values in this matrix is {0} consecutive {1}", matrix2dLongestSequence.GetLength(1), matrix2d[matrix2dLongestSequence[0, 0], matrix2dLongestSequence[1, 0]]);
                    Console.WriteLine("...........................");
                    Console.WriteLine("[x, y] indices:");
                    matrix2dLongestSequence.SwapSlices(1, 0, 1).Print(swapXY: true, highlight: new int[, ] {
                        { 0, 0 }, { matrix2dLongestSequence.GetLength(0) - 1, matrix2dLongestSequence.GetLength(1) - 1 }
                    });
                }

                #endregion Exercise 14

                #region Exercise 15

                if (exercise == "15")
                {
                    Console.WriteLine("Input a word:");
                    char[] letters = ConsoleInput.ReadWordToCharArray(true);
                    Console.WriteLine("Letters position in alphabet:");
                    string numbers       = "";
                    string lettersString = "";
                    for (int i = 0, l = letters.Length; i < l; i++)
                    {
                        numbers       += String.Format("[ {0, -2}]", (int)Char.ToLower(letters[i]) - 96);
                        lettersString += String.Format("{0}", letters[i]);
                    }
                    ConsoleOutput.PrintSuperposed(lettersString, numbers, 1, 5);                    //BUGGED
                }

                #endregion Exercise 15

                #region Exercise 16

                //if (exercise == "16")
                //{
                //	int max = 50;
                //	Console.WriteLine("Enter an integer i (0 <= i <= {0})", max);
                //	int num = ConsoleInput.ReadInt(0, max);
                //	Console.WriteLine("Let's try to find it in a series of random sorted arrays using binary search");
                //	for (int c = 1; c <= 10; c++)
                //	{
                //		int[] array = new int[20];
                //		array = ArraysExercises.RandomIntArray(20, 0, 100);
                //		array.Sort();
                //		for (int i = 0, arrayLength = array.Length; i < arrayLength; i++)
                //		{
                //			Console.Write("{0, 2}{1}", array[i], i == arrayLength - 1 ? "" : ", ");
                //		}
                //		Console.WriteLine();
                //		int numI = array.Search(num, SearchOption.Binary);
                //		if (numI == -1)
                //		{
                //			Console.WriteLine();
                //		}
                //		else {
                //			string leftPadding = numI > 0 ? new string(' ', numI * 4 - 1) : "";
                //			Console.WriteLine(leftPadding + (numI == 0 ? "/\\_" : "_/\\_"));
                //		}
                //	}
                //}

                #endregion Exercise 16

                #region Test

                if (exercise == "test")
                {
                    for (int c = 0; c < 5; c++)
                    {
                        Console.Write("\n>");
                        int[] randA = RandomIntArray(13);
                        randA.Print(false, ", ");
                        Console.Write("\n]");
                        randA.Sort().Print(false, ", ");
                        Console.WriteLine();
                    }
                }

                #endregion Test
            }
        }
예제 #36
0
        public static void Main()
        {
            var numbers = ConsoleInput.TakeInput(new List <int>());

            NumberThatOccurOddNumberOfTimes((List <int>)numbers);
        }