Created
October 22, 2017 10:23
-
-
Save unilecs/9b0d15d874c4e6ffd2685e4ed57d635d to your computer and use it in GitHub Desktop.
Найти минимальное расстояние между словами в тексте
This file contains 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; | |
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment