Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- public class Program
- {
- public class WordPos
- {
- public string Type { get; set; }
- public int Pos { get; set; }
- }
- public static int GetShortDistance(string[] words, string word1, string word2)
- {
- int min = int.MaxValue; int posWord1 = -1; int posWord2 = -1;
- var wordPosList = new List<WordPos>();
- // формируем список, связывающий слова с позицией в массиве
- for (int i = 0; i < words.Length; i++)
- {
- string currentWord = words[i];
- if (currentWord == word1)
- {
- wordPosList.Add(new WordPos { Type = "word1", Pos = i });
- }
- if (currentWord == word2)
- {
- wordPosList.Add(new WordPos { Type = "word2", Pos = i });
- }
- }
- // находим минимальное расстояние между позициями с разными типами (первое и второе слово)
- foreach (var wordPos in wordPosList)
- {
- posWord1 = wordPos.Type == "word1" ? wordPos.Pos : posWord1;
- posWord2 = wordPos.Type == "word2" ? wordPos.Pos : posWord2;
- if (posWord1 > -1 && posWord2 > -1 && posWord1 != posWord2
- && min > Math.Abs(posWord1 - posWord2) - 1)
- {
- min = Math.Abs(posWord1 - posWord2) - 1;
- }
- }
- return min != int.MaxValue ? min : -1;
- }
- public static void Main()
- {
- Console.WriteLine("UniLecs");
- var words = new[] { "1", "4", "3", "4", "5" };
- Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "4", "5")); // 0
- Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "1", "4")); // 0
- Console.WriteLine("Минимальное расстояние: {0}", GetShortDistance(words, "4", "4")); // 1
- }
- }
Add Comment
Please, Sign In to add comment