Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Sandbox
  4. {
  5. internal class Program
  6. {
  7. private static void Main(string[] args)
  8. {
  9. Program p = new Program();
  10. Console.WriteLine(p.Start(args));
  11.  
  12. Console.WriteLine("\nPress <enter> to continue...");
  13. Console.ReadLine();
  14. }
  15.  
  16. public bool Start(string[] args)
  17. {
  18. /*
  19. How would you solve this problem optimizely?
  20. Rearrange characters in a string so that no character repeats twice.
  21. Input: aaabc
  22. Output: abaca
  23. Input: aa
  24. Output: No valid output
  25. Input: aaaabc
  26. Output: No valid output
  27. */
  28.  
  29. char[] input = "aaabc".ToCharArray();
  30. char temp;
  31. bool swapfound = false;
  32.  
  33. Console.WriteLine(input);
  34. for (int i = 0; i <= input.Length - 2; i++)
  35. {
  36. if (input[i] == input[i + 1]) // we have an adjacent match
  37. {
  38. swapfound = false;
  39.  
  40. for (int d = i + 2; d <= input.Length - 1; d++)
  41. {
  42. if (input[d] != input[i + 1]) // search for swappable character
  43. {
  44. // swap adjacent match with found swappable character
  45. temp = input[d];
  46. input[d] = input[i + 1];
  47. input[i + 1] = temp;
  48.  
  49. swapfound = true;
  50. }
  51. }
  52.  
  53. if (!swapfound)
  54. {
  55. Console.WriteLine(input);
  56. return false;
  57. }
  58. }
  59. }
  60.  
  61. Console.WriteLine(input);
  62. return true;
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement