-
-
Save VegaFromLyra/6dfae910ae995435d90b to your computer and use it in GitHub Desktop.
Sort words and numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
// Given a string containing a combination of words and numbers, sort the string | |
// such that the words and numbers maintain their position in the string | |
// Input: car 2 bus 1 | |
// Output: bus 1 car 2 | |
namespace SortWordsAndNumbers | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
test("car 2 bus 1"); | |
test("zebra 5 8 9 ace boo 2"); | |
} | |
static void test(string s) { | |
Console.WriteLine("Input: {0}", s); | |
Console.WriteLine("Output: {0}", sort(s)); | |
} | |
static string sort(string input) { | |
if (String.IsNullOrEmpty(input)) { | |
return input; | |
} | |
var inputs = input.Split(' '); | |
var strings = new List<string>(); | |
var numbers = new List<int>(); | |
var stringMap = new bool[inputs.Length]; | |
for (int i = 0; i < inputs.Length; i++) { | |
int result = 0; | |
if (Int32.TryParse(inputs[i], out result)) { | |
numbers.Add(result); | |
} else { | |
strings.Add(inputs[i]); | |
stringMap[i] = true; | |
} | |
} | |
strings.Sort(); | |
numbers.Sort(); | |
int p = 0; | |
int q = 0; | |
var output = new string[inputs.Length]; | |
int current = 0; | |
while (current < output.Length) { | |
if (stringMap[current]) { | |
output[current++] = strings[p++]; | |
} else { | |
output[current++] = numbers[q++].ToString(); | |
} | |
} | |
return String.Join(" ", output); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment