Guest User

Untitled

a guest
Oct 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Program
  5. {
  6. public class WordPos
  7. {
  8. public string Type { get; set; }
  9. public int Pos { get; set; }
  10. }
  11. public static int GetShortDistance(string[] words, string word1, string word2)
  12. {
  13. int min = int.MaxValue; int posWord1 = -1; int posWord2 = -1;
  14. var wordPosList = new List<WordPos>();
  15.  
  16. // формируем список, связывающий слова с позицией в массиве
  17. for (int i = 0; i < words.Length; i++)
  18. {
  19. string currentWord = words[i];
  20. if (currentWord == word1)
  21. {
  22. wordPosList.Add(new WordPos { Type = "word1", Pos = i });
  23. }
  24. if (currentWord == word2)
  25. {
  26. wordPosList.Add(new WordPos { Type = "word2", Pos = i });
  27. }
  28. }
  29.  
  30. // находим минимальное расстояние между позициями с разными типами (первое и второе слово)
  31. foreach (var wordPos in wordPosList)
  32. {
  33. posWord1 = wordPos.Type == "word1" ? wordPos.Pos : posWord1;
  34. posWord2 = wordPos.Type == "word2" ? wordPos.Pos : posWord2;
  35.  
  36. if (posWord1 > -1 && posWord2 > -1 && posWord1 != posWord2
  37. && min > Math.Abs(posWord1 - posWord2) - 1)
  38. {
  39. min = Math.Abs(posWord1 - posWord2) - 1;
  40. }
  41. }
  42.  
  43. return min != int.MaxValue ? min : -1;
  44. }
  45.  
  46. public static void Main()
  47. {
  48. Console.WriteLine("UniLecs");
  49. var words = new[] { "1", "4", "3", "4", "5" };
  50. Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "4", "5")); // 0
  51. Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "1", "4")); // 0
  52. Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "4", "4")); // 1
  53. }
  54. }
Add Comment
Please, Sign In to add comment