Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using NUnit.Framework;
- namespace Autocomplete
- {
- internal class AutocompleteTask
- {
- public static string FindFirstByPrefix(IReadOnlyList<string> phrases, string prefix)
- {
- var index = LeftBorderTask.GetLeftBorderIndex(phrases, prefix, -1, phrases.Count) + 1;
- if (index < phrases.Count)
- return phrases[index];
- return null;
- }
- public static string[] GetTopByPrefix(IReadOnlyList<string> phrases, string prefix, int count)
- {
- if (FindFirstByPrefix(phrases, prefix) == null)
- {
- return new string[0];
- }
- var topByPrefix = new List<string>();
- var leftBorder = LeftBorderTask.GetLeftBorderIndex(phrases, prefix, -1, phrases.Count);
- var wordCount = 0;
- while (wordCount < count
- && leftBorder + wordCount + 1 < phrases.Count
- && phrases[leftBorder + wordCount + 1].StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
- {
- topByPrefix.Add(phrases[leftBorder + wordCount + 1]);
- wordCount++;
- }
- return topByPrefix.ToArray();
- }
- public static int GetCountByPrefix(IReadOnlyList<string> phrases, string prefix)
- {
- var rightBorder = RightBorderTask.GetRightBorderIndex(phrases, prefix, -1, phrases.Count);
- var leftBorder = LeftBorderTask.GetLeftBorderIndex(phrases, prefix, -1, phrases.Count);
- return rightBorder - leftBorder - 1;
- }
- }
- [TestFixture]
- public class AutocompleteTests
- {
- [Test]
- public void TopByPrefix_IsEmpty_WhenNoPhrases()
- {
- var receivedTopWords = AutocompleteTask.GetTopByPrefix(new string[] { }, "a", 10);
- CollectionAssert.IsEmpty(receivedTopWords);
- }
- [Test]
- public void TopByPrefix_IsNoEmpty_WhenExistPhrases()
- {
- var receivedTopWords = AutocompleteTask.GetTopByPrefix(new string[] { "a", "ab", "abc", "abcd" }, "c", 10);
- CollectionAssert.IsEmpty(receivedTopWords);
- }
- [Test]
- public void CountByPrefix_IsTotalCount_WhenEmptyPrefix()
- {
- var receivedlCount = AutocompleteTask.GetCountByPrefix(new string[] { "a", "ab", "abc", "abcd" }, "");
- Assert.AreEqual(4, receivedlCount);
- }
- [Test]
- public void CountByPrefix_IsTotalCount_WhenNoEmptyPrefix()
- {
- var receivedlCount = AutocompleteTask.GetCountByPrefix(new string[] { "a", "bb", "bbc", "abcd" }, "b");
- Assert.AreEqual(2, receivedlCount);
- }
- [Test]
- public void TopByPrefix_OneRecommendedWord()
- {
- var receivedlCount = AutocompleteTask.GetTopByPrefix(new string[] { "abc", "abcd", "adb" }, "adb", 10);
- CollectionAssert.AreEqual(new string[] { "adb" }, receivedlCount);
- }
- [Test]
- public void TopByPrefix_IsEmpty()
- {
- var receivedTopWords = AutocompleteTask.GetTopByPrefix(new string[] { "abc", "abcd", "adb" }, "d", 10);
- CollectionAssert.IsEmpty(receivedTopWords);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement